aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--INFO.yaml85
-rw-r--r--capabilities/pom.xml43
-rw-r--r--capabilities/src/main/java/org/onap/policy/common/capabilities/Configurable.java43
-rw-r--r--capabilities/src/main/java/org/onap/policy/common/capabilities/Startable.java15
-rw-r--r--common-logging/pom.xml73
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java15
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java59
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java41
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java30
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java15
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java8
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java6
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java12
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java379
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java18
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java80
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java181
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java33
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java514
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java8
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java22
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java212
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java9
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java7
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java7
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java26
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java7
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java22
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java121
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java69
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java70
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java350
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java31
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java17
-rw-r--r--common-parameters/pom.xml33
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java56
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java432
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java137
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/FieldValidator.java292
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java112
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java391
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ItemValidator.java71
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java4
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java24
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java19
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java17
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java30
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java19
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java36
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java32
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java22
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/ValueValidator.java146
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/ClassName.java37
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java5
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java5
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java5
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java5
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Pattern.java38
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Size.java (renamed from policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/FilterableTopicSource.java)34
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Valid.java35
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupConstraint.java57
-rw-r--r--common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupValidator.java (renamed from common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullSubGroup.java)31
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java3
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java65
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java664
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java379
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java121
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java57
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java93
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java183
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java117
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java143
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java142
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java54
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java83
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java31
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java40
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java44
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java36
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java47
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java47
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java46
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java41
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java47
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java208
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java189
-rw-r--r--common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java129
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt41
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt41
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt3
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt3
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt3
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt16
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt16
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt16
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt29
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt29
-rw-r--r--common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt29
-rw-r--r--gson/pom.xml123
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/DoubleConverter.java13
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/GsonMessageBodyHandler.java37
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/InstantAsMillisTypeAdapter.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafGranularAuthFilter.java)42
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/InstantTypeAdapter.java36
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/JacksonFieldAdapterFactory.java4
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/JacksonMethodAdapterFactory.java4
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/LocalDateTimeTypeAdapter.java39
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/LocalDateTypeAdapter.java35
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/MapDoubleAdapterFactory.java24
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/OffsetDateTimeTypeAdapter.java35
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/OffsetTimeTypeAdapter.java35
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/StringTypeAdapter.java76
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/ZoneOffsetTypeAdapter.java30
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafAuthFilter.java)44
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java46
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/internal/ClassWalker.java14
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/internal/FieldDeserializer.java12
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/internal/FieldSerializer.java7
-rw-r--r--gson/src/main/java/org/onap/policy/common/gson/internal/JacksonTypeAdapter.java9
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/DoubleConverterTest.java8
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/GsonMessageBodyHandlerTest.java54
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/InstantAsMillisTypeAdapterTest.java66
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/InstantTypeAdapterTest.java63
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java62
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java15
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/JacksonHandlerTest.java12
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java27
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/LocalDateTimeTypeAdapterTest.java72
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/LocalDateTypeAdapterTest.java73
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/MapDoubleAdapterFactoryTest.java7
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/OffsetDateTimeAdapterTest.java72
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/OffsetTimeTypeAdapterTest.java72
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/StringTypeAdapterTest.java94
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/ZoneOffsetTypeAdapterTest.java72
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapterTest.java63
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java17
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/internal/DataAdapterFactory.java15
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java10
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java6
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java9
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/internal/MethodAdapterTest.java11
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/internal/MethodDeserializerTest.java7
-rw-r--r--gson/src/test/java/org/onap/policy/common/gson/internal/MethodSerializerTest.java7
-rw-r--r--integrity-audit/pom.xml131
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java62
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java18
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java101
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java406
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java36
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java20
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java161
-rw-r--r--integrity-audit/src/main/resources/META-INF/persistence.xml51
-rw-r--r--integrity-audit/src/main/resources/logback.xml256
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java5
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java15
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/DbDaoTest.java25
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/DefaultLoggingPatternTest.java4
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java12
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java27
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java30
-rw-r--r--integrity-audit/src/test/resources/logback.xml262
-rw-r--r--integrity-monitor/pom.xml84
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java634
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java21
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java27
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java12
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java8
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java52
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java9
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java26
-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.java128
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java126
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java148
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java40
-rw-r--r--integrity-monitor/src/main/resources/META-INF/persistence.xml11
-rw-r--r--integrity-monitor/src/main/resources/logback.xml261
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/AllSeemsWellTest.java24
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTest.java127
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTestBase.java13
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementEntityTest.java9
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementTest.java303
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/StateTransitionTest.java4610
-rw-r--r--policy-endpoints/pom.xml217
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/Topic.java8
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpoint.java42
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointManager.java10
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java209
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicSink.java5
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSink.java7
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSource.java3
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactory.java105
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSourceFactory.java212
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSinkFactory.java (renamed from policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSinkFactory.java)127
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSourceFactory.java204
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSinkFactory.java12
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSourceFactory.java16
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicFactories.java (renamed from policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactories.java)18
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSink.java (renamed from policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSink.java)11
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkFactory.java (renamed from policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactory.java)61
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSource.java (renamed from policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSource.java)13
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceFactory.java88
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java18
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactories.java10
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactory.java12
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/TopicBaseHashedFactory.java4
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicFactories.java10
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java553
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java295
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBase.java48
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParams.java59
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSink.java74
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSink.java130
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSink.java82
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSink.java10
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSource.java72
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSource.java143
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSource.java79
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSource.java9
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBase.java60
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClient.java224
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientException.java53
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClient.java4
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientException.java5
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/features/NetLoggerFeatureProviders.java9
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClient.java82
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientConfigException.java4
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientFactoryInstance.java10
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/IndexedHttpClientFactory.java20
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/internal/JerseyClient.java181
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/AuthorizationFilter.java24
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServer.java50
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactory.java42
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactoryInstance.java11
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/IndexedHttpServletServerFactory.java114
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/JsonExceptionMapper.java21
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/RestServer.java87
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlExceptionMapper.java19
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlJacksonHandler.java9
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlMessageBodyHandler.java21
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/aaf/AafAuthFilter.java45
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/aaf/AafGranularAuthFilter.java48
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java74
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyServletServer.java209
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyStaticResourceServer.java107
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/JsonListener.java13
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcher.java6
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcher.java6
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/ScoListener.java15
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestClientParameters.java57
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestServerParameters.java11
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroup.java20
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/properties/PolicyEndPointProperties.java61
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/report/HealthCheckReport.java116
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/DmaapPropertyUtils.java121
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/KafkaPropertyUtils.java58
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/NetLoggerUtil.java19
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/PropertyUtils.java20
-rw-r--r--policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/UebPropertyUtils.java13
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java104
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java20
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactoryTestBase.java133
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicPropertyBuilder.java154
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicFactoryTestBase.java48
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicPropertyBuilder.java75
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkFactoryTest.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java)58
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkTest.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkTest.java)4
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceFactoryTest.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java)91
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceTest.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceTest.java)6
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpointTest.java3
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactoryTest.java6
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicFactoryTestBase.java10
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicTestBase.java46
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicPropertyBuilder.java22
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java305
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java128
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java5
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java16
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java4
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSinkTest.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java)29
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java8
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java52
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSourceTest.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.java)47
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.java6
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBaseTest.java19
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientTest.java452
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicClientExceptionTest.java (renamed from policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientExceptionTest.java)5
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java272
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java276
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java3
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java5
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyJacksonProvider.java85
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java5
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java12
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java39
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java13
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java15
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java130
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java3
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java11
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java3
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java15
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java15
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java4
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java47
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java7
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/CommonTestData.java8
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestServerParametersTest.java16
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroupTest.java18
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/report/TestHealthCheckReport.java2
-rw-r--r--policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/PropertyUtilsTest.java12
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.json37
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.json1
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.json1
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.json14
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSinkTest.json20
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.json1
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.json1
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.json17
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSourceTest.json19
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.json1
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/http/server/internal/HttpServerTest.json5
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_invalid.json3
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_valid.json3
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_all_params.json14
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_missing_mandatory.json10
-rw-r--r--policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_valid.json24
-rw-r--r--policy-endpoints/src/test/resources/webapps/alt-root/index.html30
-rw-r--r--policy-endpoints/src/test/resources/webapps/root/index.html30
-rw-r--r--pom.xml192
-rw-r--r--releases/1.10.0.yaml4
-rw-r--r--releases/1.10.1.yaml4
-rw-r--r--releases/1.10.2.yaml4
-rw-r--r--releases/1.10.3.yaml4
-rw-r--r--releases/1.11.0.yaml4
-rw-r--r--releases/1.11.1.yaml4
-rw-r--r--releases/1.12.0.yaml4
-rw-r--r--releases/1.12.1.yaml4
-rw-r--r--releases/1.12.2.yaml4
-rw-r--r--releases/1.6.2.yaml4
-rw-r--r--releases/1.6.3.yaml4
-rw-r--r--releases/1.6.4.yaml4
-rw-r--r--releases/1.6.5.yaml4
-rw-r--r--releases/1.7.0.yaml4
-rw-r--r--releases/1.7.1.yaml4
-rw-r--r--releases/1.8.0.yaml4
-rw-r--r--releases/1.9.0.yaml4
-rw-r--r--releases/1.9.1.yaml4
-rw-r--r--releases/2.0.1.yaml4
-rw-r--r--releases/2.0.2.yaml4
-rw-r--r--releases/2.1.0.yaml4
-rw-r--r--releases/2.1.1.yaml4
-rw-r--r--spring-utils/pom.xml50
-rw-r--r--spring-utils/src/main/java/org/onap/policy/common/spring/utils/CustomImplicitNamingStrategy.java (renamed from common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java)24
-rw-r--r--spring-utils/src/main/java/org/onap/policy/common/spring/utils/YamlHttpMessageConverter.java108
-rw-r--r--utils-test/pom.xml81
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java90
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java28
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java161
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java12
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java26
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java14
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java10
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java6
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java70
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java11
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java8
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java7
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java12
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java15
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java5
-rw-r--r--utils-test/src/main/resources/keystore_san.txt15
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java45
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java46
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java151
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java19
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java60
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java12
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java8
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java16
-rw-r--r--utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java5
-rw-r--r--utils/pom.xml115
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/cmd/CommandLineArgumentsHandler.java273
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/cmd/CommandLineException.java (renamed from common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java)42
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/coder/Coder.java46
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/coder/PropertyCoder.java20
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java135
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillis.java61
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderObject.java98
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/coder/StandardValCoder.java119
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/coder/StandardYamlCoder.java15
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/coder/YamlJsonTranslator.java58
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrCloser.java35
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloser.java35
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/jpa/EntityTransCloser.java37
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/logging/LoggerMarkerFilter.java98
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/logging/LoggerUtils.java105
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java64
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/properties/BeanConfigurator.java8
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/properties/PropertyObjectUtils.java242
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/properties/SpecProperties.java15
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/properties/exception/PropertyException.java43
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/resources/DirectoryUtils.java63
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/resources/MessageConstants.java43
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/resources/PrometheusUtils.java107
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/resources/ResourceUtils.java105
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/resources/TextFileUtils.java68
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java49
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/services/FeatureApiUtils.java13
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/services/OrderedServiceImpl.java19
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/services/Registry.java12
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/services/ServiceManager.java43
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/time/CurrentTime.java22
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/validation/Assertions.java11
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java10
-rw-r--r--utils/src/main/java/org/onap/policy/common/utils/validation/Version.java14
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java181
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/CoderTest.java129
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java25
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillisTest.java160
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java47
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java85
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java165
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java30
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java6
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java6
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java10
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java53
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java19
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java81
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java212
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java28
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java20
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java20
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java20
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java14
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java34
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java42
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java106
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java73
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java6
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java2
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java24
-rw-r--r--utils/src/test/resources/cmdFiles/configuration.json4
-rw-r--r--utils/src/test/resources/cmdFiles/property.json3
-rw-r--r--utils/src/test/resources/org/onap/policy/common/utils/coder/bad-regex.json9
-rw-r--r--utils/src/test/resources/org/onap/policy/common/utils/coder/missing-required.json5
-rw-r--r--utils/src/test/resources/org/onap/policy/common/utils/coder/test.schema.json71
-rw-r--r--utils/src/test/resources/org/onap/policy/common/utils/coder/valid.json9
-rw-r--r--utils/src/test/resources/version.txt1
-rw-r--r--version.properties4
450 files changed, 17411 insertions, 14012 deletions
diff --git a/INFO.yaml b/INFO.yaml
index 37e73ce2..74e00692 100644
--- a/INFO.yaml
+++ b/INFO.yaml
@@ -1,14 +1,14 @@
---
project: 'policy-common'
project_creation_date: '2017-02-14'
-lifecycle_state: 'Incubation'
+lifecycle_state: 'Mature'
project_category: ''
project_lead: &onap_releng_ptl
- name: 'Pamela Dragosh'
- email: 'pdragosh@research.att.com'
- id: 'pdragosh'
- company: 'ATT'
- timezone: 'America/New_York'
+ name: 'Liam Fallon'
+ email: 'liam.fallon@est.tech'
+ id: 'liamfallon'
+ company: 'Ericsson'
+ timezone: 'Europe/Ireland'
primary_contact: *onap_releng_ptl
issue_tracking:
type: 'jira'
@@ -26,51 +26,66 @@ meetings:
server: 'n/a'
channel: 'n/a'
repeats: 'weekly'
- time: '13:00 UTC'
+ time: '14:00 UTC'
repositories:
- - 'policy-apex-pdp'
- - 'policy-api'
- - 'policy-common'
- - 'policy-core'
- - 'policy-distribution'
- - 'policy-docker'
- - 'policy-drools-applications'
- - 'policy-drools-pdp'
- - 'policy-engine'
- - 'policy-gui'
- - 'policy-models'
- - 'policy-oom'
- - 'policy-pap'
- - 'policy-parent'
- - 'policy-pdp'
- - 'policy-xacml-pdp'
+ - 'policy/common'
committers:
- <<: *onap_releng_ptl
+ - name: 'Pamela Dragosh'
+ email: 'pd1248@att.com'
+ company: 'ATT'
+ id: 'pdragosh'
+ timezone: 'America/New_York'
- name: 'Jorge Hernandez'
email: 'jorge.hernandez-herrero@att.com'
company: 'ATT'
id: 'jhh'
timezone: 'America/Illinois'
- - name: 'Liam Fallon'
- email: 'liam.fallon@est.tech'
+ - name: 'Ram Krishna Verma'
+ email: 'ram_krishna.verma@bell.ca'
+ company: 'Bell Canada'
+ id: 'ramverma'
+ timezone: 'America/Montreal'
+ - name: 'Ramesh Murugan Iyer'
+ email: 'ramesh.murugan.iyer@est.tech'
company: 'Ericsson'
- id: 'liamfallon'
+ id: 'rameshiyer27'
timezone: 'Europe/Ireland'
- - name: 'Jim Hahn'
- email: 'jrh3@att.com'
- company: 'ATT'
- id: 'jrh3'
- timezone: 'America/New_York'
- - name: 'Ram Krishna Verma'
- email: 'ram.krishna.verma@est.tech'
+ - name: 'Adheli Tavares'
+ email: 'adheli.tavares@est.tech'
company: 'Ericsson'
- id: 'ramverma'
+ id: 'adheli.tavares'
timezone: 'Europe/Ireland'
tsc:
approval: 'https://lists.onap.org/pipermail/onap-tsc'
changes:
- type: 'Addition'
name: 'Jim Hahn'
+ link: https://lists.onap.org/g/onap-tsc/message/4976
+ - type: 'Addition'
name: 'Ram Krishna Verma'
link: https://lists.onap.org/g/onap-tsc/message/4977
- link: https://lists.onap.org/g/onap-tsc/message/4976
+ - type: 'Addition'
+ name: 'Ajith Sreekumar'
+ link: https://lists.onap.org/g/onap-tsc/message/6869
+ - type: 'Addition'
+ name: 'Jim Hahn'
+ # new PTL
+ link: https://lists.onap.org/g/onap-tsc/message/6754
+ - type: 'Addition'
+ name: 'Liam Fallon'
+ link: https://lists.onap.org/g/onap-tsc/message/8032
+ # Retired
+ - type: 'Removal'
+ name: 'Jim Hahn'
+ link: https://lists.onap.org/g/onap-tsc/message/8056
+ - type: 'Addition'
+ name: 'Ramesh Murugan Iyer'
+ link: https://lists.onap.org/g/onap-tsc/message/8689
+ # Stepped Down
+ - type: 'Removal'
+ name: 'Ajith Sreekumar'
+ link: https://lists.onap.org/g/onap-tsc/message/8878
+ - type: 'Addition'
+ name: 'Adheli Tavares'
+ link: https://lists.onap.org/g/onap-tsc/message/9296
diff --git a/capabilities/pom.xml b/capabilities/pom.xml
index 1d1e290c..e3ed2367 100644
--- a/capabilities/pom.xml
+++ b/capabilities/pom.xml
@@ -1,7 +1,7 @@
<!--
============LICENSE_START=======================================================
Copyright (C) 2018 Ericsson. All rights reserved.
- Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ Modifications Copyright (C) 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.
@@ -25,7 +25,7 @@
<parent>
<groupId>org.onap.policy.common</groupId>
<artifactId>common-modules</artifactId>
- <version>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
<artifactId>capabilities</artifactId>
@@ -33,44 +33,7 @@
<packaging>jar</packaging>
<properties>
- <!-- There is no code in this sub-module, only holds interfaces. So skip sonar. -->
+ <!-- There is no code in this submodule, only holds interfaces. So skip sonar. -->
<sonar.skip>true</sonar.skip>
</properties>
-
- <build>
- <pluginManagement>
- <plugins>
- <!--This plugin's configuration is used to store Eclipse
- m2e settings only. It has no influence on the Maven build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.jacoco</groupId>
- <artifactId>
- jacoco-maven-plugin
- </artifactId>
- <versionRange>
- [0.7.1.201405082137,)
- </versionRange>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
</project>
diff --git a/capabilities/src/main/java/org/onap/policy/common/capabilities/Configurable.java b/capabilities/src/main/java/org/onap/policy/common/capabilities/Configurable.java
new file mode 100644
index 00000000..97286744
--- /dev/null
+++ b/capabilities/src/main/java/org/onap/policy/common/capabilities/Configurable.java
@@ -0,0 +1,43 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.capabilities;
+
+/**
+ * Object that can be configured.
+ *
+ * @param <T> type of parameters
+ */
+public interface Configurable<T> {
+
+ /**
+ * Determines if this object has been configured.
+ *
+ * @return {@code true} if this object has been configured, {@code false} otherwise
+ */
+ boolean isConfigured();
+
+ /**
+ * Configures this object.
+ *
+ * @param parameters configuration parameters
+ */
+ void configure(T parameters);
+}
diff --git a/capabilities/src/main/java/org/onap/policy/common/capabilities/Startable.java b/capabilities/src/main/java/org/onap/policy/common/capabilities/Startable.java
index 49af75f8..0ce4da54 100644
--- a/capabilities/src/main/java/org/onap/policy/common/capabilities/Startable.java
+++ b/capabilities/src/main/java/org/onap/policy/common/capabilities/Startable.java
@@ -3,6 +3,7 @@
* policy-core
* ================================================================================
* Copyright (C) 2017-2018 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.
@@ -29,33 +30,33 @@ public interface Startable {
* Start operation. This operation starts the entity.
*
* @return boolean. true if the start operation was successful, otherwise false.
- * @throws IllegalStateException. if the element is in a state that conflicts with the start
+ * @throws IllegalStateException if the element is in a state that conflicts with the start
* operation.
*/
- public boolean start();
+ boolean start();
/**
* Stop operation. The entity can be restarted again by invoking the start operation.
*
* @return boolean. true if the stop operation was successful, otherwise false.
- * @throws IllegalStateException. if the element is in a state that conflicts with the stop
+ * @throws IllegalStateException if the element is in a state that conflicts with the stop
* operation.
*/
- public boolean stop();
+ boolean stop();
/**
* shutdown operation. The terminate operation yields the entity unusuable. It cannot be
* (re)started.
*
- * @throws IllegalStateException. if the element is in a state that conflicts with the stop
+ * @throws IllegalStateException if the element is in a state that conflicts with the stop
* operation.
*/
- public void shutdown();
+ void shutdown();
/**
* Checks if the entity is alive.
*
* @return boolean. true if alive, otherwise false
*/
- public boolean isAlive();
+ boolean isAlive();
}
diff --git a/common-logging/pom.xml b/common-logging/pom.xml
index 335af71b..1536f8e7 100644
--- a/common-logging/pom.xml
+++ b/common-logging/pom.xml
@@ -2,7 +2,8 @@
============LICENSE_START=======================================================
ONAP Policy Engine - Common Modules
================================================================================
- Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ 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.
@@ -24,7 +25,7 @@
<parent>
<groupId>org.onap.policy.common</groupId>
<artifactId>common-modules</artifactId>
- <version>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
<artifactId>ONAP-Logging</artifactId>
@@ -33,28 +34,9 @@
<dependencies>
<dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
<groupId>com.att.eelf</groupId>
<artifactId>eelf-core</artifactId>
- <version>1.0.1-oss</version>
+ <version>2.0.0-oss</version>
<exclusions>
<exclusion>
<groupId>org.powermock</groupId>
@@ -62,59 +44,14 @@
</exclusion>
</exclusions>
</dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito2</artifactId>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
<plugins>
<plugin>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>onap-java-style</id>
- <goals>
- <goal>check</goal>
- </goals>
- <phase>process-sources</phase>
- <configuration>
- <!-- Use Google Java Style Guide:
- https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml
- with minor changes -->
- <configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
- <!-- <sourceDirectory> is needed so that checkstyle ignores the generated sources directory -->
- <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
- <includeResources>true</includeResources>
- <includeTestSourceDirectory>true</includeTestSourceDirectory>
- <includeTestResources>true</includeTestResources>
- <excludes>
- </excludes>
- <consoleOutput>true</consoleOutput>
- <failsOnViolation>true</failsOnViolation>
- <violationSeverity>warning</violationSeverity>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.onap.oparent</groupId>
- <artifactId>checkstyle</artifactId>
- <version>${oparent.version}</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
- </plugin>
- <plugin>
<groupId>com.att.eelf</groupId>
<artifactId>eelf-maven-plugin</artifactId>
- <version>0.0.1</version>
+ <version>2.0.0-oss</version>
<executions>
<execution>
<phase>install</phase>
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
index 0373abfe..e457f5f3 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -24,7 +24,6 @@ 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;
@@ -144,7 +143,7 @@ public class OnapLoggingContext {
* with key "TransactionElapsedTime".
*/
public void transactionEnded() {
- Instant transactionEndTime = Instant.now();
+ var transactionEndTime = Instant.now();
setTransactionEndTimestamp(transactionEndTime);
setTransactionElapsedTime(transactionEndTime);
}
@@ -164,7 +163,7 @@ public class OnapLoggingContext {
* "MetricElapsedTime".
*/
public void metricEnded() {
- Instant metricEndTime = Instant.now();
+ var metricEndTime = Instant.now();
setMetricEndTimestamp(metricEndTime);
setMetricElapsedTime(metricEndTime);
}
@@ -450,7 +449,7 @@ public class OnapLoggingContext {
* @param transactionStartTime transaction start time
*/
public void setTransactionBeginTimestamp(Instant transactionStartTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(TRANSACTION_BEGIN_TIME_STAMP, sdf.format(Date.from(transactionStartTime)));
}
@@ -469,7 +468,7 @@ public class OnapLoggingContext {
* @param transactionEndTime transaction end time
*/
public void setTransactionEndTimestamp(Instant transactionEndTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(TRANSACTION_END_TIME_STAMP, sdf.format(Date.from(transactionEndTime)));
}
@@ -511,7 +510,7 @@ public class OnapLoggingContext {
* @param metricStartTime metric start time
*/
public void setMetricBeginTimestamp(Instant metricStartTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(METRIC_BEGIN_TIME_STAMP, sdf.format(Date.from(metricStartTime)));
}
@@ -530,7 +529,7 @@ public class OnapLoggingContext {
* @param metricEndTime metric end time
*/
public void setMetricEndTimestamp(Instant metricEndTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(METRIC_END_TIME_STAMP, sdf.format(Date.from(metricEndTime)));
}
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
index 6c0879ea..91133d1a 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,13 +21,16 @@
package org.onap.policy.common.logging;
-import javax.servlet.http.HttpServletRequest;
+import com.google.re2j.Pattern;
+import jakarta.servlet.http.HttpServletRequest;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
-public class OnapLoggingUtils {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class OnapLoggingUtils {
- private OnapLoggingUtils() {
- // Private constructor to prevent subclassing
- }
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
+ private static final Pattern CURLS_PAT = Pattern.compile("[{][}]");
/**
* Get the ONAPLoggingContext for a request.
@@ -36,8 +40,8 @@ public class OnapLoggingUtils {
* @return the ONAPLoggingContext
*/
public static OnapLoggingContext getLoggingContextForRequest(HttpServletRequest request,
- OnapLoggingContext baseContext) {
- OnapLoggingContext requestContext = new OnapLoggingContext(baseContext);
+ OnapLoggingContext baseContext) {
+ var requestContext = new OnapLoggingContext(baseContext);
if (request.getLocalAddr() != null) { // may be null in junit tests
requestContext.setServerIpAddress(request.getLocalAddr());
}
@@ -45,7 +49,7 @@ public class OnapLoggingUtils {
// otherwise from remote address in the request
String forwarded = request.getHeader("X-Forwarded-For");
if (forwarded != null && forwarded.trim().length() > 0) {
- forwarded = forwarded.trim().split(",")[0];
+ 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());
@@ -60,4 +64,41 @@ public class OnapLoggingUtils {
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/ErrorCodeMap.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java
index fab0415b..9e461916 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,51 +21,62 @@
package org.onap.policy.common.logging.eelf;
import java.util.EnumMap;
+import lombok.AccessLevel;
+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
*/
-public class ErrorCodeMap {
+@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 = "POLICY-100E";
+ 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 = "POLICY-400E";
+ 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 = "POLICY-502E";
+
+ 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 = "POLICY-503E";
+ 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 = "POLICY-504E";
+ 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 = "POLICY-515E";
+ 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 = "POLICY-516E";
+ 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 = "POLICY-517E";
+ 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 = "POLICY-518E";
+ 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 = "POLICY-519E";
+ 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 = "POLICY-520E";
+ private static final String ERROR_AUDIT = "300";
private static final String ERROR_AUDIT_DESCRIPTION = "This is an audit Error." + CHECK_ERROR_MESSAGE;
static {
@@ -85,10 +96,6 @@ public class ErrorCodeMap {
hm.put(MessageCodes.ERROR_AUDIT, new ErrorCodeInfo(ERROR_AUDIT, ERROR_AUDIT_DESCRIPTION));
}
- private ErrorCodeMap() {
- // Private constructor to prevent subclassing
- }
-
public static ErrorCodeInfo getErrorCodeInfo(MessageCodes messageCode) {
return hm.get(messageCode);
}
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
index 23be38ba..87a96a19 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,7 +21,9 @@
package org.onap.policy.common.logging.eelf;
import java.time.Instant;
+import lombok.AllArgsConstructor;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
/**
@@ -29,32 +31,14 @@ import lombok.Setter;
*/
@Getter
@Setter
+@NoArgsConstructor
+@AllArgsConstructor
public class EventData {
private String requestId = null;
private Instant startTime = null;
private Instant endTime = null;
- // Default constructor takes no arguments.
- // Is empty because instance variables are assigned
- // their default values upon declaration.
- public EventData() {
- // See above comments for the reason this constructor is empty
- }
-
- /**
- * Create an instance.
- *
- * @param requestId the request ID
- * @param startTime the start time
- * @param endTime the end time
- */
- public EventData(String requestId, Instant startTime, Instant endTime) {
- this.requestId = requestId;
- this.startTime = startTime;
- this.endTime = endTime;
- }
-
@Override
public String toString() {
return requestId + " Starting Time : " + this.startTime + " Ending Time : " + this.endTime;
@@ -62,8 +46,8 @@ public class EventData {
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
+ final var prime = 31;
+ var result = 1;
result = prime * result + ((requestId == null) ? 0 : requestId.hashCode());
return result;
}
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
index 71476c6a..f6f38d0d 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,12 +22,14 @@ 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;
/**
@@ -66,9 +68,7 @@ public class EventTrackInfo {
return;
}
// in case override the start time, check the original event was already stored or not
- if (!eventInfo.containsKey(id)) {
- eventInfo.put(id, event);
- }
+ eventInfo.putIfAbsent(id, event);
}
}
@@ -82,11 +82,4 @@ public class EventTrackInfo {
eventInfo.remove(eventId);
}
}
-
- /**
- * Returns a ConcurrentHashMap of EventData.
- */
- public ConcurrentMap<String, EventData> getEventInfo() {
- return eventInfo;
- }
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java
index 4b5c57a8..f5203683 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,8 +23,8 @@ 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.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
@@ -49,7 +49,7 @@ public class EventTrackInfoHandler extends TimerTask {
*/
private void cleanUp() {
- EventTrackInfo eventTrackInfo = PolicyLogger.getEventTracker();
+ var eventTrackInfo = PolicyLogger.getEventTracker();
if (eventTrackInfo == null) {
return;
}
@@ -63,7 +63,7 @@ public class EventTrackInfoHandler extends TimerTask {
ArrayList<String> expiredEvents = null;
- for (ConcurrentHashMap.Entry<String, EventData> entry : eventInfo.entrySet()) {
+ for (Map.Entry<String, EventData> entry : eventInfo.entrySet()) {
EventData event = entry.getValue();
startTime = event.getStartTime();
ns = Duration.between(startTime, Instant.now()).getSeconds();
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
index ab5712ff..629ead82 100644
--- 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
@@ -20,13 +20,13 @@
package org.onap.policy.common.logging.eelf;
-import com.att.eelf.i18n.EELFResolvableErrorEnum;
+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 EELFResolvableErrorEnum {
+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
@@ -149,7 +149,7 @@ public enum MessageCodes implements EELFResolvableErrorEnum {
MESSAGE_ERROR_SAMPLE;
- /**
+ /*
* Static initializer to ensure the resource bundles for this class are loaded... Here this
* application loads messages from three bundles.
*/
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
index 8d2031db..d71ebe54 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,8 +20,11 @@
package org.onap.policy.common.logging.eelf;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
-public class OnapConfigProperties {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class OnapConfigProperties {
/**
* The Date-time of the start of a transaction.
@@ -80,8 +83,5 @@ public class OnapConfigProperties {
public static final String SERVER_NAME = "ServerName";
-
- private OnapConfigProperties() {
- // do nothing
- }
+ 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
index f1b25d71..662ca764 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -34,6 +34,7 @@ import static org.onap.policy.common.logging.eelf.OnapConfigProperties.END_TIME_
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;
@@ -57,26 +58,31 @@ import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.Timer;
-import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.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.getInstance().getErrorLogger();
+ private static EELFLogger errorLogger = EELFManager.getErrorLogger();
- private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+ private static EELFLogger metricsLogger = EELFManager.getMetricsLogger();
- private static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
+ private static EELFLogger auditLogger = EELFManager.getAuditLogger();
- private static EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
+ private static EELFLogger debugLogger = EELFManager.getDebugLogger();
private static final String POLICY_LOGGER = "PolicyLogger";
@@ -86,7 +92,6 @@ public class PolicyLogger {
private static String hostAddress = null;
private static String component = null;
- private static TimerTask ttrcker = null;
private static boolean isEventTrackerRunning = false;
private static Timer timer = null;
@@ -110,7 +115,9 @@ public class PolicyLogger {
// size drops to this point, stop the Timer
private static int stopCheckPoint = 2500;
- private static boolean isOverrideLogbackLevel = false;
+ @Getter
+ @Setter
+ private static boolean overrideLogbackLevel = false;
private static Level debugLevel = Level.INFO;
private static Level auditLevel = Level.INFO;
@@ -133,10 +140,6 @@ public class PolicyLogger {
}
}
- private PolicyLogger() {
-
- }
-
public static synchronized Level getDebugLevel() {
return debugLevel;
}
@@ -150,7 +153,7 @@ public class PolicyLogger {
*/
public static synchronized void setDebugLevel(String newDebugLevel) {
- if (isOverrideLogbackLevel) {
+ if (overrideLogbackLevel) {
PolicyLogger.debugLevel = Level.valueOf(newDebugLevel);
debugLogger.setLevel(debugLevel);
}
@@ -170,7 +173,7 @@ public class PolicyLogger {
*/
public static synchronized void setAuditLevel(String newAuditLevel) {
- if (isOverrideLogbackLevel) {
+ if (overrideLogbackLevel) {
if ("OFF".equalsIgnoreCase(newAuditLevel)) {
PolicyLogger.auditLevel = Level.OFF;
auditLogger.setLevel(auditLevel);
@@ -195,7 +198,7 @@ public class PolicyLogger {
*/
public static synchronized void setMetricsLevel(String newMetricsLevel) {
- if (isOverrideLogbackLevel) {
+ if (overrideLogbackLevel) {
if ("OFF".equalsIgnoreCase(newMetricsLevel)) {
PolicyLogger.metricsLevel = Level.OFF;
metricsLogger.setLevel(metricsLevel);
@@ -221,7 +224,7 @@ public class PolicyLogger {
*/
public static synchronized void setErrorLevel(String newErrorLevel) {
- if (isOverrideLogbackLevel) {
+ if (overrideLogbackLevel) {
if ("OFF".equalsIgnoreCase(newErrorLevel)) {
PolicyLogger.errorLevel = Level.OFF;
errorLogger.setLevel(errorLevel);
@@ -301,8 +304,8 @@ public class PolicyLogger {
setMdcHostInfo();
- Instant startTime = Instant.now();
- Instant endTime = Instant.now();
+ var startTime = Instant.now();
+ var endTime = Instant.now();
seTimeStamps(startTime, endTime);
@@ -331,12 +334,11 @@ public class PolicyLogger {
* 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, "");
- Instant startTime = Instant.now();
- Instant endTime = Instant.now();
+ var startTime = Instant.now();
+ var endTime = Instant.now();
seTimeStamps(startTime, endTime);
@@ -349,7 +351,7 @@ public class PolicyLogger {
}
private static void seTimeStamps(Instant startTime, Instant endTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
+ var sdf = new SimpleDateFormat(DATE_FORMAT);
String formatedTime = sdf.format(Date.from(startTime));
MDC.put(BEGIN_TIME_STAMP, formatedTime);
@@ -433,18 +435,6 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
- *
- * @param className the class name
- * @param arg0 the message
- */
- public static void info(String className, String arg0) {
- MDC.put(classNameProp, className);
- debugLogger.info(MessageCodes.GENERAL_INFO, arg0);
- }
-
-
- /**
* Records only one String message.
*
* @param arg0 the message
@@ -483,14 +473,29 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
+ * Records a message with passed in message text and variable number of arguments.
*
- * @param arg0 log message
- * @param className class name
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
*/
- public static void warn(String className, String arg0) {
- MDC.put(classNameProp, className);
- debugLogger.warn(MessageCodes.GENERAL_INFO, arg0);
+ 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);
}
/**
@@ -553,19 +558,28 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
+ * Records a message with passed in message text and variable number of arguments.
*
- * @param className class name
- * @param arg0 log message
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
*/
- public static void error(String className, String arg0) {
- MDC.put(classNameProp, className);
- 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());
-
+ public static void warn(String message, Object... arguments) {
+ if (!debugLogger.isWarnEnabled()) {
+ return;
}
- errorLogger.error(MessageCodes.GENERAL_ERROR, arg0);
+ 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);
}
/**
@@ -575,13 +589,7 @@ public class PolicyLogger {
*/
public static void error(String arg0) {
MDC.put(classNameProp, "");
- 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());
-
- }
+ setErrorCode(MessageCodes.GENERAL_ERROR);
errorLogger.error(MessageCodes.GENERAL_ERROR, arg0);
}
@@ -592,13 +600,7 @@ public class PolicyLogger {
*/
public static void error(Object arg0) {
MDC.put(classNameProp, "");
- 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());
-
- }
+ setErrorCode(MessageCodes.GENERAL_ERROR);
errorLogger.error(MessageCodes.GENERAL_ERROR, "" + arg0);
}
@@ -611,13 +613,7 @@ public class PolicyLogger {
*/
public static void error(MessageCodes msg, Throwable arg0, String... arguments) {
MDC.put(classNameProp, "");
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(msg) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc());
-
- }
+ setErrorCode(msg);
String arguments2 = getNormalizedStackTrace(arg0, arguments);
errorLogger.error(msg, arguments2);
}
@@ -633,13 +629,7 @@ public class PolicyLogger {
*/
public static void error(MessageCodes msg, String className, Throwable arg0, String... arguments) {
MDC.put(classNameProp, className);
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(msg) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc());
-
- }
+ setErrorCode(msg);
String arguments2 = getNormalizedStackTrace(arg0, arguments);
errorLogger.error(msg, arguments2);
}
@@ -652,14 +642,35 @@ public class PolicyLogger {
*/
public static void error(MessageCodes msg, String... arguments) {
MDC.put(classNameProp, "");
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(msg) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc());
+ 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;
}
- errorLogger.error(msg, arguments);
+ 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);
}
/**
@@ -674,17 +685,6 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
- *
- * @param className the class name
- * @param arg0 the message
- */
- public static void debug(String className, String arg0) {
- MDC.put(classNameProp, className);
- debugLogger.debug(MessageCodes.GENERAL_INFO, arg0);
- }
-
- /**
* Records only one String message.
*
* @param arg0 the message
@@ -702,7 +702,7 @@ public class PolicyLogger {
public static void debug(Object arg0) {
MDC.put(classNameProp, "");
- debugLogger.debug("" + arg0);
+ debugLogger.debug("{}", arg0);
}
/**
@@ -734,15 +734,28 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
+ * Records a message with passed in message text and variable number of arguments.
*
- * @param className the class name
- * @param arg0 the message
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
*/
- public static void audit(String className, Object arg0) {
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- MDC.put(classNameProp, className);
- auditLogger.info("" + arg0);
+ 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);
}
/**
@@ -751,9 +764,34 @@ public class PolicyLogger {
* @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);
+ 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);
}
/**
@@ -823,7 +861,7 @@ public class PolicyLogger {
public static void trace(Object arg0) {
MDC.put(classNameProp, "");
- debugLogger.trace("" + arg0);
+ debugLogger.trace("{}", arg0);
}
/**
@@ -839,18 +877,18 @@ public class PolicyLogger {
if (eventTracker == null) {
eventTracker = new EventTrackInfo();
}
- EventData event = new EventData();
+ 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);
+ 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 : " + size + " on " + new Date());
- debugLogger.info("isEventTrackerRunning : " + isEventTrackerRunning);
+ debugLogger.info("EventInfo concurrentHashMap Size : {} on {}", size, new Date());
+ debugLogger.info("isEventTrackerRunning : {}", isEventTrackerRunning);
if (size >= concurrentHashMapLimit) {
@@ -972,7 +1010,7 @@ public class PolicyLogger {
return;
}
- EventData event = eventTracker.getEventDataByRequestId(eventId);
+ var event = eventTracker.getEventDataByRequestId(eventId);
if (event != null) {
Instant endTime = event.getEndTime();
@@ -1000,7 +1038,7 @@ public class PolicyLogger {
return;
}
- EventData event = eventTracker.getEventDataByRequestId(eventId.toString());
+ var event = eventTracker.getEventDataByRequestId(eventId.toString());
if (event != null) {
Instant endTime = event.getEndTime();
@@ -1049,7 +1087,7 @@ public class PolicyLogger {
if (eventTracker != null && eventTracker.getEventDataByRequestId(eventId) != null) {
eventTracker.remove(eventId);
- debugLogger.info("eventTracker.remove(" + eventId + ")");
+ debugLogger.info("eventTracker.remove({})", eventId);
}
}
@@ -1066,6 +1104,7 @@ public class PolicyLogger {
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);
}
@@ -1084,6 +1123,7 @@ public class PolicyLogger {
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);
}
@@ -1121,32 +1161,55 @@ public class PolicyLogger {
* @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 class name and a String message.
+ * Records the metrics event with a String message.
*
* @param arg0 the message
*/
- public static void metrics(String className, Object arg0) {
+ public static void metrics(Object arg0) {
seTimeStamps();
- MDC.put(classNameProp, className);
+ 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 the metrics event with a String message.
+ * Records a message with passed in message text and variable number of arguments.
*
- * @param arg0 the message
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
*/
- public static void metrics(Object arg0) {
+ 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, "");
- String serviceName = MDC.get(MDC_SERVICE_NAME);
- metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, "" + arg0);
+ metricsLogger.info(message, arguments);
}
/**
@@ -1166,13 +1229,13 @@ public class PolicyLogger {
* @param arguments the messages
*/
private static String getNormalizedStackTrace(Throwable throwable, String... arguments) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
+ 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;
- StringBuilder newArgument = new StringBuilder();
- for (int i = 0; i < curSize; i++) {
+ var newArgument = new StringBuilder();
+ for (var i = 0; i < curSize; i++) {
newArgument.append(arguments[i]);
newArgument.append(":");
}
@@ -1186,12 +1249,12 @@ public class PolicyLogger {
private static void startCleanUp() {
if (!isEventTrackerRunning) {
- ttrcker = new EventTrackInfoHandler();
+ var ttrcker = new EventTrackInfoHandler();
timer = new Timer(true);
timer.scheduleAtFixedRate(ttrcker, timerDelayTime, checkInterval);
- debugLogger.info("EventTrackInfoHandler begins! : " + new Date());
+ debugLogger.info("EventTrackInfoHandler begins! : {}", new Date());
} else {
- debugLogger.info("Timer is still running : " + new Date());
+ debugLogger.info("Timer is still running : {}", new Date());
}
}
@@ -1205,9 +1268,9 @@ public class PolicyLogger {
if (isEventTrackerRunning && timer != null) {
timer.cancel();
timer.purge();
- debugLogger.info("Timer stopped: " + new Date());
+ debugLogger.info("Timer stopped: {}", new Date());
} else {
- debugLogger.info("Timer was already stopped : " + new Date());
+ debugLogger.info("Timer was already stopped : {}", new Date());
}
isEventTrackerRunning = false;
@@ -1219,7 +1282,7 @@ public class PolicyLogger {
*/
public static LoggerType init(Properties properties) {
- Properties loggerProperties = getLoggerProperties(properties);
+ var loggerProperties = getLoggerProperties(properties);
// fetch and verify definitions of some properties
try {
@@ -1241,7 +1304,7 @@ public class PolicyLogger {
stopCheckPoint = getIntProp(loggerProperties, "stop.check.point", stopCheckPoint);
component = loggerProperties.getProperty("policy.component", "DROOLS");
- debugLogger.info("component: " + component);
+ debugLogger.info("component: {}", component);
return detmLoggerType(loggerProperties);
@@ -1261,9 +1324,9 @@ public class PolicyLogger {
}
private static int getIntProp(Properties properties, String propName, int defaultValue) {
- final int propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
+ final var propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
- debugLogger.info(propName + " value: " + propValue);
+ debugLogger.info("{} value: {}", propName, propValue);
if (propValue > 0) {
return propValue;
@@ -1276,7 +1339,7 @@ public class PolicyLogger {
ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc());
}
- errorLogger.error("failed to get the " + propName + ", so use its default value: " + defaultValue);
+ errorLogger.error("failed to get the {}, so use its default value: {}", propName, defaultValue);
return defaultValue;
}
}
@@ -1296,7 +1359,7 @@ public class PolicyLogger {
final String propValue = properties.getProperty(propName, defaultValue);
if (!StringUtils.isBlank(propValue)) {
- debugLogger.info(propName + " level: " + propValue);
+ debugLogger.info("{} level: {}", propName, propValue);
}
setter.accept(propValue);
@@ -1306,31 +1369,27 @@ public class PolicyLogger {
final String propValue = properties.getProperty(propName, "ON");
if (Level.OFF.toString().equalsIgnoreCase(propValue)) {
- debugLogger.info(propName + " level: " + propValue);
+ debugLogger.info("{} level: {}", propName, propValue);
}
setter.accept(propValue);
}
private static void setOverrideLogbackLevels(Properties loggerProperties) {
- final String overrideLogbackLevel = loggerProperties.getProperty("override.logback.level.setup");
+ final var overrideLogbackLevelText = loggerProperties.getProperty("override.logback.level.setup");
- if (!StringUtils.isBlank(overrideLogbackLevel)) {
- isOverrideLogbackLevel = "TRUE".equalsIgnoreCase(overrideLogbackLevel);
+ 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);
+ debugLogger.info("loggerType value: {}", loggerTypeProp);
switch (loggerTypeProp.toUpperCase()) {
case "EELF":
return LoggerType.EELF;
-
- case "LOG4J":
- return LoggerType.LOG4J;
-
case "SYSTEMOUT":
return LoggerType.SYSTEMOUT;
@@ -1339,28 +1398,26 @@ public class PolicyLogger {
}
}
-
/**
- * Returns true for overriding logback levels; returns false for not.
- */
- public static boolean isOverrideLogbackLevel() {
-
- return isOverrideLogbackLevel;
- }
-
- /**
- * Sets true for overriding logback levels; sets false for not.
+ * Sets server information to MDC.
*/
- public static void setOverrideLogbackLevel(boolean odl) {
-
- isOverrideLogbackLevel = odl;
-
+ public static void setServerInfo(String serverHost, String serverPort) {
+ MDC.put(SERVER_NAME, serverHost + ":" + serverPort);
}
/**
- * Sets server information to MDC.
+ * Sets error category, code and description.
*/
- public static void setServerInfo(String serverHost, String serverPort) {
- MDC.put(SERVER_NAME, serverHost + ":" + serverPort);
+ 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
index dc740440..425c62a4 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,22 +20,28 @@
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 {
- private DisplayUtils() {
- // do nothing
- }
+ /*
+ * 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);
+ System.out.println(message); // NOSONAR
}
public static void displayErrorMessage(Object msg) {
- System.err.println(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
index a3e5cc8f..0e0ef2bf 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,10 +21,9 @@
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;
@@ -36,6 +35,7 @@ public class EelfLogger implements Logger, Serializable {
private static final long serialVersionUID = 5385586713941277192L;
private String className = "";
+ @Getter
private String transId = UUID.randomUUID().toString();
/**
@@ -137,14 +137,6 @@ public class EelfLogger implements Logger, Serializable {
}
/**
- * Returns transaction Id for logging.
- */
- @Override
- public String getTransId() {
- return transId;
- }
-
- /**
* Records a message.
*
* @param message the message
@@ -166,6 +158,17 @@ public class EelfLogger implements Logger, Serializable {
}
/**
+ * 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
@@ -210,6 +213,17 @@ public class EelfLogger implements Logger, Serializable {
}
/**
+ * 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
@@ -234,6 +248,17 @@ public class EelfLogger implements Logger, Serializable {
* 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) {
@@ -278,6 +303,17 @@ public class EelfLogger implements Logger, Serializable {
* 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) {
@@ -387,6 +423,17 @@ public class EelfLogger implements Logger, Serializable {
}
/**
+ * 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
@@ -485,6 +532,17 @@ public class EelfLogger implements Logger, Serializable {
}
/**
+ * 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
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
index 030363dc..6c301712 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -29,7 +30,6 @@ 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;
@@ -40,13 +40,12 @@ public class FlexLogger extends SecurityManager {
private static final String GET_LOGGER_PREFIX = "FlexLogger:getLogger : loggerType = ";
private static LoggerType loggerType = LoggerType.EELF;
- private static ConcurrentHashMap<String, Logger4J> logger4JMap = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, EelfLogger> eelfLoggerMap = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, SystemOutLogger> systemOutMap = new ConcurrentHashMap<>();
// --- init logger first
static {
- loggerType = initlogger();
+ loggerType = initLogger();
}
/**
@@ -55,103 +54,41 @@ public class FlexLogger extends SecurityManager {
* @param clazz the class
*/
public static Logger getLogger(Class<?> clazz) {
- Logger logger = null;
- displayMessage(GET_LOGGER_PREFIX + loggerType);
- switch (loggerType) {
-
- case EELF:
- logger = getEelfLogger(clazz, false);
- break;
- case LOG4J:
- logger = getLog4JLogger();
- break;
- case SYSTEMOUT:
- default:
- logger = getSystemOutLogger();
- break;
- }
-
- return logger;
-
+ return getLogger(clazz, false);
}
/**
* Returns an instance of Logger.
- *
- * @param name the name of the logger
*/
- public static Logger getLogger(String name) {
- Logger logger = null;
- displayMessage(GET_LOGGER_PREFIX + loggerType);
- switch (loggerType) {
-
- case EELF:
- logger = getEelfLogger(null, false);
- break;
- case LOG4J:
- logger = getLog4JLogger(name);
- break;
- case SYSTEMOUT:
- default:
- logger = getSystemOutLogger();
- break;
- }
-
- return logger;
-
+ public static Logger getLogger() {
+ return getLogger(null);
}
/**
* Returns an instance of Logger.
*
- * @param clazz the class
+ * @param clazz the class
* @param isNewTransaction is a new transaction
*/
public static Logger getLogger(Class<?> clazz, boolean isNewTransaction) {
- Logger logger = null;
+ Logger logger;
displayMessage(GET_LOGGER_PREFIX + loggerType);
- switch (loggerType) {
-
- case EELF:
- logger = getEelfLogger(clazz, isNewTransaction);
- break;
- case LOG4J:
- logger = getLog4JLogger();
- break;
- case SYSTEMOUT:
- default:
- logger = getSystemOutLogger();
- break;
+ if (loggerType == LoggerType.EELF) {
+ logger = getEelfLogger(clazz, isNewTransaction);
+ } else {
+ logger = getSystemOutLogger();
}
return logger;
-
}
/**
* Returns an instance of Logger.
*
- * @param name the name of the logger
* @param isNewTransaction is a new transaction
*/
- public static Logger getLogger(String name, boolean isNewTransaction) {
- Logger logger = null;
- displayMessage(GET_LOGGER_PREFIX + loggerType);
- switch (loggerType) {
-
- case EELF:
- logger = getEelfLogger(null, isNewTransaction);
- break;
- case LOG4J:
- logger = getLog4JLogger(name);
- break;
- case SYSTEMOUT:
- default:
- logger = getSystemOutLogger();
- break;
- }
-
- return logger;
+ public static Logger getLogger(boolean isNewTransaction) {
+ return getLogger(null, isNewTransaction);
}
/**
@@ -163,40 +100,9 @@ public class FlexLogger extends SecurityManager {
}
/**
- * Returns an instance of Logger4J.
- */
- private static Logger4J getLog4JLogger() {
- String className = new FlexLogger().getClassName();
-
- if (!logger4JMap.containsKey(className)) {
- // for 1610 release use the default debug.log for log4j
- Logger4J logger = new Logger4J("debugLogger", className);
- logger4JMap.put(className, logger);
- }
-
- return logger4JMap.get(className);
- }
-
- /**
- * Returns an instance of Logger4J.
- *
- * @param name the name of the logger
- */
- private static Logger4J getLog4JLogger(String name) {
- String className = new FlexLogger().getClassName();
-
- if (!logger4JMap.containsKey(className)) {
- Logger4J logger = new Logger4J(name, className);
- logger4JMap.put(className, logger);
- }
-
- return logger4JMap.get(className);
- }
-
- /**
* Returns an instance of EelfLogger.
*
- * @param clazz the class
+ * @param clazz the class
* @param isNewTransaction is a new transaction
*/
private static EelfLogger getEelfLogger(Class<?> clazz, boolean isNewTransaction) {
@@ -209,21 +115,13 @@ public class FlexLogger extends SecurityManager {
className = new FlexLogger().getClassName();
}
- if (!eelfLoggerMap.containsKey(className)) {
- logger = new EelfLogger(clazz, isNewTransaction);
- eelfLoggerMap.put(className, logger);
- } else {
- logger = eelfLoggerMap.get(className);
- if (logger == null) {
- logger = new EelfLogger(clazz, isNewTransaction);
- eelfLoggerMap.put(className, logger);
- }
- // installl already created but it is new transaction
- if (isNewTransaction) {
- String transId = PolicyLogger.postMdcInfoForEvent(null);
- logger.setTransId(transId);
- }
+ 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;
}
@@ -235,37 +133,30 @@ public class FlexLogger extends SecurityManager {
String className = new FlexLogger().getClassName();
- if (!systemOutMap.containsKey(className)) {
- SystemOutLogger logger = new SystemOutLogger(className);
- systemOutMap.put(className, logger);
- }
-
- return systemOutMap.get(className);
+ return systemOutMap.computeIfAbsent(className, SystemOutLogger::new);
}
/**
* loads the logger properties.
*/
- private static LoggerType initlogger() {
- LoggerType loggerType = LoggerType.EELF;
+ private static LoggerType initLogger() {
+ var loggerType = LoggerType.EELF;
Properties properties = null;
try {
properties = PropertyUtil.getProperties("config/policyLogger.properties");
displayMessage("FlexLogger:properties => " + properties);
- if (properties != null) {
- String overrideLogbackLevel = properties.getProperty("override.logback.level.setup");
- displayMessage("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel);
- String 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"));
- }
+ 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);
+ displayMessage("initLogger" + e1);
} finally {
// OK to pass no properties (null)
loggerType = PolicyLogger.init(properties);
@@ -295,10 +186,10 @@ public class FlexLogger extends SecurityManager {
String auditLevel = properties.getProperty("audit.level");
String errorLevel = properties.getProperty("error.level");
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
- Instant startTime = Instant.now();
- String formatedTime = sdf.format(Date.from(startTime));
- displayMessage("FlexLogger.propertiesChanged : called at time : " + formatedTime);
+ 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) {
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
index d6f020e0..ad155a4c 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,7 +21,6 @@
package org.onap.policy.common.logging.flexlogger;
import java.util.UUID;
-
import org.onap.policy.common.logging.eelf.MessageCodes;
/**
@@ -41,6 +40,11 @@ public interface Logger {
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);
@@ -61,6 +65,11 @@ public interface Logger {
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);
@@ -71,6 +80,11 @@ public interface Logger {
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);
@@ -91,6 +105,11 @@ public interface Logger {
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);
@@ -111,6 +130,11 @@ public interface Logger {
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);
@@ -157,6 +181,11 @@ public interface Logger {
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();
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java
deleted file mode 100644
index 8802d17e..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java
+++ /dev/null
@@ -1,514 +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.flexlogger;
-
-import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage;
-
-import com.att.eelf.configuration.EELFLogger.Level;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.UUID;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.Priority;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
-
-/**
- * Logger4J implements all the methods of interface Logger by calling org.apache.log4j.Logger
- */
-public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logger, Serializable {
-
- private static final long serialVersionUID = 3183729429888828471L;
- private Logger log = null;
- private String methodName = "";
- private String className = "";
- private String transId = UUID.randomUUID().toString();
-
- /**
- * Constructor.
- *
- * @param clazz the class
- */
- public Logger4J(Class<?> clazz) {
- displayMessage("create instance of Logger4J");
- if (clazz != null) {
- log = Logger.getLogger(clazz);
- className = clazz.getName();
- }
- }
-
- /**
- * Constructor.
- *
- * @param name the name of the logger
- * @param className the name of the class
- */
- public Logger4J(String name, String className) {
- displayMessage("create instance of Logger4J");
- if (name != null) {
- log = Logger.getLogger(name);
- }
- this.className = className;
- }
-
- /**
- * Sets transaction Id.
- */
- @Override
- public void setTransId(String transId) {
- log.info(transId);
- this.transId = transId;
- }
-
- /**
- * Returns transaction Id.
- */
- @Override
- public String getTransId() {
- return transId;
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void debug(Object message) {
- if (isDebugEnabled()) {
- log.debug(transId + "|" + message);
- }
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void debug(Object message, Throwable throwable) {
- log.debug(message, throwable);
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- */
- @Override
- public void error(Object message) {
- log.error(transId + "|" + className + "|" + message);
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void error(Object message, Throwable throwable) {
- log.error(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) {
- log.error(transId + "|" + 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) {
- log.error(transId + "|" + className + "|" + "MessageCode:" + msg + Arrays.asList(arguments));
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void info(Object message) {
- log.info(transId + "|" + className + "|" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void info(Object message, Throwable throwable) {
- log.info(message, throwable);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void warn(Object message) {
- log.warn(transId + "|" + className + "|" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void warn(Object message, Throwable throwable) {
- log.warn(message, throwable);
- }
-
- /**
- * Records a message.
- *
- * @param msg the message code
- * @param arguments the messages
- */
- @Override
- public void warn(MessageCodes msg, String... arguments) {
- log.warn(className + "|" + "MessageCodes:" + msg + Arrays.asList(arguments));
- }
-
- /**
- * 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) {
- log.warn(className + "|" + "MessageCodes:" + msg + Arrays.asList(arguments));
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void trace(Object message) {
- log.trace(transId + "|" + className + "|" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void trace(Object message, Throwable throwable) {
- log.trace(message, throwable);
- }
-
- /**
- * Returns true for debug enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isDebugEnabled() {
- return log.isDebugEnabled();
- }
-
- /**
- * Returns true for error enabled, or false for not.
- *
- * @return boolean
- */
- @SuppressWarnings("deprecation")
- @Override
- public boolean isErrorEnabled() {
- return log.isEnabledFor(Priority.ERROR);
- }
-
- /**
- * Returns true for info enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isInfoEnabled() {
- return log.isInfoEnabled();
- }
-
- /**
- * Returns true for warn enabled, or false for not.
- *
- * @return boolean
- */
- @SuppressWarnings("deprecation")
- @Override
- public boolean isWarnEnabled() {
- // return log4j value
- return log.isEnabledFor(Priority.WARN);
- }
-
- /**
- * Returns true for audit enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isAuditEnabled() {
- 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);
- }
-
- /**
- * Records an audit message.
- *
- * @param message the message
- */
- @Override
- public void audit(Object message) {
- log.info(className + "|" + message);
- }
-
- /**
- * Records an audit message.
- *
- * @param message the message
- * @param throwable the throwable
- */
-
- @Override
- public void audit(Object message, Throwable throwable) {
- log.info(message, throwable);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- */
- @Override
- public void recordAuditEventStart(String eventId) {
- log.info(className + "|recordAuditEventStart with eventId " + eventId);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- */
- @Override
- public void recordAuditEventStart(UUID eventId) {
- if (eventId != null) {
- recordAuditEventStart(eventId.toString());
- }
- }
-
- /**
- * 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) {
- log.info(className + "|" + eventId + ":" + rule);
- }
-
- /**
- * 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) {
- if (eventId != null) {
- recordAuditEventEnd(eventId.toString(), rule, policyVersion);
- } else {
- 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) {
- log.info(className + "|" + eventId + ":" + rule);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- */
- @Override
- public void recordAuditEventEnd(UUID eventId, String rule) {
- if (eventId != null) {
- recordAuditEventEnd(eventId.toString(), rule);
- } else {
- recordAuditEventEnd(eventId, rule);
- }
- }
-
- /**
- * Records a metrics message.
- *
- * @param eventId the event ID
- * @param message the message
- */
- @Override
- public void recordMetricEvent(String eventId, String message) {
- log.info(className + "|" + eventId + ":" + message);
-
- }
-
- /**
- * Records a metrics message.
- *
- * @param eventId the event ID
- * @param message the message
- */
- @Override
- public void recordMetricEvent(UUID eventId, String message) {
- if (eventId != null) {
- recordMetricEvent(eventId.toString(), message);
- } else {
- recordMetricEvent(eventId, message);
- }
- }
-
- /**
- * Records a metrics message.
- *
- * @param message the message
- */
- @Override
- public void metrics(Object message) {
- log.info(message);
- }
-
- /**
- * 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) {
- log.info(message);
- }
-
- /**
- * Returns true for trace enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isTraceEnabled() {
- return log.isTraceEnabled();
- }
-
- /**
- * Records transaction Id.
- *
- * @param transId the transaction ID
- */
- @Override
- public void postMdcInfoForTriggeredRule(String transId) {
- log.info(transId);
- }
-
- /* ============================================================ */
-
- /*
- * Support for 'Serializable' -- the default rules don't work for the 'log' field
- */
-
- private void writeObject(ObjectOutputStream out) throws IOException {
- // write out 'methodName', 'className', 'transId' strings
- out.writeObject(methodName);
- out.writeObject(className);
- out.writeObject(transId);
- }
-
- private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
-
- // read in 'methodName', 'className', 'transId' strings
- methodName = (String) (in.readObject());
- className = (String) (in.readObject());
- transId = (String) (in.readObject());
-
- // look up associated logger
- log = Logger.getLogger(className);
- }
-}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java
index 8bf0dd78..f73bc4bc 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -24,5 +24,5 @@ package org.onap.policy.common.logging.flexlogger;
* Logger types.
*/
public enum LoggerType {
- EELF, LOG4J, SYSTEMOUT
+ 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
index 38759bc2..ef6c2e95 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -32,13 +32,17 @@ 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 class PropertyUtil {
+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.
@@ -60,17 +64,13 @@ public class PropertyUtil {
*/
public static Properties getProperties(File file) throws IOException {
// create an InputStream (may throw a FileNotFoundException)
- FileInputStream fis = new FileInputStream(file);
- try {
+ try (var fis = new FileInputStream(file)) {
// create the properties instance
- Properties rval = new Properties();
+ var rval = new Properties();
// load properties (may throw an IOException)
rval.load(fis);
return rval;
- } finally {
- // close input stream
- fis.close();
}
}
@@ -202,7 +202,7 @@ public class PropertyUtil {
lastModified = timestamp;
// Save old set, and initial set of changed properties.
- Properties oldProperties = properties;
+ var oldProperties = properties;
HashSet<String> changedProperties = new HashSet<>(oldProperties.stringPropertyNames());
// Fetch the list of listeners that we will potentially notify,
@@ -238,7 +238,7 @@ public class PropertyUtil {
for (final Listener notify : listeners) {
// Copy 'properties' and 'changedProperties', so it doesn't
// cause problems if the recipient makes changes.
- final Properties tmpProperties = (Properties) (properties.clone());
+ final var tmpProperties = (Properties) (properties.clone());
final HashSet<String> tmpChangedProperties = new HashSet<>(changedProperties);
// Do the notification in a separate thread, so blocking
@@ -276,7 +276,7 @@ public class PropertyUtil {
// Convert the file to a canonical form in order to avoid the situation
// where different names refer to the same file.
- File tempFile = file.getCanonicalFile();
+ 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
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
index f7a68a3d..d16a1d7a 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,27 +23,28 @@ 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 isDebugEnabled = true;
- private boolean isInfoEnabled = true;
- private boolean isWarnEnabled = true;
- private boolean isErrorEnabled = true;
- private boolean isAuditEnabled = true;
- private boolean isMetricsEnabled = true;
+ 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();
/**
@@ -78,35 +79,35 @@ public class SystemOutLogger implements Logger, Serializable {
private void initLevel() {
if (PolicyLogger.getDebugLevel() == Level.DEBUG) {
- isDebugEnabled = true;
- isInfoEnabled = true;
- isWarnEnabled = true;
+ debugEnabled = true;
+ infoEnabled = true;
+ warnEnabled = true;
} else {
- isDebugEnabled = false;
+ debugEnabled = false;
}
if (PolicyLogger.getDebugLevel() == Level.INFO) {
- isInfoEnabled = true;
- isWarnEnabled = true;
- isDebugEnabled = false;
+ infoEnabled = true;
+ warnEnabled = true;
+ debugEnabled = false;
}
if (PolicyLogger.getDebugLevel() == Level.OFF) {
- isInfoEnabled = false;
- isWarnEnabled = false;
- isDebugEnabled = false;
+ infoEnabled = false;
+ warnEnabled = false;
+ debugEnabled = false;
}
if (PolicyLogger.getErrorLevel() == Level.OFF) {
- isErrorEnabled = false;
+ errorEnabled = false;
}
if (PolicyLogger.getAuditLevel() == Level.OFF) {
- isAuditEnabled = false;
+ auditEnabled = false;
}
if (PolicyLogger.getMetricsLevel() == Level.OFF) {
- isMetricsEnabled = false;
+ metricsEnabled = false;
}
}
@@ -121,15 +122,6 @@ public class SystemOutLogger implements Logger, Serializable {
}
/**
- * Returns transaction Id.
- */
- @Override
- public String getTransId() {
-
- return transId;
- }
-
- /**
* Records a message.
*
* @param message the message
@@ -152,6 +144,21 @@ public class SystemOutLogger implements Logger, Serializable {
}
/**
+ * 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
@@ -193,181 +200,177 @@ public class SystemOutLogger implements Logger, Serializable {
*/
@Override
public void error(MessageCodes msg, String... arguments) {
-
displayMessage(transId + "|" + className + " : " + "MessageCode:" + msg + Arrays.asList(arguments));
}
/**
- * Records a message.
+ * Records a error message.
*
* @param message the message
+ * @param arguments variable number of arguments
*/
@Override
- public void info(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
+ 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
- * @param throwable the throwable
*/
@Override
- public void info(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
+ public void info(Object message) {
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records a message.
*
* @param message the message
+ * @param throwable the throwable
*/
@Override
- public void warn(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
+ public void info(Object message, Throwable throwable) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records a message.
*
* @param message the message
- * @param throwable the throwable
+ * @param arguments variable number of arguments
*/
@Override
- public void warn(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
+ 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 msg the message code
- * @param arguments the messages
+ * @param message the message
*/
@Override
- public void warn(MessageCodes msg, String... arguments) {
-
- displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
+ public void warn(Object message) {
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* 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) {
+ 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 trace(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
+ public void warn(Object message, Throwable throwable) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records a message.
*
- * @param message the message
+ * @param msg the message code
* @param throwable the throwable
+ * @param arguments the messages
*/
@Override
- public void trace(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
- }
+ public void warn(MessageCodes msg, Throwable throwable, String... arguments) {
- /**
- * Returns true for debug enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isDebugEnabled() {
- return isDebugEnabled;
- }
+ displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
- /**
- * Returns true for warn enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isWarnEnabled() {
- return isWarnEnabled;
}
/**
- * Returns true for info enabled, or false for not.
+ * Records a message.
*
- * @return boolean
+ * @param message the message
+ * @param arguments variable number of arguments
*/
@Override
- public boolean isInfoEnabled() {
- return isInfoEnabled;
+ 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));
+ }
}
/**
- * Returns true for error enabled, or false for not.
+ * Records a message.
*
- * @return boolean
+ * @param message the message
*/
@Override
- public boolean isErrorEnabled() {
- return isErrorEnabled;
+ public void trace(Object message) {
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
- * Returns true for audit enabled, or false for not.
+ * Records a message.
*
- * @return boolean
+ * @param message the message
+ * @param throwable the throwable
*/
@Override
- public boolean isAuditEnabled() {
-
- return isAuditEnabled;
+ public void trace(Object message, Throwable throwable) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
- * Returns true for metrics enabled, or false for not.
+ * Records an audit message.
*
- * @return boolean
+ * @param message the message
*/
@Override
- public boolean isMetricsEnabled() {
+ public void audit(Object message) {
- return isMetricsEnabled;
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records an audit message.
*
* @param message the message
+ * @param throwable the throwable
*/
@Override
- public void audit(Object message) {
-
- displayMessage(transId + "|" + className + " : " + message);
+ public void audit(Object message, Throwable throwable) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* 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);
+ public void audit(String message, Object... arguments) {
+ if (arguments.length == 1) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
+ } else {
+ displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
+ }
}
/**
@@ -480,6 +483,21 @@ public class SystemOutLogger implements Logger, Serializable {
}
/**
+ * 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
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
index ee64306f..eb2b318e 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,8 @@
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;
@@ -27,6 +29,7 @@ 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 {
@@ -47,8 +50,4 @@ public class LoggingContextFactory {
return forShared ? new SharedContext(baseContext) : new Slf4jLoggingContext(baseContext);
}
}
-
- private LoggingContextFactory() {
- // do nothing
- }
}
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
index e5f5e65b..13b38fc0 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,7 +22,6 @@ 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;
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
index 781be600..c34d9696 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 AT&T.
* ================================================================================
* 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.
@@ -47,7 +48,7 @@ public class ErrorCodeMapTest {
@Test
public void testErrorCodeInfoGetErrorCode() {
ErrorCodeInfo errorCodeInfo = ErrorCodeMap.getErrorCodeInfo(MessageCodes.EXCEPTION_ERROR);
- assertEquals("POLICY-503E", errorCodeInfo.getErrorCode());
+ assertEquals("500", errorCodeInfo.getErrorCode());
}
@Test
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
index 6fe81d27..882cc2cf 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -21,13 +21,10 @@
package org.onap.policy.common.logging.eelf;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import java.time.Instant;
-
import org.junit.Test;
public class EventDataTest {
@@ -142,32 +139,33 @@ public class EventDataTest {
final EventData d3 = new EventData("abc", iend, istart);
// same object
- assertTrue(d1.equals(d1));
+ assertEquals(d1, d1);
// compare with null
- assertFalse(d1.equals(null));
+ assertNotEquals(d1, null);
// compare with request id
- assertTrue(d1.equals("abc"));
- assertFalse(d1.equals("abd"));
+ // note: ignoring sonar because we want to test d1.equals(), not "abc".equals()
+ assertEquals(d1, "abc"); // NOSONAR
+ assertNotEquals(d1, "abd");
// compare with int - different class type
- assertFalse(d1.equals(10));
+ assertNotEquals(d1, 10);
// "this" has null request id
- assertFalse(new EventData().equals(d1));
+ assertNotEquals(new EventData(), d1);
// both null
- assertTrue(new EventData().equals(new EventData()));
+ assertEquals(new EventData(), new EventData());
// this request id is not null, other is null
- assertFalse(d1.equals(new EventData()));
+ assertNotEquals(d1, new EventData());
// neither null, same
- assertTrue(d1.equals(d3));
+ assertEquals(d1, d3);
// neither null, diff
- assertFalse(d1.equals(d2));
+ 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
index d1d5983d..2cc1e59e 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -24,7 +24,6 @@ import static org.junit.Assert.assertEquals;
import java.time.Instant;
import java.util.concurrent.ConcurrentMap;
-
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
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
index e6024682..0ca5feb5 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -23,10 +23,10 @@ package org.onap.policy.common.logging.eelf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.time.Instant;
-
import org.junit.Before;
import org.junit.Test;
@@ -62,8 +62,8 @@ public class EventTrackInfoTest {
info.storeEventData(data1);
info.storeEventData(data2);
- assertTrue(data1 == info.getEventDataByRequestId("abc"));
- assertTrue(data2 == info.getEventDataByRequestId("def"));
+ assertSame(data1, info.getEventDataByRequestId("abc"));
+ assertSame(data2, info.getEventDataByRequestId("def"));
assertNull(info.getEventDataByRequestId("hello"));
}
@@ -86,14 +86,14 @@ public class EventTrackInfoTest {
assertEquals(2, info.getEventInfo().size());
// look-up by request id
- assertTrue(data1 == info.getEventDataByRequestId("abc"));
- assertTrue(data2 == info.getEventDataByRequestId("def"));
+ 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());
- assertTrue(data1 == info.getEventDataByRequestId("abc"));
- assertTrue(data2 == info.getEventDataByRequestId("def"));
+ assertSame(data1, info.getEventDataByRequestId("abc"));
+ assertSame(data2, info.getEventDataByRequestId("def"));
}
/**
@@ -111,7 +111,7 @@ public class EventTrackInfoTest {
// look-up by request id
assertNull(info.getEventDataByRequestId("abc"));
- assertTrue(data2 == info.getEventDataByRequestId("def"));
+ assertSame(data2, info.getEventDataByRequestId("def"));
}
/**
@@ -123,8 +123,8 @@ public class EventTrackInfoTest {
info.storeEventData(data2);
assertEquals(2, info.getEventInfo().size());
- assertTrue(data1 == info.getEventInfo().get("abc"));
- assertTrue(data2 == info.getEventInfo().get("def"));
+ 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
index 6af3632a..62fcfaf4 100644
--- 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
@@ -3,7 +3,8 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020 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.
@@ -30,11 +31,13 @@ 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.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.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;
@@ -43,16 +46,14 @@ import static org.onap.policy.common.logging.eelf.OnapConfigProperties.STATUS_CO
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.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import org.powermock.reflect.Whitebox;
import org.slf4j.MDC;
+import org.springframework.test.util.ReflectionTestUtils;
public class PolicyLoggerTest {
@@ -189,7 +190,7 @@ public class PolicyLoggerTest {
@Test
public void testInfoMessageCodesStringStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).info(MessageCodes.ERROR_DATA_ISSUE, "str2");
}
@@ -197,7 +198,10 @@ public class PolicyLoggerTest {
@Test
public void testInfoStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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");
}
@@ -205,7 +209,7 @@ public class PolicyLoggerTest {
@Test
public void testInfoObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info("str1");
Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str1");
}
@@ -213,7 +217,7 @@ public class PolicyLoggerTest {
@Test
public void testInfoMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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"));
@@ -222,7 +226,7 @@ public class PolicyLoggerTest {
@Test
public void testInfoMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
@@ -232,7 +236,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnMessageCodesStringStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "str1");
Mockito.verify(mockLogger).warn(MessageCodes.ERROR_DATA_ISSUE);
}
@@ -240,7 +244,10 @@ public class PolicyLoggerTest {
@Test
public void testWarnStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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");
}
@@ -248,7 +255,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(1);
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "1");
}
@@ -256,7 +263,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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"));
@@ -265,7 +272,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
@@ -275,7 +282,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn("str1");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "str1");
}
@@ -283,10 +290,13 @@ public class PolicyLoggerTest {
@Test
public void testErrorStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ 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("POLICY-515E", MDC.get("ErrorCode"));
+ 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"));
}
@@ -294,11 +304,11 @@ public class PolicyLoggerTest {
@Test
public void testErrorString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error("str1");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1");
assertEquals("ERROR", MDC.get("ErrorCategory"));
- assertEquals("POLICY-515E", MDC.get("ErrorCode"));
+ 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"));
}
@@ -306,11 +316,11 @@ public class PolicyLoggerTest {
@Test
public void testErrorObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(1);
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "1");
assertEquals("ERROR", MDC.get("ErrorCategory"));
- assertEquals("POLICY-515E", MDC.get("ErrorCode"));
+ 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"));
}
@@ -318,7 +328,7 @@ public class PolicyLoggerTest {
@Test
public void testErrorMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ 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"));
@@ -327,7 +337,7 @@ public class PolicyLoggerTest {
@Test
public void testErrorMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
@@ -337,7 +347,7 @@ public class PolicyLoggerTest {
@Test
public void testErrorMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
}
@@ -345,7 +355,7 @@ public class PolicyLoggerTest {
@Test
public void testDebugMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
}
@@ -353,7 +363,10 @@ public class PolicyLoggerTest {
@Test
public void testDebugStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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");
}
@@ -361,7 +374,7 @@ public class PolicyLoggerTest {
@Test
public void testDebugString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug("str1");
Mockito.verify(mockLogger).debug("str1");
}
@@ -369,35 +382,38 @@ public class PolicyLoggerTest {
@Test
public void testDebugObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(1);
- Mockito.verify(mockLogger).debug("1");
+ Mockito.verify(mockLogger).debug("{}", 1);
}
@Test
public void testAuditStringObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
+ 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");
+ Mockito.verify(mockLogger).info("{}", "1");
}
@Test
public void testAuditObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "auditLogger", mockLogger);
PolicyLogger.audit(1);
assertEquals("", MDC.get("ClassName"));
assertEquals("COMPLETE", MDC.get("StatusCode"));
- Mockito.verify(mockLogger).info("1");
+ Mockito.verify(mockLogger).info("{}", 1);
}
@Test
public void testDebugMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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"));
@@ -406,7 +422,7 @@ public class PolicyLoggerTest {
@Test
public void testDebugMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
@@ -416,7 +432,7 @@ public class PolicyLoggerTest {
@Test
public void testIsDebugEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isDebugEnabled());
assertTrue(PolicyLogger.isDebugEnabled());
@@ -425,7 +441,7 @@ public class PolicyLoggerTest {
@Test
public void testIsErrorEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isErrorEnabled());
assertTrue(PolicyLogger.isErrorEnabled());
@@ -434,7 +450,7 @@ public class PolicyLoggerTest {
@Test
public void testIsWarnEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isWarnEnabled());
assertTrue(PolicyLogger.isWarnEnabled());
@@ -443,7 +459,7 @@ public class PolicyLoggerTest {
@Test
public void testIsInfoEnabled1() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isInfoEnabled1());
assertTrue(PolicyLogger.isInfoEnabled1());
@@ -452,7 +468,7 @@ public class PolicyLoggerTest {
@Test
public void testIsAuditEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isAuditEnabled());
assertTrue(PolicyLogger.isAuditEnabled());
@@ -461,7 +477,7 @@ public class PolicyLoggerTest {
@Test
public void testIsInfoEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isInfoEnabled());
assertTrue(PolicyLogger.isInfoEnabled());
@@ -470,7 +486,7 @@ public class PolicyLoggerTest {
@Test
public void testTraceStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.trace("str1", "str2");
Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "str2");
}
@@ -478,9 +494,9 @@ public class PolicyLoggerTest {
@Test
public void testTraceObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.trace(1);
- Mockito.verify(mockLogger).trace("1");
+ Mockito.verify(mockLogger).trace("{}", 1);
}
@Test
@@ -570,7 +586,7 @@ public class PolicyLoggerTest {
@Test
public void testRecordMetricEventString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.recordMetricEvent("eventId");
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("eventId"));
@@ -579,7 +595,7 @@ public class PolicyLoggerTest {
@Test
public void testMetricsString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metrics("str1");
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("str1"));
@@ -588,7 +604,10 @@ public class PolicyLoggerTest {
@Test
public void testMetricsStringObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ 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"));
@@ -597,7 +616,7 @@ public class PolicyLoggerTest {
@Test
public void testMetricsObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metrics(1);
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("1"));
@@ -606,14 +625,14 @@ public class PolicyLoggerTest {
@Test
public void testMetricsPrintln() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metricsPrintln("str1");
Mockito.verify(mockLogger).info("str1");
}
@Test
public void testInitNullProperties() {
- PolicyLogger.init(null);
+ assertThatCode(() -> PolicyLogger.init(null)).doesNotThrowAnyException();
}
@Test
@@ -630,7 +649,7 @@ public class PolicyLoggerTest {
properties.setProperty("stop.check.point", "0");
properties.setProperty("logger.property", "LOG4J");
- PolicyLogger.init(properties);
+ assertThatCode(() -> PolicyLogger.init(properties)).doesNotThrowAnyException();
}
@Test
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
index d3c09ee6..1d77451b 100644
--- 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
@@ -3,7 +3,8 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020 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.
@@ -27,6 +28,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.never;
import com.att.eelf.configuration.EELFLogger;
import java.util.UUID;
@@ -34,8 +36,8 @@ import org.junit.Test;
import org.mockito.Mockito;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
-import org.powermock.reflect.Whitebox;
import org.slf4j.MDC;
+import org.springframework.test.util.ReflectionTestUtils;
public class EelfLoggerTest {
@@ -91,7 +93,10 @@ public class EelfLoggerTest {
@Test
public void testDebugObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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");
}
@@ -99,7 +104,10 @@ public class EelfLoggerTest {
@Test
public void testErrorObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ 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");
}
@@ -107,7 +115,10 @@ public class EelfLoggerTest {
@Test
public void testInfoObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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");
}
@@ -115,7 +126,10 @@ public class EelfLoggerTest {
@Test
public void testWarnObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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");
}
@@ -123,7 +137,7 @@ public class EelfLoggerTest {
@Test
public void testTraceObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.trace("message");
Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "message");
}
@@ -131,7 +145,7 @@ public class EelfLoggerTest {
@Test
public void testIsDebugEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isDebugEnabled());
assertTrue(eelfLogger.isDebugEnabled());
@@ -141,7 +155,7 @@ public class EelfLoggerTest {
@Test
public void testIsInfoEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isInfoEnabled());
assertTrue(eelfLogger.isInfoEnabled());
@@ -150,7 +164,7 @@ public class EelfLoggerTest {
@Test
public void testIsWarnEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isWarnEnabled());
assertTrue(eelfLogger.isWarnEnabled());
@@ -159,7 +173,7 @@ public class EelfLoggerTest {
@Test
public void testIsErrorEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isErrorEnabled());
assertTrue(eelfLogger.isErrorEnabled());
@@ -182,7 +196,7 @@ public class EelfLoggerTest {
@Test
public void testIsTraceEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isTraceEnabled());
assertTrue(eelfLogger.isTraceEnabled());
@@ -198,7 +212,7 @@ public class EelfLoggerTest {
@Test
public void testDebugObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.debug("message", new NullPointerException());
Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@@ -207,7 +221,7 @@ public class EelfLoggerTest {
@Test
public void testErrorObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
eelfLogger.error("message", new NullPointerException());
Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@@ -217,8 +231,10 @@ public class EelfLoggerTest {
@Test
public void testInfoObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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"));
}
@@ -226,7 +242,7 @@ public class EelfLoggerTest {
@Test
public void testWarnObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.warn("message", new NullPointerException());
Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@@ -235,17 +251,17 @@ public class EelfLoggerTest {
@Test
public void testTraceObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.trace("message", new NullPointerException());
- Mockito.verify(mockLogger).trace("message");
+ Mockito.verify(mockLogger).trace("{}", "message");
}
@Test
public void testAuditObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "auditLogger", mockLogger);
eelfLogger.audit("message", new NullPointerException());
- Mockito.verify(mockLogger).info("message");
+ Mockito.verify(mockLogger).info("{}", "message");
}
@Test
@@ -315,7 +331,10 @@ public class EelfLoggerTest {
@Test
public void testMetrics() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ 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"));
@@ -324,7 +343,7 @@ public class EelfLoggerTest {
@Test
public void testErrorMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ 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"));
@@ -333,7 +352,7 @@ public class EelfLoggerTest {
@Test
public void testErrorMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
eelfLogger.error(MessageCodes.GENERAL_ERROR, "str1", "str2");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1", "str2");
@@ -348,7 +367,7 @@ public class EelfLoggerTest {
@Test
public void testWarnMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
}
@@ -356,7 +375,7 @@ public class EelfLoggerTest {
@Test
public void testWarnMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ 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"));
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
index a74dd94d..c0194f2b 100644
--- 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
@@ -3,7 +3,8 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020 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.
@@ -21,6 +22,7 @@
package org.onap.policy.common.logging.flexlogger;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
@@ -29,93 +31,65 @@ import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger.PropertiesCallBack;
-import org.powermock.reflect.Whitebox;
+import org.springframework.test.util.ReflectionTestUtils;
public class FlexLoggerTest {
@Test
public void testGetLoggerClassOfQEelf() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
+ 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
- public void testGetLoggerClassOfQLog4j() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
- Logger logger = FlexLogger.getLogger(this.getClass());
- assertSame(logger, FlexLogger.getLogger(this.getClass()));
- }
-
- @Test
public void testGetLoggerClassOfQSystemOut() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
Logger logger = FlexLogger.getLogger(this.getClass());
assertSame(logger, FlexLogger.getLogger(this.getClass()));
}
@Test
public void testGetLoggerStringEelf() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger("str1");
- assertSame(logger, FlexLogger.getLogger("str1"));
- }
-
- @Test
- public void testGetLoggerStringLog4j() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
- Logger logger = FlexLogger.getLogger("str1");
- assertSame(logger, FlexLogger.getLogger("str1"));
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
+ Logger logger = FlexLogger.getLogger();
+ assertSame(logger, FlexLogger.getLogger());
}
@Test
public void testGetLoggerStringSystemOut() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
- Logger logger = FlexLogger.getLogger("str1");
- assertSame(logger, FlexLogger.getLogger("str1"));
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ Logger logger = FlexLogger.getLogger();
+ assertSame(logger, FlexLogger.getLogger());
}
@Test
public void testGetLoggerClassOfQBooleanEelf() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger(this.getClass(), true);
- assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
- }
-
- @Test
- public void testGetLoggerClassOfQBooleanLog4j() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
Logger logger = FlexLogger.getLogger(this.getClass(), true);
assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
}
@Test
public void testGetLoggerClassOfQBooleanSystemOut() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
Logger logger = FlexLogger.getLogger(this.getClass(), true);
assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
}
@Test
public void testGetLoggerStringBooleanEelf() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger("str1", true);
- assertSame(logger, FlexLogger.getLogger("str1", true));
- }
-
- @Test
- public void testGetLoggerStringBooleanLog4j() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
- Logger logger = FlexLogger.getLogger("str1", true);
- assertSame(logger, FlexLogger.getLogger("str1", true));
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
+ Logger logger = FlexLogger.getLogger(true);
+ assertSame(logger, FlexLogger.getLogger(true));
}
@Test
public void testGetLoggerStringBooleanSystemOut() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
- Logger logger = FlexLogger.getLogger("str1", true);
- assertSame(logger, FlexLogger.getLogger("str1", true));
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ Logger logger = FlexLogger.getLogger(true);
+ assertSame(logger, FlexLogger.getLogger(true));
}
@Test
@@ -131,7 +105,9 @@ public class FlexLoggerTest {
changedKeys.add("error.level");
changedKeys.add("audit.level");
PropertiesCallBack propertiesCallBack = new PropertiesCallBack("name");
- propertiesCallBack.propertiesChanged(PropertyUtil.getProperties("config/policyLogger.properties"), changedKeys);
+ assertThatCode(() -> propertiesCallBack
+ .propertiesChanged(PropertyUtil.getProperties("config/policyLogger.properties"), changedKeys))
+ .doesNotThrowAnyException();
}
}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java
deleted file mode 100644
index 99c343c0..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.flexlogger;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.UUID;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.powermock.reflect.Whitebox;
-
-public class Logger4JTest {
-
- private Logger4J logger4J = new Logger4J("str1", "Logger4JTest");
-
- @Test
- public void testLogger4JClassOfQ() {
- new Logger4J(this.getClass());
- }
-
- @Test
- public void testSetAndGetTransId() {
- logger4J.setTransId("transactionId");
- assertEquals("transactionId", logger4J.getTransId());
- }
-
- @Test
- public void testDebugObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isDebugEnabled()).thenReturn(true);
- logger4J.setTransId("transactionId");
- logger4J.debug("message");
- Mockito.verify(logger).debug("transactionId|message");
- }
-
- @Test
- public void testErrorObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.error("message");
- Mockito.verify(logger).error("transactionId|Logger4JTest|message");
- }
-
- @Test
- public void testInfoObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.info("message");
- Mockito.verify(logger).info("transactionId|Logger4JTest|message");
- }
-
- @Test
- public void testWarnObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.warn("message");
- Mockito.verify(logger).warn("transactionId|Logger4JTest|message");
- }
-
- @Test
- public void testTraceObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.trace("message");
- Mockito.verify(logger).trace("transactionId|Logger4JTest|message");
- }
-
- @Test
- public void testIsDebugEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isDebugEnabled()).thenReturn(true).thenReturn(false);
- assertTrue(logger4J.isDebugEnabled());
- assertFalse(logger4J.isDebugEnabled());
- }
-
- @Test
- public void testIsErrorEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isEnabledFor(Level.ERROR)).thenReturn(true).thenReturn(false);
- assertTrue(logger4J.isErrorEnabled());
- assertFalse(logger4J.isErrorEnabled());
- }
-
- @Test
- public void testIsInfoEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isInfoEnabled()).thenReturn(true).thenReturn(false);
- assertTrue(logger4J.isInfoEnabled());
- assertFalse(logger4J.isInfoEnabled());
- }
-
- @Test
- public void testIsWarnEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isEnabledFor(Level.WARN)).thenReturn(true).thenReturn(false);
- assertTrue(logger4J.isWarnEnabled());
- assertFalse(logger4J.isWarnEnabled());
- }
-
- @Test
- public void testAuditObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.audit("str1");
- Mockito.verify(logger).info("Logger4JTest|str1");
- }
-
- @Test
- public void testRecordAuditEventStartString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.recordAuditEventEnd("eventId", "rule");
- Mockito.verify(logger).info("Logger4JTest|eventId:rule");
- }
-
- @Test
- public void testRecordAuditEventStartUuid() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- UUID uuid = UUID.randomUUID();
- logger4J.recordAuditEventStart(uuid);
- Mockito.verify(logger).info("Logger4JTest|recordAuditEventStart with eventId " + uuid.toString());
- }
-
- @Test
- public void testRecordAuditEventEndStringStringString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.recordAuditEventEnd("eventId", "rule", "policyVersion");
- Mockito.verify(logger).info("Logger4JTest|eventId:rule");
- }
-
- @Test
- public void testRecordAuditEventEndUuidStringString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- UUID uuid = UUID.randomUUID();
- logger4J.recordAuditEventEnd(uuid, "rule", "policyVersion");
- Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":rule");
- }
-
- @Test
- public void testRecordAuditEventEndStringString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.recordAuditEventEnd("eventId", "rule");
- Mockito.verify(logger).info("Logger4JTest|eventId:rule");
- }
-
- @Test
- public void testRecordAuditEventEndUuidString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- UUID uuid = UUID.randomUUID();
- logger4J.recordAuditEventEnd(uuid, "rule");
- Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":rule");
- }
-
- @Test
- public void testRecordMetricEventStringString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.recordMetricEvent("eventId", "str1");
- Mockito.verify(logger).info("Logger4JTest|eventId:str1");
- }
-
- @Test
- public void testRecordMetricEventUuidString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- UUID uuid = UUID.randomUUID();
- logger4J.recordMetricEvent(uuid, "str1");
- Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":str1");
- }
-
- @Test
- public void testMetrics() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.metrics("str1");
- Mockito.verify(logger).info("str1");
- }
-
- @Test
- public void testErrorMessageCodesThrowableStringArray() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.error(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
- Mockito.verify(logger)
- .error("transactionId|Logger4JTest|MessageCodes :" + MessageCodes.GENERAL_ERROR + "[str1, str2]");
- }
-
- @Test
- public void testErrorMessageCodesStringArray() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.error(MessageCodes.GENERAL_ERROR, "str1", "str2");
- Mockito.verify(logger)
- .error("transactionId|Logger4JTest|MessageCode:" + MessageCodes.GENERAL_ERROR + "[str1, str2]");
- }
-
- @Test
- public void testPostMdcInfoForEventString() {
- String returnedTransactionId = logger4J.postMdcInfoForEvent("transactionId");
- assertEquals("transactionId", returnedTransactionId);
- }
-
- @Test
- public void testPostMdcInfoForEventEmptyString() {
- String returnedTransactionId = logger4J.postMdcInfoForEvent("");
- assertNotNull("", returnedTransactionId);
- assertNotEquals("", returnedTransactionId);
- }
-
- @Test
- public void testWarnMessageCodesStringArray() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
- Mockito.verify(logger).warn("Logger4JTest|MessageCodes:" + MessageCodes.GENERAL_ERROR + "[str1, str2]");
- }
-
- @Test
- public void testWarnMessageCodesThrowableStringArray() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.warn(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
- Mockito.verify(logger).warn("Logger4JTest|MessageCodes:" + MessageCodes.GENERAL_ERROR + "[str1, str2]");
- }
-
- @Test
- public void testDebugObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- Exception exception = new NullPointerException();
- logger4J.debug("message", exception);
- Mockito.verify(logger).debug("message", exception);
- }
-
- @Test
- public void testErrorObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- Exception exception = new NullPointerException();
- logger4J.error("message", exception);
- Mockito.verify(logger).error("message", exception);
- }
-
- @Test
- public void testInfoObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- Exception exception = new NullPointerException();
- logger4J.info("message", exception);
- Mockito.verify(logger).info("message", exception);
- }
-
- @Test
- public void testWarnObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Exception exception = new NullPointerException();
- logger4J.warn("message", exception);
- Mockito.verify(logger).warn("message", exception);
- }
-
- @Test
- public void testTraceObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Exception exception = new NullPointerException();
- logger4J.trace("message", exception);
- Mockito.verify(logger).trace("message", exception);
- }
-
- @Test
- public void testAuditObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Exception exception = new NullPointerException();
- logger4J.audit("message", exception);
- Mockito.verify(logger).info("message", exception);
- }
-
- @Test
- public void testIsTraceEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.isTraceEnabled();
- Mockito.verify(logger).isTraceEnabled();
- }
-
- @Test
- public void testPostMdcInfoForTriggeredRule() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.postMdcInfoForTriggeredRule("transactionId");
- Mockito.verify(logger).info("transactionId");
- }
-
- @Test
- public void testPostMdcInfoForEventObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.postMdcInfoForEvent(1);
- Mockito.verify(logger).info(1);
- }
-
-}
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
index bbf77179..13f525c9 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018-2020 Ericsson, AT&T. 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.
@@ -43,28 +44,28 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.PropertyUtil.Listener;
-import org.powermock.reflect.Whitebox;
+import org.springframework.test.util.ReflectionTestUtils;
public 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;
-
+
@BeforeClass
public static void setUpBeforeClass() {
- saveTimer = Whitebox.getInternalState(PropertyUtil.LazyHolder.class, TIMER_FIELD);
-
+ saveTimer = (Timer) ReflectionTestUtils.getField(PropertyUtil.LazyHolder.class, TIMER_FIELD);
+
}
-
+
@AfterClass
public static void tearDownAfterClass() {
- Whitebox.setInternalState(PropertyUtil.LazyHolder.class, TIMER_FIELD, saveTimer);
-
+ ReflectionTestUtils.setField(PropertyUtil.LazyHolder.class, TIMER_FIELD, saveTimer);
+
}
/**
@@ -74,15 +75,15 @@ public class PropertyUtilTest {
public void setUp() throws IOException {
task = null;
timer = mock(Timer.class);
- Whitebox.setInternalState(PropertyUtil.LazyHolder.class, TIMER_FIELD, timer);
-
+ 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");
@@ -95,7 +96,7 @@ public class PropertyUtilTest {
PropertyUtil.stopListening(FILE, testListener);
FILE.delete();
}
-
+
@Test
public void testTimer() {
assertNotNull(saveTimer);
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
index 92df0297..38c9e0d2 100644
--- 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
@@ -3,7 +3,7 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-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.
@@ -21,16 +21,15 @@
package org.onap.policy.common.logging.flexlogger;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.att.eelf.configuration.EELFLogger.Level;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.Test;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -41,7 +40,7 @@ public class SystemOutLoggerTest {
@Test
public void testSystemOutLoggerClassOfQ() {
- new SystemOutLogger(SystemOutLoggerTest.class);
+ assertThatCode(() -> new SystemOutLogger(SystemOutLoggerTest.class)).doesNotThrowAnyException();
}
@Test
@@ -426,7 +425,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.debug(1, new NullPointerException());
+ systemOutLogger.debug("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
@@ -443,7 +442,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.error(1, new NullPointerException());
+ systemOutLogger.error("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
@@ -460,7 +459,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.info(1, new NullPointerException());
+ systemOutLogger.info("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
@@ -477,7 +476,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.warn(1, new NullPointerException());
+ systemOutLogger.warn("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
@@ -511,7 +510,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.audit(1, new NullPointerException());
+ systemOutLogger.audit("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
diff --git a/common-parameters/pom.xml b/common-parameters/pom.xml
index 9b8f01d9..2798d43d 100644
--- a/common-parameters/pom.xml
+++ b/common-parameters/pom.xml
@@ -1,7 +1,8 @@
<!--
============LICENSE_START=======================================================
Copyright (C) 2018 Ericsson. All rights reserved.
- Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ Modifications Copyright (C) 2019, 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.
@@ -23,7 +24,7 @@
<parent>
<groupId>org.onap.policy.common</groupId>
<artifactId>common-modules</artifactId>
- <version>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
<artifactId>common-parameters</artifactId>
@@ -31,33 +32,19 @@
<description>[${project.parent.artifactId}] module provides common property and parameter handling the ONAP Policy Framework</description>
<dependencies>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <scope>test</scope>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java
index f8eebcf1..e1620530 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java
@@ -1,6 +1,6 @@
-/*
+/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,6 +23,9 @@ package org.onap.policy.common.parameters;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.BiConsumer;
import java.util.function.Function;
/**
@@ -65,6 +68,19 @@ public class BeanValidationResult extends ValidationResultImpl {
}
/**
+ * Adds a result to this result.
+ * @param name name of the object of this result
+ * @param object object being validated
+ * @param status status of the new result
+ * @param message new result message
+ * @return {@code true} if the status is {@code null} or valid, {@code false} if the
+ * status is invalid
+ */
+ public boolean addResult(String name, Object object, ValidationStatus status, String message) {
+ return addResult(new ObjectValidationResult(name, object, status, message));
+ }
+
+ /**
* Validates that a sub-object within the bean is not {@code null}.
*
* @param subName name of the sub-object
@@ -72,7 +88,7 @@ public class BeanValidationResult extends ValidationResultImpl {
* @return {@code true} if the value is not null, {@code false} otherwise
*/
public boolean validateNotNull(String subName, Object subObject) {
- ObjectValidationResult result = new ObjectValidationResult(subName, subObject);
+ var result = new ObjectValidationResult(subName, subObject);
if (result.validateNotNull()) {
return true;
@@ -110,10 +126,10 @@ public class BeanValidationResult extends ValidationResultImpl {
return true;
}
- BeanValidationResult result = new BeanValidationResult(listName, null);
+ var result = new BeanValidationResult(listName, null);
for (T item : list) {
if (item == null) {
- result.addResult(new ObjectValidationResult("item", item, ValidationStatus.INVALID, "null"));
+ result.addResult("item", item, ValidationStatus.INVALID, "null");
} else {
result.addResult(itemValidator.apply(item));
}
@@ -129,6 +145,34 @@ public class BeanValidationResult extends ValidationResultImpl {
}
/**
+ * Validates the entries in a map.
+ *
+ * @param mapName name of the list
+ * @param map map whose entries are to be validated, or {@code null}
+ * @param entryValidator function to validate an entry in the map
+ * @return {@code true} if all entries in the map are valid, {@code false} otherwise
+ */
+ public <V> boolean validateMap(String mapName, Map<String, V> map,
+ BiConsumer<BeanValidationResult, Entry<String, V>> entryValidator) {
+ if (map == null) {
+ return true;
+ }
+
+ var result = new BeanValidationResult(mapName, null);
+ for (Entry<String, V> ent : map.entrySet()) {
+ entryValidator.accept(result, ent);
+ }
+
+ if (result.isValid()) {
+ return true;
+
+ } else {
+ addResult(result);
+ return false;
+ }
+ }
+
+ /**
* Gets the validation result.
*
* @param initialIndentation the indentation to use on the main result output
@@ -142,7 +186,7 @@ public class BeanValidationResult extends ValidationResultImpl {
return null;
}
- StringBuilder builder = new StringBuilder();
+ var builder = new StringBuilder();
builder.append(initialIndentation);
builder.append('"');
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java
new file mode 100644
index 00000000..4ed7e42c
--- /dev/null
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java
@@ -0,0 +1,432 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters;
+
+import java.lang.reflect.Field;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Map.Entry;
+import org.apache.commons.lang3.StringUtils;
+import org.onap.policy.common.parameters.annotations.ClassName;
+import org.onap.policy.common.parameters.annotations.Max;
+import org.onap.policy.common.parameters.annotations.Min;
+import org.onap.policy.common.parameters.annotations.NotBlank;
+import org.onap.policy.common.parameters.annotations.NotNull;
+import org.onap.policy.common.parameters.annotations.Pattern;
+import org.onap.policy.common.parameters.annotations.Size;
+import org.onap.policy.common.parameters.annotations.Valid;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Bean validator, supporting the parameter annotations.
+ */
+public class BeanValidator {
+ public static final Logger logger = LoggerFactory.getLogger(BeanValidator.class);
+
+ /**
+ * Validates top level fields within an object. For each annotated field, it retrieves
+ * the value using the public "getter" method for the field. If there is no public
+ * "getter" method, then it throws an exception. Otherwise, it validates the retrieved
+ * value based on the annotations. This recurses through super classes looking for
+ * fields to be verified, but it does not examine any interfaces.
+ *
+ * @param name name of the object being validated
+ * @param object object to be validated. If {@code null}, then an empty result is
+ * returned
+ * @return the validation result
+ */
+ public BeanValidationResult validateTop(String name, Object object) {
+ var result = new BeanValidationResult(name, object);
+ if (object == null) {
+ return result;
+ }
+
+ // check class hierarchy - don't need to check interfaces
+ for (Class<?> clazz = object.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
+ validateFields(result, object, clazz);
+ }
+
+ return result;
+ }
+
+ /**
+ * Adds validators based on the annotations that are available.
+ *
+ * @param validator where to add the validators
+ */
+ protected void addValidators(ValueValidator validator) {
+ validator.addAnnotation(NotNull.class, this::verNotNull);
+ validator.addAnnotation(NotBlank.class, this::verNotBlank);
+ validator.addAnnotation(Size.class, this::verSize);
+ validator.addAnnotation(Max.class, this::verMax);
+ validator.addAnnotation(Min.class, this::verMin);
+ validator.addAnnotation(Pattern.class, this::verRegex);
+ validator.addAnnotation(ClassName.class, this::verClassName);
+ validator.addAnnotation(Valid.class, this::verCascade);
+ }
+
+ /**
+ * Performs validation of all annotated fields found within the class.
+ *
+ * @param result validation results are added here
+ * @param object object whose fields are to be validated
+ * @param clazz class, within the object's hierarchy, to be examined for fields to be
+ * verified
+ */
+ private void validateFields(BeanValidationResult result, Object object, Class<?> clazz) {
+ for (Field field : clazz.getDeclaredFields()) {
+ var validator = makeFieldValidator(clazz, field);
+ validator.validateField(result, object);
+ }
+ }
+
+ /**
+ * Verifies that the value is not null.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verNotNull(BeanValidationResult result, String fieldName, Object value) {
+ if (value == null) {
+ result.addResult(fieldName, xlate(value), ValidationStatus.INVALID, "is null");
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Verifies that the value is not blank. Note: this does <i>not</i> verify that the
+ * value is not {@code null}.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verNotBlank(BeanValidationResult result, String fieldName, Object value) {
+ if (value instanceof String && StringUtils.isBlank(value.toString())) {
+ result.addResult(fieldName, xlate(value), ValidationStatus.INVALID, "is blank");
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Verifies that the value has the specified number of elements.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param annot annotation against which the value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verSize(BeanValidationResult result, String fieldName, Size annot, Object value) {
+ int size;
+ if (value instanceof Collection) {
+ size = ((Collection<?>) value).size();
+
+ } else if (value instanceof Map) {
+ size = ((Map<?, ?>) value).size();
+
+ } else {
+ return true;
+ }
+
+
+ if (size < annot.min()) {
+ result.addResult(fieldName, xlate(value), ValidationStatus.INVALID,
+ "minimum number of elements: " + annot.min());
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Verifies that the value matches a regular expression.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param annot annotation against which the value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verRegex(BeanValidationResult result, String fieldName, Pattern annot, Object value) {
+ try {
+ if (value instanceof String && com.google.re2j.Pattern.matches(annot.regexp(), value.toString())) {
+ return true;
+ }
+
+ } catch (RuntimeException e) {
+ logger.warn("validation error for regular expression: {}", annot.regexp(), e);
+ }
+
+ result.addResult(fieldName, xlate(value), ValidationStatus.INVALID,
+ "does not match regular expression " + annot.regexp());
+ return false;
+ }
+
+ /**
+ * Verifies that the value is <= the minimum value.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param annot annotation against which the value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verMax(BeanValidationResult result, String fieldName, Max annot, Object value) {
+ if (!(value instanceof Number)) {
+ return true;
+ }
+
+ Number num = (Number) value;
+ if (num instanceof Integer || num instanceof Long) {
+ if (num.longValue() <= annot.value()) {
+ return true;
+ }
+
+ } else if (num instanceof Float || num instanceof Double) {
+ if (num.doubleValue() <= annot.value()) {
+ return true;
+ }
+
+ } else {
+ return true;
+ }
+
+ result.addResult(fieldName, xlate(value), ValidationStatus.INVALID,
+ "exceeds the maximum value: " + annot.value());
+ return false;
+ }
+
+ /**
+ * Verifies that the value is >= the minimum value.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param annot annotation against which the value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verMin(BeanValidationResult result, String fieldName, Min annot, Object value) {
+ return verMin(result, fieldName, annot.value(), value);
+ }
+
+ /**
+ * Verifies that the value is >= the minimum value.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param min minimum against which the value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verMin(BeanValidationResult result, String fieldName, long min, Object value) {
+ if (!(value instanceof Number)) {
+ return true;
+ }
+
+ Number num = (Number) value;
+ if (num instanceof Integer || num instanceof Long) {
+ if (num.longValue() >= min) {
+ return true;
+ }
+
+ } else if (num instanceof Float || num instanceof Double) {
+ if (num.doubleValue() >= min) {
+ return true;
+ }
+
+ } else {
+ return true;
+ }
+
+ result.addResult(fieldName, xlate(value), ValidationStatus.INVALID,
+ "is below the minimum value: " + min);
+ return false;
+ }
+
+ /**
+ * Verifies that the value is a valid class name.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verClassName(BeanValidationResult result, String fieldName, Object value) {
+ if (!(value instanceof String)) {
+ return true;
+ }
+
+ try {
+ Class.forName(value.toString());
+ return true;
+
+ } catch (final ClassNotFoundException exp) {
+ result.addResult(fieldName, value, ValidationStatus.INVALID, "class is not in the classpath");
+ return false;
+ }
+ }
+
+ /**
+ * Verifies that the value is valid by recursively invoking
+ * {@link #validateTop(String, Object)}.
+ *
+ * @param result where to add the validation result
+ * @param fieldName field whose value is being verified
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verCascade(BeanValidationResult result, String fieldName, Object value) {
+ if (value == null || value instanceof Collection || value instanceof Map) {
+ return true;
+ }
+
+ BeanValidationResult result2 = (value instanceof ParameterGroup ? ((ParameterGroup) value).validate()
+ : validateTop(fieldName, value));
+
+ if (result2.isClean()) {
+ return true;
+ }
+
+ result.addResult(result2);
+
+ return result2.isValid();
+ }
+
+ /**
+ * Validates the items in a collection.
+ *
+ * @param result where to add the validation result
+ * @param fieldName name of the field containing the collection
+ * @param itemValidator validator for individual items within the list
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verCollection(BeanValidationResult result, String fieldName, ValueValidator itemValidator,
+ Object value) {
+
+ if (!(value instanceof Collection)) {
+ return true;
+ }
+
+ Collection<?> list = (Collection<?>) value;
+
+ var result2 = new BeanValidationResult(fieldName, value);
+ var count = 0;
+ for (Object item : list) {
+ itemValidator.validateValue(result2, String.valueOf(count++), item);
+ }
+
+ if (result2.isClean()) {
+ return true;
+ }
+
+ result.addResult(result2);
+ return false;
+ }
+
+ /**
+ * Validates the items in a Map.
+ *
+ * @param result where to add the validation result
+ * @param fieldName name of the field containing the map
+ * @param keyValidator validator for an individual key within the Map entry
+ * @param valueValidator validator for an individual value within the Map entry
+ * @param value value to be verified
+ * @return {@code true} if the next check should be performed, {@code false} otherwise
+ */
+ public boolean verMap(BeanValidationResult result, String fieldName, ValueValidator keyValidator,
+ ValueValidator valueValidator, Object value) {
+
+ if (!(value instanceof Map)) {
+ return true;
+ }
+
+ Map<?, ?> map = (Map<?, ?>) value;
+
+ var result2 = new BeanValidationResult(fieldName, value);
+
+ for (Entry<?, ?> entry : map.entrySet()) {
+ String name = getEntryName(entry);
+
+ var result3 = new BeanValidationResult(name, entry);
+ keyValidator.validateValue(result3, "key", entry.getKey());
+ valueValidator.validateValue(result3, "value", entry.getValue());
+
+ if (!result3.isClean()) {
+ result2.addResult(result3);
+ }
+ }
+
+ if (result2.isClean()) {
+ return true;
+ }
+
+ result.addResult(result2);
+ return false;
+ }
+
+ /**
+ * Gets a name for an entry.
+ *
+ * @param entry entry whose name is to be determined
+ * @return a name for the entry
+ */
+ protected <K, V> String getEntryName(Map.Entry<K, V> entry) {
+ var key = entry.getKey();
+ if (key == null) {
+ return "";
+ }
+
+ return key.toString();
+ }
+
+ /**
+ * Makes a field validator.
+ *
+ * @param clazz class containing the field
+ * @param field field of interest
+ * @return a validator for the given field
+ */
+ protected FieldValidator makeFieldValidator(Class<?> clazz, Field field) {
+ return new FieldValidator(this, clazz, field);
+ }
+
+ /**
+ * Translates a value to something printable, for use by
+ * {@link ObjectValidationResult}. This default method simply returns the original
+ * value.
+ *
+ * @param value value to be translated
+ * @return the translated value
+ */
+ public Object xlate(Object value) {
+ return value;
+ }
+}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java
deleted file mode 100644
index f35d1970..00000000
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * This class holds the result of the validation of a parameter group.
- */
-public abstract class CommonGroupValidationResult implements ValidationResult {
-
-
- private final String messagePrefix;
-
- /**
- * Validation status for the entire class.
- */
- protected ValidationStatus status = ValidationStatus.CLEAN;
-
- /**
- * Status message.
- */
- protected String message;
-
- /**
- * Validation results for each parameter in the group.
- */
- protected final Map<String, ValidationResult> validationResultMap = new LinkedHashMap<>();
-
-
- /**
- * Constructs the object.
- *
- * @param messagePrefix status message prefix
- */
- public CommonGroupValidationResult(String messagePrefix) {
- this.messagePrefix = messagePrefix;
- this.message = messagePrefix + status.toString();
- }
-
- /**
- * Gets the status of validation.
- *
- * @return the status
- */
- @Override
- public ValidationStatus getStatus() {
- return status;
- }
-
- /**
- * Set the validation result on a parameter group.
- *
- * @param status The validation status the parameter group is receiving
- * @param message The validation message explaining the validation status
- */
- @Override
- public void setResult(ValidationStatus status, String message) {
- setResult(status);
- this.message = message;
- }
-
- /**
- * Set the validation result on a parameter group. On a sequence of calls, the most
- * serious validation status is recorded, assuming the status enum ordinal increase in
- * order of severity
- *
- * @param status The validation status the parameter group is receiving
- */
- public void setResult(final ValidationStatus status) {
- if (this.status.ordinal() < status.ordinal()) {
- this.status = status;
- this.message = messagePrefix + status;
- }
- }
-
- /**
- * Gets the validation result.
- *
- * @param initialIndentation the indentation to use on the main result output
- * @param subIndentation the indentation to use on sub parts of the result output
- * @param showClean output information on clean fields
- * @return the result
- */
- @Override
- public String getResult(final String initialIndentation, final String subIndentation, final boolean showClean) {
- if (status == ValidationStatus.CLEAN && !showClean) {
- return null;
- }
-
- StringBuilder result = new StringBuilder();
-
- result.append(initialIndentation);
-
- addGroupTypeName(result);
-
- result.append(status);
- result.append(", ");
- result.append(message);
- result.append('\n');
-
- for (ValidationResult fieldResult : validationResultMap.values()) {
- String msg = fieldResult.getResult(initialIndentation + subIndentation, subIndentation, showClean);
- if (msg != null) {
- result.append(msg);
- }
- }
-
- return result.toString();
- }
-
- /**
- * Adds the group type and name to the result string.
- *
- * @param result result string
- */
- protected abstract void addGroupTypeName(StringBuilder result);
-}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/FieldValidator.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/FieldValidator.java
new file mode 100644
index 00000000..d441c286
--- /dev/null
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/FieldValidator.java
@@ -0,0 +1,292 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters;
+
+import com.google.gson.annotations.SerializedName;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AnnotatedParameterizedType;
+import java.lang.reflect.AnnotatedType;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Collection;
+import java.util.Map;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.Setter;
+import org.apache.commons.lang3.StringUtils;
+import org.onap.policy.common.parameters.annotations.NotNull;
+
+/**
+ * Validator of the contents of a field, supporting the parameter annotations.
+ */
+public class FieldValidator extends ValueValidator {
+
+ /**
+ * {@code True} if there is a field-level annotation, {@code false} otherwise.
+ */
+ @Getter
+ @Setter(AccessLevel.PROTECTED)
+ private boolean fieldAnnotated = false;
+
+ /**
+ * Class containing the field of interest.
+ */
+ private final Class<?> clazz;
+
+ /**
+ * Field of interest.
+ */
+ private final Field field;
+
+ /**
+ * Name of the field when serialized (i.e., as the client would know it).
+ */
+ private final String serializedName;
+
+ /**
+ * Method to retrieve the field's value.
+ */
+ private Method accessor;
+
+
+ /**
+ * Constructs the object.
+ *
+ * @param validator provider of validation methods
+ * @param clazz class containing the field
+ * @param field field whose value is to be validated
+ */
+ public FieldValidator(BeanValidator validator, Class<?> clazz, Field field) {
+ this.clazz = clazz;
+ this.field = field;
+
+ String fieldName = field.getName();
+ if (fieldName.contains("$")) {
+ serializedName = fieldName;
+ return;
+ }
+
+ SerializedName serAnnot = field.getAnnotation(SerializedName.class);
+ serializedName = (serAnnot != null ? serAnnot.value() : fieldName);
+
+ validator.addValidators(this);
+ addListValidator(validator);
+ addMapValidator(validator);
+
+ if (checkers.isEmpty()) {
+ // has no annotations - nothing to check
+ return;
+ }
+
+ // verify the field type is of interest
+ int mod = field.getModifiers();
+ if (Modifier.isStatic(mod)) {
+ classOnly(clazz.getName() + "." + fieldName + " is annotated but the field is static");
+ checkers.clear();
+ return;
+ }
+
+ // get the field's "getter" method
+ accessor = getAccessor(clazz, fieldName);
+ if (accessor == null) {
+ classOnly(clazz.getName() + "." + fieldName + " is annotated but has no \"get\" method");
+ checkers.clear();
+ return;
+ }
+
+ // determine if null is allowed
+ if (field.getAnnotation(NotNull.class) != null || clazz.getAnnotation(NotNull.class) != null) {
+ setNullAllowed(false);
+ }
+ }
+
+ /**
+ * Adds validators for the individual items within a collection, if the field is a
+ * collection.
+ *
+ * @param validator provider of validation methods
+ */
+ private void addListValidator(BeanValidator validator) {
+ if (!Collection.class.isAssignableFrom(field.getType())) {
+ return;
+ }
+
+ var tannot = field.getAnnotatedType();
+ if (!(tannot instanceof AnnotatedParameterizedType)) {
+ return;
+ }
+
+ AnnotatedType[] targs = ((AnnotatedParameterizedType) tannot).getAnnotatedActualTypeArguments();
+ if (targs.length != 1) {
+ return;
+ }
+
+ var itemValidator = new ItemValidator(validator, targs[0]);
+ if (itemValidator.isEmpty()) {
+ return;
+ }
+
+ checkers.add((result, fieldName, value) -> validator.verCollection(result, fieldName, itemValidator, value));
+ }
+
+ /**
+ * Adds validators for the individual entries within a map, if the field is a map.
+ *
+ * @param validator provider of validation methods
+ */
+ private void addMapValidator(BeanValidator validator) {
+ if (!Map.class.isAssignableFrom(field.getType())) {
+ return;
+ }
+
+ var tannot = field.getAnnotatedType();
+ if (!(tannot instanceof AnnotatedParameterizedType)) {
+ return;
+ }
+
+ AnnotatedType[] targs = ((AnnotatedParameterizedType) tannot).getAnnotatedActualTypeArguments();
+ if (targs.length != 2) {
+ return;
+ }
+
+ var keyValidator = new ItemValidator(validator, targs[0]);
+ var valueValidator = new ItemValidator(validator, targs[1]);
+ if (keyValidator.isEmpty() && valueValidator.isEmpty()) {
+ return;
+ }
+
+ checkers.add((result, fieldName, value) -> validator.verMap(result, fieldName, keyValidator, valueValidator,
+ value));
+ }
+
+ /**
+ * Performs validation of a single field.
+ *
+ * @param result validation results are added here
+ * @param object object whose field is to be validated
+ */
+ public void validateField(BeanValidationResult result, Object object) {
+ if (isEmpty()) {
+ // has no annotations - nothing to check
+ return;
+ }
+
+ // get the value
+ Object value = getValue(object, accessor);
+
+ validateValue(result, serializedName, value);
+ }
+
+ /**
+ * Gets the value from the object using the accessor function.
+ *
+ * @param object object whose value is to be retrieved
+ * @param accessor "getter" method
+ * @return the object's value
+ */
+ private Object getValue(Object object, Method accessor) {
+ try {
+ return accessor.invoke(object);
+
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ throw new IllegalArgumentException(clazz.getName() + "." + field.getName() + " accessor threw an exception",
+ e);
+ }
+ }
+
+ /**
+ * Throws an exception if there are field-level annotations.
+ *
+ * @param exceptionMessage exception message
+ */
+ private void classOnly(String exceptionMessage) {
+ if (isFieldAnnotated()) {
+ throw new IllegalArgumentException(exceptionMessage);
+ }
+ }
+
+ /**
+ * Gets an annotation from the field or the class.
+ *
+ * @param annotClass annotation class of interest
+ * @return the annotation, or {@code null} if neither the field nor the class has the
+ * desired annotation
+ */
+ @Override
+ public <T extends Annotation> T getAnnotation(Class<T> annotClass) {
+
+ // field annotation takes precedence over class annotation
+ var annot = field.getAnnotation(annotClass);
+ if (annot != null) {
+ setFieldAnnotated(true);
+ return annot;
+ }
+
+ return clazz.getAnnotation(annotClass);
+ }
+
+ /**
+ * Gets an accessor method for the given field.
+ *
+ * @param clazz class whose methods are to be searched
+ * @param fieldName field whose "getter" is to be identified
+ * @return the field's "getter" method, or {@code null} if it is not found
+ */
+ private Method getAccessor(Class<?> clazz, String fieldName) {
+ var capname = StringUtils.capitalize(fieldName);
+ var accessor2 = getMethod(clazz, "get" + capname);
+ if (accessor2 != null) {
+ return accessor2;
+ }
+
+ return getMethod(clazz, "is" + capname);
+ }
+
+ /**
+ * Gets the "getter" method having the specified name.
+ *
+ * @param clazz class whose methods are to be searched
+ * @param methodName name of the method of interest
+ * @return the method, or {@code null} if it is not found
+ */
+ private Method getMethod(Class<?> clazz, String methodName) {
+ for (Method method : clazz.getMethods()) {
+ if (methodName.equals(method.getName()) && validMethod(method)) {
+ return method;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Determines if a method is a valid "getter".
+ *
+ * @param method method to be checked
+ * @return {@code true} if the method is a valid "getter", {@code false} otherwise
+ */
+ private boolean validMethod(Method method) {
+ int mod = method.getModifiers();
+ return !(Modifier.isStatic(mod) || method.getReturnType() == void.class || method.getParameterCount() != 0);
+ }
+}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java
deleted file mode 100644
index 2a616dba..00000000
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters;
-
-import java.lang.reflect.Field;
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * This class holds the result of the validation of a map of parameter groups.
- */
-public class GroupMapValidationResult extends CommonGroupValidationResult {
- // The name of the parameter group map
- final String mapParameterName;
-
- /**
- * Constructor, create the group map validation result.
- *
- * @param field the map parameter field
- * @param mapObject the value of the map parameter field
- */
- protected GroupMapValidationResult(final Field field, final Object mapObject) {
- super(ParameterConstants.PARAMETER_GROUP_MAP_HAS_STATUS_MESSAGE);
-
- this.mapParameterName = field.getName();
-
- // Cast the map object to a map of parameter groups keyed by string, we can't type check maps
- // due to restrictions on generics so we have to check each entry key is a string and each entry
- // value is a parameter group
- @SuppressWarnings("unchecked")
- Map<String, ParameterGroup> parameterGroupMap = (Map<String, ParameterGroup>) mapObject;
-
- // Add a validation result per map entry
- for (Entry<String, ParameterGroup> parameterGroupMapEntry : parameterGroupMap.entrySet()) {
- // Create a validation status entry for the map
- validationResultMap.put(parameterGroupMapEntry.getKey(),
- new GroupValidationResult(parameterGroupMapEntry.getValue()));
- }
- }
-
- /**
- * Gets the name of the parameter being validated.
- *
- * @return the name
- */
- @Override
- public String getName() {
- return mapParameterName;
- }
-
- /**
- * Set the validation result on a parameter map entry.
- *
- * @param entryName The name of the parameter map entry
- * @param status The validation status for the entry
- * @param message The validation message for the entry
- */
- public void setResult(final String entryName, final ValidationStatus status, final String message) {
- ValidationResult validationResult = validationResultMap.get(entryName);
- if (validationResult == null) {
- throw new ParameterRuntimeException("no entry with name \"" + entryName + "\" exists");
- }
-
- // Set the status of the parameter group and replace the field result
- validationResult.setResult(status, message);
- this.setResult(status);
- }
-
-
- /**
- * Set the validation result on a parameter map entry.
- *
- * @param entryName The name of the parameter map entry
- * @param mapEntryValidationResult The validation result for the entry
- */
- public void setResult(final String entryName, final ValidationResult mapEntryValidationResult) {
- ValidationResult validationResult = validationResultMap.get(entryName);
- if (validationResult == null) {
- throw new ParameterRuntimeException("no entry with name \"" + entryName + "\" exists");
- }
-
- // Set the status of the parameter group and replace the field result
- validationResultMap.put(entryName, mapEntryValidationResult);
- this.setResult(mapEntryValidationResult.getStatus());
- }
-
- @Override
- protected void addGroupTypeName(StringBuilder result) {
- result.append("parameter group map \"");
- result.append(mapParameterName);
- result.append("\" ");
- }
-} \ No newline at end of file
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java
deleted file mode 100644
index fd680451..00000000
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java
+++ /dev/null
@@ -1,391 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.apache.commons.lang3.StringUtils;
-
-/**
- * This class holds the result of the validation of a parameter group.
- */
-public class GroupValidationResult extends CommonGroupValidationResult {
- // The parameter group which the validation result applies
- private final ParameterGroup parameterGroup;
-
- /**
- * Constructor, create the field validation result with default arguments.
- *
- * @param parameterGroup the parameter group being validated
- */
- public GroupValidationResult(final ParameterGroup parameterGroup) {
- super(ParameterConstants.PARAMETER_GROUP_HAS_STATUS_MESSAGE);
-
- this.parameterGroup = parameterGroup;
-
- // Parameter group definitions may be optional
- if (parameterGroup == null) {
- return;
- }
-
- // Add a validation result for all fields in the declared class
- for (Field field : parameterGroup.getClass().getDeclaredFields()) {
- // Check if a validation result should be added for this declared field
- if (isIncludedField(field)) {
- // Set a validation result for the field
- validationResultMap.put(field.getName(), getSetValidationResult(field, parameterGroup));
- }
- }
-
- // Add a validation result for protected and public fields in super classes
- for (Field field : getSuperclassFields(parameterGroup.getClass().getSuperclass())) {
- // Check if a validation result should be added for this declared field
- if (isIncludedField(field)) {
- // Set a validation result for the field
- validationResultMap.putIfAbsent(field.getName(), getSetValidationResult(field, parameterGroup));
- }
- }
- }
-
- /**
- * Construct a validation result for a field, updating "this" status.
- *
- * @param field The parameter field
- * @param ParameterGroup The parameter group containing the field
- * @return the validation result
- * @throws Exception on accessing private fields
- */
- private ValidationResult getSetValidationResult(Field field, ParameterGroup parameterGroup) {
- ValidationResult result = getValidationResult(field, parameterGroup);
- setResult(result.getStatus());
-
- return result;
- }
-
- /**
- * Construct a validation result for a field.
- *
- * @param field The parameter field
- * @param ParameterGroup The parameter group containing the field
- * @return the validation result
- * @throws Exception on accessing private fields
- */
- private ValidationResult getValidationResult(final Field field, final ParameterGroup parameterGroup) {
- final String fieldName = field.getName();
- final Class<?> fieldType = field.getType();
- final Object fieldObject = getObjectField(parameterGroup, field);
-
- // perform null checks
- ParameterValidationResult result = new ParameterValidationResult(field, fieldObject);
- if (!result.isValid()) {
- return result;
- }
-
- // Nested parameter groups are allowed
- if (ParameterGroup.class.isAssignableFrom(fieldType)) {
- if (null != fieldObject) {
- return ((ParameterGroup) fieldObject).validate();
- }
- else {
- return new GroupValidationResult((ParameterGroup) fieldObject);
- }
- }
-
- // Nested maps of parameter groups are allowed
- if (Map.class.isAssignableFrom(field.getType())) {
- checkMapIsParameterGroupMap(fieldName, fieldObject);
- return new GroupMapValidationResult(field, fieldObject);
- }
-
- // Collections of parameter groups are not allowed
- if (Collection.class.isAssignableFrom(field.getType())) {
- checkCollection4ParameterGroups(fieldName, fieldObject);
- return result;
- }
-
- // It's a regular parameter
- return result;
- }
-
- /**
- * Get the value of a field in an object using a getter found with reflection.
- *
- * @param targetObject The object on which to read the field value
- * @param fieldName The name of the field
- * @return The field value
- */
- private Object getObjectField(final Object targetObject, final Field field) {
- String getterMethodName;
-
- // Check for Boolean fields, the convention for boolean getters is that they start with "is"
- // If the field name already starts with "is" then the getter has the field name otherwise
- // the field name is prepended with "is"
- if (boolean.class.equals(field.getType())) {
- if (field.getName().startsWith("is")) {
- getterMethodName = field.getName();
- } else {
- getterMethodName = "is" + StringUtils.capitalize(field.getName());
- }
- } else {
- getterMethodName = "get" + StringUtils.capitalize(field.getName());
- }
-
- // Look up the getter method for the field
- Method getterMethod;
- try {
- getterMethod = targetObject.getClass().getMethod(getterMethodName, (Class<?>[]) null);
- } catch (NoSuchMethodException | SecurityException e) {
- throw new ParameterRuntimeException("could not get getter method for parameter \"" + field.getName() + "\"",
- e);
- }
-
- // Invoke the getter
- try {
- return getterMethod.invoke(targetObject, (Object[]) null);
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- throw new ParameterRuntimeException("error calling getter method for parameter \"" + field.getName() + "\"",
- e);
- }
- }
-
- /**
- * Check if this field is a map of parameter groups indexed by string keys.
- *
- * @param fieldName the name of the collection field.
- * @param mapObject the map object to check
- */
- private void checkMapIsParameterGroupMap(String fieldName, Object mapObject) {
- if (mapObject == null) {
- throw new ParameterRuntimeException("map parameter \"" + fieldName + "\" is null");
- }
-
- Map<?, ?> incomingMap = (Map<?, ?>) mapObject;
-
- for (Entry<?, ?> mapEntry : incomingMap.entrySet()) {
- // Check the key is a string
- if (!String.class.isAssignableFrom(mapEntry.getKey().getClass())) {
- throw new ParameterRuntimeException("map entry is not a parameter group keyed by a string, key \""
- + mapEntry.getKey() + "\" in map \"" + fieldName + "\" is not a string");
- }
-
- // Check the value is a parameter group
- if (!ParameterGroup.class.isAssignableFrom(mapEntry.getValue().getClass())) {
- throw new ParameterRuntimeException("map entry is not a parameter group keyed by a string, value \""
- + mapEntry.getValue() + "\" in map \"" + fieldName + "\" is not a parameter group");
- }
- }
- }
-
- /**
- * Check if this field contains parameter groups.
- *
- * @param fieldName the name of the collection field.
- * @param collectionObject the collection object to check
- */
- private void checkCollection4ParameterGroups(final String fieldName, final Object collectionObject) {
- if (collectionObject == null) {
- throw new ParameterRuntimeException("collection parameter \"" + fieldName + "\" is null");
- }
-
- Collection<?> collection2Check = (Collection<?>) collectionObject;
-
- for (Object collectionMember : collection2Check) {
- if (ParameterGroup.class.isAssignableFrom(collectionMember.getClass())) {
- throw new ParameterRuntimeException("collection parameter \"" + fieldName + "\" is illegal,"
- + " parameter groups are not allowed as collection members");
- }
- }
- }
-
- /**
- * Gets the parameter group for this validation result.
- *
- * @return the parameter class
- */
- public ParameterGroup getParameterGroup() {
- return parameterGroup;
- }
-
- /**
- * Gets the name of the parameter group being validated.
- *
- * @return the name
- */
- @Override
- public String getName() {
- return parameterGroup.getName();
- }
-
- /**
- * Set the validation result on a parameter in a parameter group.
- *
- * @param parameterName The name of the parameter
- * @param status The validation status the field is receiving
- * @param message The validation message explaining the validation status
- */
- public void setResult(final String parameterName, final ValidationStatus status, final String message) {
- ValidationResult validationResult = validationResultMap.get(parameterName);
-
- if (validationResult == null) {
- throw new ParameterRuntimeException("no parameter field exists for parameter: " + parameterName);
- }
-
- // Set the status and the message on the result irrespective of validation result type
- validationResult.setResult(status, message);
-
- // Set the status of this result
- this.setResult(status);
- }
-
- /**
- * Set the validation result on a nested parameter group.
- *
- * @param parameterName The name of the parameter field
- * @param nestedValidationResult The validation result from a nested field
- */
- public void setResult(final String parameterName, final ValidationResult nestedValidationResult) {
- GroupValidationResult groupValidationResult;
- try {
- groupValidationResult = (GroupValidationResult) validationResultMap.get(parameterName);
- } catch (ClassCastException e) {
- throw new ParameterRuntimeException("parameter is not a nested group parameter: " + parameterName, e);
- }
-
- if (groupValidationResult == null) {
- throw new ParameterRuntimeException("no nested parameter field exists for parameter: " + parameterName);
- }
-
- // Set the status of the parameter group and replace the field result
- validationResultMap.put(parameterName, nestedValidationResult);
- this.setResult(nestedValidationResult.getStatus());
- }
-
- /**
- * Set the validation result on a nested parameter group map entry.
- *
- * @param parameterName The name of the parameter field
- * @param key The key of the map entry
- * @param nestedMapValidationResult The validation result from a nested map entry
- */
- public void setResult(final String parameterName, final String key,
- final ValidationResult nestedMapValidationResult) {
- GroupMapValidationResult groupMapValidationResult;
- try {
- groupMapValidationResult = (GroupMapValidationResult) validationResultMap.get(parameterName);
- } catch (ClassCastException e) {
- throw new ParameterRuntimeException("parameter is not a nested group map parameter: " + parameterName, e);
- }
-
- if (groupMapValidationResult == null) {
- throw new ParameterRuntimeException("no group map parameter field exists for parameter: " + parameterName);
- }
-
- // Set the status of the parameter group and the field
- groupMapValidationResult.setResult(key, nestedMapValidationResult);
- this.setResult(nestedMapValidationResult.getStatus());
- }
-
- /**
- * Set the validation status on a group map entry.
- *
- * @param parameterName The name of the parameter field
- * @param key The key of the map entry
- * @param status The validation status of the entry
- * @param message The message for the parameter group
- */
- public void setResult(final String parameterName, final String key, final ValidationStatus status,
- final String message) {
- GroupMapValidationResult groupMapValidationResult;
- try {
- groupMapValidationResult = (GroupMapValidationResult) validationResultMap.get(parameterName);
- } catch (ClassCastException e) {
- throw new ParameterRuntimeException("parameter is not a nested group map parameter: " + parameterName, e);
- }
-
- if (groupMapValidationResult == null) {
- throw new ParameterRuntimeException("no group map parameter field exists for parameter: " + parameterName);
- }
-
- // Set the status of the parameter group and the field
- groupMapValidationResult.setResult(key, status, message);
- this.setResult(status);
- }
-
- @Override
- protected void addGroupTypeName(StringBuilder result) {
- result.append("parameter group \"");
-
- if (parameterGroup != null) {
- result.append(parameterGroup.getName());
- result.append("\" type \"");
- result.append(parameterGroup.getClass().getName());
- } else {
- result.append("UNDEFINED");
- }
-
- result.append("\" ");
- }
-
-
- /**
- * Check if a field should be included for validation.
- *
- * @param field the field to check for inclusion
- * @return true of the field should be included
- */
- private boolean isIncludedField(final Field field) {
- return !field.getName().startsWith("$") && !field.getName().startsWith("_")
- && !Modifier.isStatic(field.getModifiers());
- }
-
- /**
- * Get the public and protected fields of super classes.
- * @param firstSuperClass the first superclass to check
- *
- * @return a set of the superclass fields
- */
- private List<Field> getSuperclassFields(final Class<?> firstSuperClass) {
- List<Field> superclassFields = new ArrayList<>();
-
- Class<?> currentClass = firstSuperClass;
- while (currentClass.getSuperclass() != null) {
- for (Field field : currentClass.getDeclaredFields()) {
- // Check if this field is public or protected
- if (Modifier.isPublic(field.getModifiers()) || Modifier.isProtected(field.getModifiers())) {
- superclassFields.add(field);
- }
- }
-
- // Check the next super class down
- currentClass = currentClass.getSuperclass();
- }
-
- return superclassFields;
- }
-}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ItemValidator.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ItemValidator.java
new file mode 100644
index 00000000..44b70cdf
--- /dev/null
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ItemValidator.java
@@ -0,0 +1,71 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AnnotatedType;
+
+/**
+ * Validator of an "item", which is typically found in a collection, or the key or value
+ * components of an entry in a Map.
+ */
+public class ItemValidator extends ValueValidator {
+ private final AnnotatedType annotatedType;
+
+ /**
+ * Constructs the object.
+ *
+ * @param validator provider of validation methods
+ * @param annotatedType a type having validation annotations to be
+ * applied to the item
+ */
+ public ItemValidator(BeanValidator validator, AnnotatedType annotatedType) {
+ this(validator, annotatedType, true);
+ }
+
+ /**
+ * Constructs the object.
+ *
+ * @param validator provider of validation methods
+ * @param annotatedType a type having validation annotations to be
+ * applied to the item
+ * @param addValidators {@code true} if to add validators
+ */
+ public ItemValidator(BeanValidator validator, AnnotatedType annotatedType, boolean addValidators) {
+ this.annotatedType = annotatedType;
+
+ if (addValidators) {
+ validator.addValidators(this);
+ }
+ }
+
+ /**
+ * Gets an annotation from the field or the class.
+ *
+ * @param annotClass annotation class of interest
+ * @return the annotation, or {@code null} if the {@link #annotatedType} does
+ * not contain the desired annotation
+ */
+ @Override
+ public <T extends Annotation> T getAnnotation(Class<T> annotClass) {
+ return annotatedType.getAnnotation(annotClass);
+ }
+}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java
index e5597206..af1884a3 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java
@@ -1,6 +1,6 @@
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -40,6 +40,8 @@ public class ObjectValidationResult extends ValidationResultImpl {
*
* @param name name of the object of this result
* @param object object being validated
+ * @param status result status
+ * @param message result message
*/
public ObjectValidationResult(String name, Object object, ValidationStatus status, String message) {
super(name, object, status, message);
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java
index 240b1f40..300d49c7 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java
@@ -1,45 +1,43 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.common.parameters;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+
/**
* This static class holds the values of constants for parameter handling.
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ParameterConstants {
// Indentation is 0 on the left and 2 for each level of hierarchy
public static final String DEFAULT_INITIAL_RESULT_INDENTATION = "";
public static final String DEFAULT_RESULT_INDENTATION = " ";
-
+
// By default we do not show validation results for parameters that are validated as clean
public static final boolean DO_NOT_SHOW_CLEAN_RESULTS = false;
-
+
// Messages for clean validations
public static final String PARAMETER_GROUP_HAS_STATUS_MESSAGE = "parameter group has status ";
public static final String PARAMETER_GROUP_MAP_HAS_STATUS_MESSAGE = "parameter group map has status ";
public static final String PARAMETER_HAS_STATUS_MESSAGE = "parameter has status ";
-
- /**
- * Private constructor to prevent subclassing.
- */
- private ParameterConstants() {
- // Private constructor to prevent subclassing
- }
-} \ No newline at end of file
+}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java
index 0b29a4e6..aa3105ef 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,6 +21,8 @@
package org.onap.policy.common.parameters;
+import lombok.Getter;
+
/**
* Exception thrown oon parameter reading, validation, and check errors.
*
@@ -29,6 +32,7 @@ public class ParameterException extends Exception {
private static final long serialVersionUID = -8507246953751956974L;
// The object on which the exception was thrown
+ @Getter
private final transient Object object;
/**
@@ -84,28 +88,19 @@ public class ParameterException extends Exception {
/**
* Build a cascaded message from an exception and all its nested exceptions.
- *
+ *
* @param throwable the top level exception
* @return cascaded message string
*/
public static String buildCascadedMessage(final Throwable throwable) {
- final StringBuilder builder = new StringBuilder();
+ final var builder = new StringBuilder();
builder.append(throwable.getMessage());
- for (Throwable t = throwable; t != null; t = t.getCause()) {
+ for (var t = throwable; t != null; t = t.getCause()) {
builder.append("\ncaused by: ");
builder.append(t.getMessage());
}
return builder.toString();
}
-
- /**
- * Get the object on which the exception was thrown.
- *
- * @return The object on which the exception was thrown
- */
- public Object getObject() {
- return object;
- }
}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java
index 8bfa183b..ab610933 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java
@@ -1,19 +1,20 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
@@ -29,28 +30,28 @@ package org.onap.policy.common.parameters;
public interface ParameterGroup {
/**
* Get the group name.
- *
+ *
* @return the group name
*/
public String getName();
/**
* Set the group name.
- *
+ *
* @param name the group name
*/
public void setName(final String name);
/**
* Validate parameters.
- *
+ *
* @return the result of the parameter validation
*/
- GroupValidationResult validate();
+ BeanValidationResult validate();
/**
* Check if the parameters are valid.
- *
+ *
* @return true if the parameters are valid
*/
default boolean isValid() {
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java
index f0f34ac1..8a987bdd 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,7 +20,9 @@
package org.onap.policy.common.parameters;
+import lombok.AllArgsConstructor;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
import org.onap.policy.common.parameters.annotations.NotBlank;
import org.onap.policy.common.parameters.annotations.NotNull;
@@ -32,30 +34,16 @@ import org.onap.policy.common.parameters.annotations.NotNull;
@NotBlank
@Getter
@Setter
+@NoArgsConstructor
+@AllArgsConstructor
public class ParameterGroupImpl implements ParameterGroup {
/**
- * Group name. Note: this MUST not be "private" or it will not be validated.
+ * Group name.
*/
- protected String name;
-
- /**
- * Constructs the object, with a {@code null} name.
- */
- public ParameterGroupImpl() {
- this.name = null;
- }
-
- /**
- * Constructs the object.
- *
- * @param name the group's name
- */
- public ParameterGroupImpl(String name) {
- this.name = name;
- }
+ private String name;
@Override
- public GroupValidationResult validate() {
- return new GroupValidationResult(this);
+ public BeanValidationResult validate() {
+ return new BeanValidator().validateTop(getClass().getSimpleName(), this);
}
}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java
index 071593a9..4eb79447 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java
@@ -1,25 +1,28 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.common.parameters;
+import lombok.Getter;
+
/**
* A run time exception thrown on parameter validations.
*
@@ -29,6 +32,7 @@ public class ParameterRuntimeException extends RuntimeException {
private static final long serialVersionUID = -8507246953751956974L;
// The object on which the exception was thrown
+ @Getter
private final transient Object object;
/**
@@ -81,13 +85,4 @@ public class ParameterRuntimeException extends RuntimeException {
public String getCascadedMessage() {
return ParameterException.buildCascadedMessage(this);
}
-
- /**
- * Get the object on which the exception was thrown.
- *
- * @return The object
- */
- public Object getObject() {
- return object;
- }
}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java
index 358e5535..a368d25f 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java
@@ -1,19 +1,20 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
@@ -24,37 +25,32 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
/**
* The parameter service makes ONAP PF parameter groups available to all classes in a JVM.
- *
+ *
* <p>The reason for having a parameter service is to avoid having to pass parameters down long call chains in modules
* such as PDPs and editors. The parameter service makes correct and verified parameters available statically.
- *
+ *
* <p>The parameter service must be used with care because changing a parameter set anywhere in a JVM will affect all
* users of those parameters anywhere in the JVM.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
-public abstract class ParameterService {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class ParameterService {
// The map holding the parameters
private static Map<String, ParameterGroup> parameterGroupMap = new ConcurrentHashMap<>();
/**
- * This class is an abstract static class that cannot be extended.
- */
- private ParameterService() {
- }
-
- /**
* Register a parameter group with the parameter service.
*
* @param parameterGroup the parameter group
*/
public static void register(final ParameterGroup parameterGroup) {
- if (!parameterGroupMap.containsKey(parameterGroup.getName())) {
- parameterGroupMap.put(parameterGroup.getName(), parameterGroup);
- } else {
+ if (parameterGroupMap.putIfAbsent(parameterGroup.getName(), parameterGroup) != null) {
throw new ParameterRuntimeException(
"\"" + parameterGroup.getName() + "\" already registered in parameter service");
}
@@ -70,7 +66,7 @@ public abstract class ParameterService {
if (overwrite && parameterGroupMap.containsKey(parameterGroup.getName())) {
deregister(parameterGroup);
}
-
+
register(parameterGroup);
}
@@ -80,9 +76,7 @@ public abstract class ParameterService {
* @param parameterGroupName the name of the parameter group
*/
public static void deregister(final String parameterGroupName) {
- if (parameterGroupMap.containsKey(parameterGroupName)) {
- parameterGroupMap.remove(parameterGroupName);
- } else {
+ if (parameterGroupMap.remove(parameterGroupName) == null) {
throw new ParameterRuntimeException("\"" + parameterGroupName + "\" not registered in parameter service");
}
}
@@ -104,7 +98,7 @@ public abstract class ParameterService {
*/
public static <T extends ParameterGroup> T get(final String parameterGroupName) {
@SuppressWarnings("unchecked")
- final T parameterGroup = (T) parameterGroupMap.get(parameterGroupName);
+ final var parameterGroup = (T) parameterGroupMap.get(parameterGroupName);
if (parameterGroup == null) {
throw new ParameterRuntimeException("\"" + parameterGroupName + "\" not found in parameter service");
@@ -120,7 +114,7 @@ public abstract class ParameterService {
* @return true if the parameter is defined
*/
public static boolean contains(final String parameterGroupName) {
- return parameterGroupMap.containsKey(parameterGroupName) && parameterGroupMap.get(parameterGroupName) != null;
+ return parameterGroupMap.get(parameterGroupName) != null;
}
/**
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java
index 35837376..7e56230d 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java
@@ -1,7 +1,7 @@
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications 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.
@@ -73,7 +73,7 @@ public class ParameterValidationResult implements ValidationResult {
* @param parameterValue field's value
*/
private void checkMinValue(final Field field, final Object parameterValue) {
- Min minAnnot = field.getAnnotation(Min.class);
+ var minAnnot = field.getAnnotation(Min.class);
if (minAnnot != null && ((Number) parameterValue).longValue() < minAnnot.value()) {
setResult(ValidationStatus.INVALID, "must be >= " + minAnnot.value());
}
@@ -86,7 +86,7 @@ public class ParameterValidationResult implements ValidationResult {
* @param parameterValue field's value
*/
private void checkMaxValue(final Field field, final Object parameterValue) {
- Max maxAnnot = field.getAnnotation(Max.class);
+ var maxAnnot = field.getAnnotation(Max.class);
if (maxAnnot != null && ((Number) parameterValue).longValue() > maxAnnot.value()) {
setResult(ValidationStatus.INVALID, "must be <= " + maxAnnot.value());
}
@@ -102,7 +102,7 @@ public class ParameterValidationResult implements ValidationResult {
* @return the field's annotation, or {@code null} if it does not exist
*/
private static <T extends Annotation> T getAnyAnnotation(final Field field, Class<T> annotClass) {
- T annot = field.getAnnotation(annotClass);
+ var annot = field.getAnnotation(annotClass);
if (annot != null) {
return annot;
}
@@ -157,21 +157,13 @@ public class ParameterValidationResult implements ValidationResult {
return null;
}
- StringBuilder validationResultBuilder = new StringBuilder();
-
- validationResultBuilder.append(initialIndentation);
- validationResultBuilder.append("field \"");
- validationResultBuilder.append(getName());
- validationResultBuilder.append("\" type \"");
- validationResultBuilder.append(field.getType().getName());
- validationResultBuilder.append("\" value \"");
- validationResultBuilder.append(parameterValue);
- validationResultBuilder.append("\" ");
- validationResultBuilder.append(getStatus());
- validationResultBuilder.append(", ");
- validationResultBuilder.append(message);
- validationResultBuilder.append('\n');
-
- return validationResultBuilder.toString();
+ return initialIndentation
+ + "field \"" + getName()
+ + "\" type \"" + field.getType().getName()
+ + "\" value \"" + parameterValue
+ + "\" " + getStatus()
+ + ", "
+ + message
+ + '\n';
}
}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java
index 1d8aa239..45898818 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java
@@ -1,6 +1,7 @@
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,12 +21,14 @@
package org.onap.policy.common.parameters;
+import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Basic implementation of a ValidationResult.
*/
@Getter
+@AllArgsConstructor
public abstract class ValidationResultImpl implements ValidationResult {
public static final String ITEM_HAS_STATUS_MESSAGE = "item has status ";
@@ -56,27 +59,12 @@ public abstract class ValidationResultImpl implements ValidationResult {
* @param name name of the object of this result
* @param object object being validated
*/
- public ValidationResultImpl(String name, Object object) {
+ protected ValidationResultImpl(String name, Object object) {
this.name = name;
this.object = object;
}
/**
- * Constructs the object.
- *
- * @param name name of the object of this result
- * @param object object being validated
- * @param status the validation status
- * @param message the validation message explaining the validation status
- */
- public ValidationResultImpl(String name, Object object, ValidationStatus status, String message) {
- this.name = name;
- this.object = object;
- this.status = status;
- this.message = message;
- }
-
- /**
* Validates that the value is not {@code null}.
*
* @return {@code true} if the value is not null, {@code false} otherwise
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ValueValidator.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ValueValidator.java
new file mode 100644
index 00000000..faf41008
--- /dev/null
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ValueValidator.java
@@ -0,0 +1,146 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters;
+
+import java.lang.annotation.Annotation;
+import java.util.ArrayList;
+import java.util.List;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import org.onap.policy.common.parameters.annotations.NotNull;
+
+/**
+ * Validator of a value.
+ * <p/>
+ * Note: this currently does not support Min/Max validation of "short" or "byte"; these
+ * annotations are simply ignored for these types.
+ */
+@NoArgsConstructor
+public class ValueValidator {
+
+ /**
+ * {@code True} if the value is allowed to be {@code null}, {@code false} otherwise.
+ * Subclasses are expected to set this, typically based on the validation annotations
+ * associated with the value.
+ */
+ @Getter
+ @Setter(AccessLevel.PROTECTED)
+ private boolean nullAllowed = true;
+
+ /**
+ * Predicates to invoke to validate an object.
+ * <p/>
+ * Note: each predicate is expected to return {@code true} if the next check is
+ * allowed to proceed, {@code false} otherwise. In addition, if {@link #nullAllowed}
+ * is {@code true}, then the predicates must be prepared to deal with a {@code null}
+ * Object as their input parameter.
+ */
+ protected List<Checker> checkers = new ArrayList<>(10);
+
+ /**
+ * Determines if the validator has anything to check.
+ *
+ * @return {@code true} if the validator is empty (i.e., has nothing to check)
+ */
+ public boolean isEmpty() {
+ return checkers.isEmpty();
+ }
+
+ /**
+ * Performs validation of a single field.
+ *
+ * @param result validation results are added here
+ * @param fieldName field whose value is being verified
+ * @param value value to be validated
+ */
+ protected void validateValue(BeanValidationResult result, String fieldName, Object value) {
+
+ if (value == null && isNullAllowed()) {
+ // value is null and null is allowed - just return
+ return;
+ }
+
+ for (Checker checker : checkers) {
+ if (!checker.test(result, fieldName, value)) {
+ // invalid - don't bother with additional checks
+ return;
+ }
+ }
+ }
+
+ /**
+ * Looks for an annotation at the class or field level. If an annotation is found at
+ * either the field or class level, then it adds a verifier to
+ * {@link ValueValidator#checkers}.
+ *
+ * @param annotClass class of annotation to find
+ * @param checker function to validate the value
+ */
+ public <T extends Annotation> void addAnnotation(Class<T> annotClass, Checker checker) {
+ var annot = getAnnotation(annotClass);
+ if (annot != null) {
+ checkers.add(checker);
+
+ if (annotClass == NotNull.class) {
+ setNullAllowed(false);
+ }
+ }
+ }
+
+ /**
+ * Looks for an annotation at the class or field level. If an annotation is found at
+ * either the field or class level, then it adds a verifier to
+ * {@link ValueValidator#checkers}.
+ *
+ * @param annotClass class of annotation to find
+ * @param checker function to validate the value
+ */
+ public <T extends Annotation> void addAnnotation(Class<T> annotClass, CheckerWithAnnot<T> checker) {
+ var annot = getAnnotation(annotClass);
+ if (annot != null) {
+ checkers.add((result, fieldName, value) -> checker.test(result, fieldName, annot, value));
+ }
+ }
+
+ /**
+ * Gets an annotation from the field or the class. The default method simply returns
+ * {@code null}.
+ *
+ * @param annotClass annotation class of interest
+ * @return the annotation, or {@code null} if neither the field nor the class has the
+ * desired annotation
+ */
+ public <T extends Annotation> T getAnnotation(Class<T> annotClass) {
+ return null;
+ }
+
+ // functions to validate a value extracted from a field
+
+ public static interface Checker {
+ boolean test(BeanValidationResult result, String fieldName, Object value);
+ }
+
+ public static interface CheckerWithAnnot<T extends Annotation> {
+ boolean test(BeanValidationResult result, String fieldName, T annotation, Object value);
+ }
+}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/ClassName.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/ClassName.java
new file mode 100644
index 00000000..14d76fd7
--- /dev/null
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/ClassName.java
@@ -0,0 +1,37 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.TYPE_USE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+/**
+ * Indicates that a field (i.e., String) identifies the name of a class in the classpath.
+ */
+@Retention(RUNTIME)
+@Target({FIELD, TYPE_USE})
+public @interface ClassName {
+
+}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java
index 1d8fd90f..f28fd2cf 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,13 +21,14 @@
package org.onap.policy.common.parameters.annotations;
import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
-@Target(FIELD)
+@Target({FIELD, TYPE_USE})
public @interface Max {
/**
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java
index 9ad6d7e0..305d9810 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,13 +21,14 @@
package org.onap.policy.common.parameters.annotations;
import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
-@Target(FIELD)
+@Target({FIELD, TYPE_USE})
public @interface Min {
/**
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java
index 169fa593..0744beb5 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,6 +22,7 @@ package org.onap.policy.common.parameters.annotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
@@ -31,7 +32,7 @@ import java.lang.annotation.Target;
* Indicates that a field (i.e., String) may not be empty.
*/
@Retention(RUNTIME)
-@Target({TYPE, FIELD})
+@Target({TYPE, FIELD, TYPE_USE})
public @interface NotBlank {
}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java
index 3c7bc8b7..81356005 100644
--- a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,6 +22,7 @@ package org.onap.policy.common.parameters.annotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
@@ -31,7 +32,7 @@ import java.lang.annotation.Target;
* Indicates that a field may not be null.
*/
@Retention(RUNTIME)
-@Target({TYPE, FIELD})
+@Target({TYPE, FIELD, TYPE_USE})
public @interface NotNull {
}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Pattern.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Pattern.java
new file mode 100644
index 00000000..91a74d70
--- /dev/null
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Pattern.java
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.TYPE_USE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Retention(RUNTIME)
+@Target({FIELD, TYPE_USE})
+public @interface Pattern {
+
+ /**
+ * Regular expression to be matched.
+ */
+ String regexp();
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/FilterableTopicSource.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Size.java
index 27f4ceb7..160e0124 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/FilterableTopicSource.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Size.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -18,22 +18,26 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.common.endpoints.event.comm;
+package org.onap.policy.common.parameters.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.TYPE_USE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
/**
- * TopicSource that supports server-side filtering.
+ * Indicates the size of a Map or Collection.
*/
-public interface FilterableTopicSource extends TopicSource {
+@Retention(RUNTIME)
+@Target({FIELD, TYPE_USE})
+public @interface Size {
/**
- * Sets the server-side filter.
- *
- * @param filter new filter value, or {@code null}
- * @throws UnsupportedOperationException if the consumer does not support
- * server-side filtering
- * @throws IllegalArgumentException if the consumer cannot be built with the
- * new filter
+ * The minimum size allowed.
+ *
+ * @return the minimum size allowed
*/
- public void setFilter(String filter);
-
+ int min();
}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Valid.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Valid.java
new file mode 100644
index 00000000..227a726f
--- /dev/null
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Valid.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.TYPE_USE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Retention(RUNTIME)
+@Target({TYPE, FIELD, TYPE_USE})
+public @interface Valid {
+
+}
diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupConstraint.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupConstraint.java
new file mode 100644
index 00000000..c73d135a
--- /dev/null
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupConstraint.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.parameters.validation;
+
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Documented
+@Constraint(validatedBy = ParameterGroupValidator.class)
+@Target({ElementType.FIELD})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ParameterGroupConstraint {
+
+ /**
+ * Get error Message.
+ *
+ * @return error Message
+ */
+ String message() default "validation error(s) on parameters";
+
+ /**
+ * Get groups.
+ *
+ * @return Class arrays
+ */
+ Class<?>[] groups() default {};
+
+ /**
+ * Get payload.
+ *
+ * @return Class arrays
+ */
+ Class<? extends Payload>[] payload() default {};
+}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullSubGroup.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupValidator.java
index 7fe1402f..024ca139 100644
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullSubGroup.java
+++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupValidator.java
@@ -1,7 +1,6 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
+ * 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.
@@ -19,23 +18,25 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.common.parameters.testclasses;
+package org.onap.policy.common.parameters.validation;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
+import org.onap.policy.common.parameters.BeanValidationResult;
import org.onap.policy.common.parameters.ParameterGroup;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-public class ParameterGroupWithNullSubGroup extends ParameterGroupImpl {
- private ParameterGroup subGroup = null;
+public class ParameterGroupValidator implements ConstraintValidator<ParameterGroupConstraint, ParameterGroup> {
- /**
- * Create a test parameter group.
- * @param name the parameter group name
- */
- public ParameterGroupWithNullSubGroup(final String name) {
- super(name);
+ @Override
+ public boolean isValid(ParameterGroup value, ConstraintValidatorContext context) {
+ if (value == null) {
+ return true;
+ }
+ final BeanValidationResult result = value.validate();
+ if (!result.isValid()) {
+ context.buildConstraintViolationWithTemplate(result.getMessage()).addConstraintViolation();
+ }
+ return result.isValid();
}
- public ParameterGroup getSubGroup() {
- return subGroup;
- }
}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java
index b874db69..48d2f4b5 100644
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java
+++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-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.
@@ -24,7 +24,6 @@ package org.onap.policy.common.parameters;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
-
import org.junit.Test;
public class ExceptionTest {
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java
index 12cd80cb..b7bea204 100644
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java
+++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java
@@ -1,8 +1,8 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.parameters;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
@@ -27,17 +28,25 @@ import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+import java.util.function.BiConsumer;
import org.junit.Before;
import org.junit.Test;
public class TestBeanValidationResult {
+ private static final String TEXT1 = "abc";
+ private static final String TEXT2 = "def";
private static final String MY_LIST = "my-list";
+ private static final String MY_MAP = "my-map";
private static final String OBJECT = "an object";
private static final String INITIAL_INDENT = "xx ";
private static final String NEXT_INDENT = "yy ";
private static final String MID_INDENT = "xx yy ";
private static final String NAME = "my-name";
private static final String MY_LIST_INVALID = " 'my-list' INVALID, item has status INVALID\n ";
+ private static final String MY_MAP_INVALID = " 'my-map' INVALID, item has status INVALID\n ";
private static final String BEAN_INVALID_MSG = requote("'my-name' INVALID, item has status INVALID\n");
private String cleanMsg;
@@ -52,10 +61,10 @@ public class TestBeanValidationResult {
*/
@Before
public void setUp() {
- clean = new ObjectValidationResult("abc", 10);
+ clean = new ObjectValidationResult(TEXT1, 10);
cleanMsg = clean.getResult("", "", true);
- invalid = new ObjectValidationResult("def", 20);
+ invalid = new ObjectValidationResult(TEXT2, 20);
invalid.setResult(ValidationStatus.INVALID, "invalid");
invalidMsg = invalid.getResult();
@@ -83,6 +92,10 @@ public class TestBeanValidationResult {
assertEquals(INITIAL_INDENT + BEAN_INVALID_MSG + MID_INDENT + cleanMsg + MID_INDENT + invalidMsg,
bean.getResult(INITIAL_INDENT, NEXT_INDENT, true));
+
+ bean = new BeanValidationResult(NAME, OBJECT);
+ assertFalse(bean.addResult(MY_LIST, "hello", ValidationStatus.INVALID, TEXT1));
+ assertThat(bean.getResult()).contains("\"" + MY_LIST + "\" value \"hello\" INVALID, " + TEXT1);
}
@Test
@@ -150,6 +163,50 @@ public class TestBeanValidationResult {
}
+ @Test
+ public void testValidateMap() {
+ Map<String, ValidationResult> map = null;
+ bean = new BeanValidationResult(NAME, OBJECT);
+ assertTrue(bean.validateMap(MY_MAP, map, validMapEntry()));
+ assertTrue(bean.isValid());
+ assertNull(bean.getResult());
+
+ map = Map.of(TEXT1, clean, TEXT2, clean);
+ bean = new BeanValidationResult(NAME, OBJECT);
+ assertTrue(bean.validateMap(MY_MAP, map, validMapEntry()));
+ assertTrue(bean.isValid());
+ assertNull(bean.getResult());
+
+ // null value in the map
+ map = new TreeMap<>();
+ map.put(TEXT1, clean);
+ map.put(TEXT2, null);
+ bean = new BeanValidationResult(NAME, OBJECT);
+ assertFalse(bean.validateMap(MY_MAP, map, validMapEntry()));
+ assertFalse(bean.isValid());
+ assertEquals(requote(BEAN_INVALID_MSG + MY_MAP_INVALID
+ + "item 'def' value 'null' INVALID, is null\n"), bean.getResult());
+
+ map = Map.of(TEXT1, invalid, TEXT2, invalid);
+ bean = new BeanValidationResult(NAME, OBJECT);
+ assertFalse(bean.validateMap(MY_MAP, map, validMapEntry()));
+ assertFalse(bean.isValid());
+ assertEquals(requote(BEAN_INVALID_MSG + MY_MAP_INVALID + invalidMsg
+ + " " + invalidMsg), bean.getResult());
+
+ }
+
+ private BiConsumer<BeanValidationResult, Entry<String, ValidationResult>> validMapEntry() {
+ return (result, entry) -> {
+ var value = entry.getValue();
+ if (value == null) {
+ result.validateNotNull(entry.getKey(), value);
+ } else {
+ result.addResult(value);
+ }
+ };
+ }
+
private static String requote(String text) {
return text.replace('\'', '"');
}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java
new file mode 100644
index 00000000..83d0a7f9
--- /dev/null
+++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java
@@ -0,0 +1,664 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import lombok.Getter;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.parameters.annotations.ClassName;
+import org.onap.policy.common.parameters.annotations.Max;
+import org.onap.policy.common.parameters.annotations.Min;
+import org.onap.policy.common.parameters.annotations.NotBlank;
+import org.onap.policy.common.parameters.annotations.NotNull;
+import org.onap.policy.common.parameters.annotations.Pattern;
+import org.onap.policy.common.parameters.annotations.Size;
+import org.onap.policy.common.parameters.annotations.Valid;
+
+public class TestBeanValidator {
+ private static final String TOP = "top";
+ private static final String STR_FIELD = "strValue";
+ private static final String INT_FIELD = "intValue";
+ private static final String NUM_FIELD = "numValue";
+ private static final String ITEMS_FIELD = "items";
+ private static final String STRING_VALUE = "string value";
+ private static final int INT_VALUE = 20;
+
+ private BeanValidator validator;
+
+ @Before
+ public void setUp() {
+ validator = new BeanValidator();
+ }
+
+ @Test
+ public void testValidateTop_testValidateFields() {
+ // validate null
+ assertTrue(validator.validateTop(TOP, null).isValid());
+
+ // validate something that has no annotations
+ assertTrue(validator.validateTop(TOP, validator).isValid());
+
+ @NotNull
+ @Getter
+ class Data {
+ String strValue;
+ }
+
+ // one failure case
+ Data data = new Data();
+ BeanValidationResult result = validator.validateTop(TOP, data);
+ assertInvalid("testValidateFields", result, STR_FIELD, "null");
+ assertTrue(result.getResult().contains(TOP));
+
+ // one success case
+ data.strValue = STRING_VALUE;
+ assertTrue(validator.validateTop(TOP, data).isValid());
+
+ /**
+ * Repeat with a subclass.
+ */
+ @Getter
+ class Derived extends Data {
+ @Min(10)
+ int intValue;
+ }
+
+ Derived derived = new Derived();
+ derived.strValue = STRING_VALUE;
+ derived.intValue = INT_VALUE;
+
+ // success case
+ assertTrue(validator.validateTop(TOP, derived).isValid());
+
+ // failure cases
+ derived.strValue = null;
+ assertInvalid("testValidateFields", validator.validateTop(TOP, derived), STR_FIELD, "null");
+ derived.strValue = STRING_VALUE;
+
+ derived.intValue = 1;
+ assertInvalid("testValidateFields", validator.validateTop(TOP, derived), INT_FIELD, "minimum");
+ derived.intValue = INT_VALUE;
+
+ // both invalid
+ derived.strValue = null;
+ derived.intValue = 1;
+ result = validator.validateTop(TOP, derived);
+ assertInvalid("testValidateFields", result, STR_FIELD, "null");
+ assertInvalid("testValidateFields", result, INT_FIELD, "minimum");
+ derived.strValue = STRING_VALUE;
+ derived.intValue = INT_VALUE;
+ }
+
+ @Test
+ public void testVerNotNull() {
+ class NotNullCheck {
+ @Getter
+ @Min(1)
+ @NotNull
+ Integer intValue;
+ }
+
+ NotNullCheck notNullCheck = new NotNullCheck();
+ assertInvalid("testVerNotNull", validator.validateTop(TOP, notNullCheck), INT_FIELD, "null");
+
+ notNullCheck.intValue = INT_VALUE;
+ assertTrue(validator.validateTop(TOP, notNullCheck).isValid());
+
+ notNullCheck.intValue = 0;
+ assertInvalid("testVerNotNull", validator.validateTop(TOP, notNullCheck), INT_FIELD, "minimum");
+ }
+
+ @Test
+ public void testVerNotBlank() {
+ class NotBlankCheck {
+ @Getter
+ @NotBlank
+ String strValue;
+ }
+
+ NotBlankCheck notBlankCheck = new NotBlankCheck();
+
+ // null
+ assertTrue(validator.validateTop(TOP, notBlankCheck).isValid());
+
+ // empty
+ notBlankCheck.strValue = "";
+ assertInvalid("testVerNotNull", validator.validateTop(TOP, notBlankCheck), STR_FIELD, "blank");
+
+ // spaces
+ notBlankCheck.strValue = " ";
+ assertInvalid("testVerNotNull", validator.validateTop(TOP, notBlankCheck), STR_FIELD, "blank");
+
+ // not blank
+ notBlankCheck.strValue = STRING_VALUE;
+ assertTrue(validator.validateTop(TOP, notBlankCheck).isValid());
+
+ /*
+ * Class with "blank" annotation on an integer.
+ */
+ class NotBlankInt {
+ @Getter
+ @NotBlank
+ int intValue;
+ }
+
+ NotBlankInt notBlankInt = new NotBlankInt();
+ notBlankInt.intValue = 0;
+ assertTrue(validator.validateTop(TOP, notBlankInt).isValid());
+ }
+
+ /**
+ * Tests verSize with a collection.
+ */
+ @Test
+ public void testVerSizeCollection() {
+ class CollectionSizeCheck {
+ @Getter
+ @Size(min = 3)
+ Collection<Integer> items;
+ }
+
+ CollectionSizeCheck collCheck = new CollectionSizeCheck();
+
+ // valid length - exact
+ collCheck.items = List.of(1, 2, 3);
+ assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue();
+
+ // valid length - extra
+ collCheck.items = List.of(1, 2, 3, 4);
+ assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue();
+
+ // too few
+ collCheck.items = List.of(1, 2);
+ assertInvalid("testVerSize", validator.validateTop(TOP, collCheck), ITEMS_FIELD, "minimum", "3");
+
+ // null
+ collCheck.items = null;
+ assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue();
+ }
+
+ /**
+ * Tests verSize with a map.
+ */
+ @Test
+ public void testVerSizeMap() {
+ class MapSizeCheck {
+ @Getter
+ @Size(min = 3)
+ Map<Integer, Integer> items;
+ }
+
+ MapSizeCheck mapCheck = new MapSizeCheck();
+
+ // valid length - exact
+ mapCheck.items = Map.of(1, 10, 2, 20, 3, 30);
+ assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue();
+
+ // valid length - extra
+ mapCheck.items = Map.of(1, 10, 2, 20, 3, 30, 4, 40);
+ assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue();
+
+ // too few
+ mapCheck.items = Map.of(1, 10, 2, 20);
+ assertInvalid("testVerSize", validator.validateTop(TOP, mapCheck), ITEMS_FIELD, "minimum", "3");
+
+ // null
+ mapCheck.items = null;
+ assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue();
+ }
+
+ /**
+ * Tests verSize with an object for which it doesn't apply.
+ */
+ @Test
+ public void testVerSizeOther() {
+ class OtherSizeCheck {
+ @Getter
+ @Size(min = 3)
+ Integer items;
+ }
+
+ OtherSizeCheck otherCheck = new OtherSizeCheck();
+
+ otherCheck.items = 10;
+ assertThat(validator.validateTop(TOP, otherCheck).isValid()).isTrue();
+ }
+
+ @Test
+ public void testVerRegex() {
+ class RegexCheck {
+ @Getter
+ @Pattern(regexp = "[a-f]*")
+ String strValue;
+ }
+
+ RegexCheck regexCheck = new RegexCheck();
+
+ // does not match
+ regexCheck.strValue = "xyz";
+ assertInvalid("testVerRegex", validator.validateTop(TOP, regexCheck), STR_FIELD,
+ "does not match regular expression [a-f]");
+
+ // matches
+ regexCheck.strValue = "abcabc";
+ assertTrue(validator.validateTop(TOP, regexCheck).isValid());
+
+ // invalid regex
+ class InvalidRegexCheck {
+ @Getter
+ @Pattern(regexp = "[a-f")
+ String strValue;
+ }
+
+ InvalidRegexCheck invalidRegexCheck = new InvalidRegexCheck();
+
+ // does not match
+ invalidRegexCheck.strValue = "abc";
+ assertInvalid("testVerRegex", validator.validateTop(TOP, invalidRegexCheck), STR_FIELD,
+ "does not match regular expression [a-f");
+
+ // matches
+ regexCheck.strValue = "abcabc";
+ assertTrue(validator.validateTop(TOP, regexCheck).isValid());
+
+ /*
+ * Class with "regex" annotation on an integer.
+ */
+ class RegexInt {
+ @Getter
+ @Pattern(regexp = "[a-f]*")
+ int intValue;
+ }
+
+ RegexInt regexInt = new RegexInt();
+ regexInt.intValue = 0;
+ assertInvalid("testVerRegex", validator.validateTop(TOP, regexInt), INT_FIELD,
+ "does not match regular expression [a-f]");
+ }
+
+ @Test
+ public void testVerMax() {
+ /*
+ * Field is not a number.
+ */
+ class NonNumeric {
+ @Getter
+ @Max(100)
+ String strValue;
+ }
+
+ NonNumeric nonNumeric = new NonNumeric();
+ nonNumeric.strValue = STRING_VALUE;
+ assertTrue(validator.validateTop(TOP, nonNumeric).isValid());
+
+ /*
+ * Integer field.
+ */
+ class IntField {
+ @Getter
+ @Max(100)
+ Integer intValue;
+ }
+
+ // ok value
+ IntField intField = new IntField();
+ assertNumeric("testVerMax-integer", intField, value -> {
+ intField.intValue = value;
+ }, INT_FIELD, "maximum", INT_VALUE, 100, 101);
+
+ /*
+ * Long field.
+ */
+ class LongField {
+ @Getter
+ @Max(100)
+ Long numValue;
+ }
+
+ // ok value
+ LongField longField = new LongField();
+ assertNumeric("testVerMax-long", longField, value -> {
+ longField.numValue = (long) value;
+ }, NUM_FIELD, "maximum", INT_VALUE, 100, 101);
+
+ /*
+ * Float field.
+ */
+ class FloatField {
+ @Getter
+ @Max(100)
+ Float numValue;
+ }
+
+ // ok value
+ FloatField floatField = new FloatField();
+ assertNumeric("testVerMax-float", floatField, value -> {
+ floatField.numValue = (float) value;
+ }, NUM_FIELD, "maximum", INT_VALUE, 100, 101);
+
+ /*
+ * Double field.
+ */
+ class DoubleField {
+ @Getter
+ @Max(100)
+ Double numValue;
+ }
+
+ // ok value
+ DoubleField doubleField = new DoubleField();
+ assertNumeric("testVerMax-double", doubleField, value -> {
+ doubleField.numValue = (double) value;
+ }, NUM_FIELD, "maximum", INT_VALUE, 100, 101);
+
+ /*
+ * Atomic Integer field (which is a subclass of Number).
+ */
+ class AtomIntValue {
+ @Getter
+ @Max(100)
+ AtomicInteger numValue;
+ }
+
+ // ok value
+ AtomIntValue atomIntField = new AtomIntValue();
+ atomIntField.numValue = new AtomicInteger(INT_VALUE);
+ assertTrue(validator.validateTop(TOP, atomIntField).isValid());
+
+ // invalid value - should be OK, because it isn't an Integer
+ atomIntField.numValue.set(101);
+ assertTrue(validator.validateTop(TOP, atomIntField).isValid());
+ }
+
+ @Test
+ public void testVerMin() {
+ /*
+ * Field is not a number.
+ */
+ class NonNumeric {
+ @Getter
+ @Min(10)
+ String strValue;
+ }
+
+ NonNumeric nonNumeric = new NonNumeric();
+ nonNumeric.strValue = STRING_VALUE;
+ assertTrue(validator.validateTop(TOP, nonNumeric).isValid());
+
+ /*
+ * Integer field.
+ */
+ class IntField {
+ @Getter
+ @Min(10)
+ Integer intValue;
+ }
+
+ // ok value
+ IntField intField = new IntField();
+ assertNumeric("testVerMin-integer", intField, value -> {
+ intField.intValue = value;
+ }, INT_FIELD, "minimum", INT_VALUE, 10, 1);
+
+ /*
+ * Long field.
+ */
+ class LongField {
+ @Getter
+ @Min(10)
+ Long numValue;
+ }
+
+ // ok value
+ LongField longField = new LongField();
+ assertNumeric("testVerMin-long", longField, value -> {
+ longField.numValue = (long) value;
+ }, NUM_FIELD, "minimum", INT_VALUE, 10, 1);
+
+ /*
+ * Float field.
+ */
+ class FloatField {
+ @Getter
+ @Min(10)
+ Float numValue;
+ }
+
+ // ok value
+ FloatField floatField = new FloatField();
+ assertNumeric("testVerMin-float", floatField, value -> {
+ floatField.numValue = (float) value;
+ }, NUM_FIELD, "minimum", INT_VALUE, 10, 1);
+
+ /*
+ * Double field.
+ */
+ class DoubleField {
+ @Getter
+ @Min(10)
+ Double numValue;
+ }
+
+ // ok value
+ DoubleField doubleField = new DoubleField();
+ assertNumeric("testVerMin-double", doubleField, value -> {
+ doubleField.numValue = (double) value;
+ }, NUM_FIELD, "minimum", INT_VALUE, 10, 1);
+
+ /*
+ * Atomic Integer field (which is a subclass of Number).
+ */
+ class AtomIntValue {
+ @Getter
+ @Min(10)
+ AtomicInteger numValue;
+ }
+
+ // ok value
+ AtomIntValue atomIntField = new AtomIntValue();
+ atomIntField.numValue = new AtomicInteger(INT_VALUE);
+ assertTrue(validator.validateTop(TOP, atomIntField).isValid());
+
+ // invalid value - should be OK, because it isn't an Integer
+ atomIntField.numValue.set(101);
+ assertTrue(validator.validateTop(TOP, atomIntField).isValid());
+ }
+
+ @Test
+ public void testVerClassName() {
+ class ClassNameCheck {
+ @Getter
+ @ClassName
+ String strValue;
+ }
+
+ ClassNameCheck classCheck = new ClassNameCheck();
+
+ // null should be OK
+ classCheck.strValue = null;
+ assertTrue(validator.validateTop(TOP, classCheck).isValid());
+
+ // valid class name
+ classCheck.strValue = getClass().getName();
+ assertTrue(validator.validateTop(TOP, classCheck).isValid());
+
+ // invalid class name
+ classCheck.strValue = "<unknown class>";
+ assertInvalid("testVerClassName", validator.validateTop(TOP, classCheck),
+ STR_FIELD, "class is not in the classpath");
+ }
+
+ @Test
+ public void testVerCascade() {
+ class Item {
+ @Getter
+ @NotNull
+ Integer intValue;
+ }
+
+ @Getter
+ class Container {
+ @Valid
+ Item checked;
+
+ Item unchecked;
+
+ @Valid
+ List<Item> items;
+
+ @Valid
+ Map<String, Item> itemMap;
+ }
+
+ Container cont = new Container();
+ cont.unchecked = new Item();
+ cont.items = List.of(new Item());
+ cont.itemMap = Map.of(STRING_VALUE, new Item());
+
+ cont.checked = null;
+ assertTrue(validator.validateTop(TOP, cont).isValid());
+
+ cont.checked = new Item();
+
+ assertInvalid("testVerCascade", validator.validateTop(TOP, cont), INT_FIELD, "null");
+
+ cont.checked.intValue = INT_VALUE;
+ assertTrue(validator.validateTop(TOP, cont).isValid());
+ }
+
+ @Test
+ public void testVerCollection() {
+ @Getter
+ class Container {
+ List<@Min(5) Integer> items;
+
+ // not a collection - should not be checked
+ @Valid
+ String strValue;
+
+ String noAnnotations;
+ }
+
+ Container cont = new Container();
+ cont.strValue = STRING_VALUE;
+ cont.noAnnotations = STRING_VALUE;
+
+ // null collection - always valid
+ assertTrue(validator.validateTop(TOP, cont).isValid());
+
+ // empty collection - always valid
+ cont.items = List.of();
+ assertTrue(validator.validateTop(TOP, cont).isValid());
+
+ cont.items = List.of(-10, -20);
+ assertThat(validator.validateTop(TOP, cont).getResult()).contains("\"0\"", "-10", "\"1\"", "-20", "minimum");
+
+ cont.items = List.of(10, -30);
+ assertThat(validator.validateTop(TOP, cont).getResult()).contains("\"1\"", "-30", "minimum")
+ .doesNotContain("\"0\"");
+
+ cont.items = List.of(10, 20);
+ assertTrue(validator.validateTop(TOP, cont).isValid());
+ }
+
+ @Test
+ public void testVerMap() {
+ @Getter
+ class Container {
+ Map<String, @Min(5) Integer> items;
+
+ // not a map
+ @NotBlank
+ String strValue;
+
+ String noAnnotations;
+ }
+
+ Container cont = new Container();
+ cont.strValue = STRING_VALUE;
+ cont.noAnnotations = STRING_VALUE;
+
+ // null map - always valid
+ assertTrue(validator.validateTop(TOP, cont).isValid());
+
+ // empty map - always valid
+ cont.items = Map.of();
+ assertTrue(validator.validateTop(TOP, cont).isValid());
+
+ cont.items = Map.of("abc", -10, "def", -20);
+ assertThat(validator.validateTop(TOP, cont).getResult()).contains("abc", "-10", "def", "-20", "minimum");
+
+ cont.items = Map.of("abc", 10, "def", -30);
+ assertThat(validator.validateTop(TOP, cont).getResult()).contains("def", "-30", "minimum")
+ .doesNotContain("abc");
+
+ cont.items = Map.of("abc", 10, "def", 20);
+ assertTrue(validator.validateTop(TOP, cont).isValid());
+ }
+
+ @Test
+ public void testGetEntryName() {
+ assertThat(validator.getEntryName(makeEntry(null, 0))).isEmpty();
+ assertThat(validator.getEntryName(makeEntry("", 0))).isEmpty();
+ assertThat(validator.getEntryName(makeEntry(STRING_VALUE, 0))).isEqualTo(STRING_VALUE);
+ }
+
+ /**
+ * Makes a Map entry with the given key and value.
+ *
+ * @param key desired key
+ * @param value desired value
+ * @return a new Map entry
+ */
+ private Map.Entry<String, Integer> makeEntry(String key, int value) {
+ HashMap<String, Integer> map = new HashMap<>();
+ map.put(key, value);
+ return map.entrySet().iterator().next();
+ }
+
+ private <T> void assertNumeric(String testName, T object, Consumer<Integer> setter, String fieldName,
+ String expectedText, int inside, int edge, int outside) {
+ setter.accept(inside);
+ assertTrue(validator.validateTop(TOP, object).isValid());
+
+ // on the edge
+ setter.accept(edge);
+ assertTrue(validator.validateTop(TOP, object).isValid());
+
+ // invalid
+ setter.accept(outside);
+ assertInvalid("testVerNotNull", validator.validateTop(TOP, object), fieldName, expectedText);
+ }
+
+
+ private void assertInvalid(String testName, BeanValidationResult result, String... text) {
+ assertThat(result.getResult()).describedAs(testName).contains(text);
+ }
+}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java
new file mode 100644
index 00000000..81a7b8ff
--- /dev/null
+++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java
@@ -0,0 +1,379 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * 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.parameters;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.google.gson.annotations.SerializedName;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.util.List;
+import java.util.Map;
+import lombok.Getter;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.parameters.annotations.Min;
+import org.onap.policy.common.parameters.annotations.NotBlank;
+import org.onap.policy.common.parameters.annotations.NotNull;
+
+public class TestFieldValidator extends ValidatorUtil {
+ private static final String INT_LIST_FIELD = "intList";
+ private static final String INT_MAP_FIELD = "intMap";
+ private static final String UNANNOTATED_FIELD = "unannotated";
+ private static final String INT_FIELD = "intValue";
+ private static final int VALID_INT = 10;
+ private static final int INVALID_INT = -10;
+
+ @Getter
+ private int unannotated;
+
+ @Min(0)
+ @Getter
+ private int intValue;
+
+ @Getter
+ private List<@Min(1) Integer> intList;
+
+ @Getter
+ private Map<@NotBlank String, @Min(1) Integer> intMap;
+
+ @SerializedName("annotated_key_map")
+ @Getter
+ private Map<@NotBlank String, Integer> annotatedKeyMap;
+
+ @Getter
+ private Map<String, @Min(1) Integer> annotatedValueMap;
+
+ @Getter
+ private List<Integer> unannotatedList;
+
+ @Getter
+ private Map<String, Integer> unannotatedMap;
+
+ @NotNull
+ @Getter
+ private boolean boolValue;
+
+ @NotNull
+ @Getter
+ private String notNullValue;
+
+ @Min(0)
+ @Getter
+ private static int staticField;
+
+ /**
+ * Has no accessor.
+ */
+ @Min(0)
+ private int noMethod;
+
+ /**
+ * Accessor is {@link #getStaticMethod()}, which is static.
+ */
+ @Min(0)
+ private int staticMethod;
+
+ /**
+ * Accessor is {@link #getVoidMethod()}, which returns a void.
+ */
+ @Min(0)
+ private int voidMethod;
+
+ /**
+ * Accessor is {@link #getParameterizedMethod()}, which requires a parameter.
+ */
+ @Min(0)
+ private int parameterizedMethod;
+
+ /**
+ * Accessor is {@link #getExMethod()}, which throws an exception.
+ */
+ @Min(0)
+ private int exMethod;
+
+
+ @Before
+ public void setUp() {
+ bean = new BeanValidator();
+ }
+
+ @Test
+ public void testGetAnnotation() {
+ // field-level annotation
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse();
+
+ // class-level annotation
+ assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "text")).isEmpty()).isFalse();
+ }
+
+ @Test
+ public void testFieldValidator() throws NoSuchFieldException, SecurityException {
+ /*
+ * Note: nested classes contain fields like "$this", thus the check for "$" in the
+ * variable name is already covered by the other tests.
+ */
+
+ /*
+ * Class with no annotations.
+ */
+ @NotNull
+ class NoAnnotations {
+ @SuppressWarnings("unused")
+ String strValue;
+ }
+
+ Field field = NoAnnotations.class.getDeclaredField("this$0");
+
+ assertThat(new FieldValidator(bean, NoAnnotations.class, field).isEmpty()).isTrue();
+
+ // unannotated
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotated")).isEmpty()).isTrue();
+
+ // these are invalid for various reasons
+
+ Field staticField2 = getField("staticField");
+ assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticField2))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ Field noMethodField = getField("noMethod");
+ assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, noMethodField))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ // annotated
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse();
+ }
+
+ @Test
+ public void testFieldValidator_SetNullAllowed() {
+ // default - null is allowed
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isNullAllowed()).isTrue();
+
+ // field-level NotNull
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("notNullValue")).isNullAllowed())
+ .isFalse();
+
+ // class-level NotNull
+ assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "noMethod")).isNullAllowed())
+ .isFalse();
+ }
+
+ @Test
+ public void testAddListValidator() {
+
+ // unannotated
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotatedList")).isEmpty()).isTrue();
+
+ // annotated
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_LIST_FIELD)).isEmpty()).isFalse();
+ }
+
+ @Test
+ public void testAddMapValidator() {
+
+ // unannotated
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotatedMap")).isEmpty()).isTrue();
+
+ // annotated
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_MAP_FIELD)).isEmpty()).isFalse();
+
+ // only the key is annotated
+ FieldValidator validator = new FieldValidator(bean, TestFieldValidator.class, getField("annotatedKeyMap"));
+ assertThat(validator.isEmpty()).isFalse();
+
+ BeanValidationResult result = new BeanValidationResult(MY_NAME, this);
+ annotatedKeyMap = Map.of("abc", -10);
+ validator.validateField(result, this);
+ assertThat(result.getResult()).isNull();
+
+ annotatedKeyMap = Map.of(" ", -10);
+ validator.validateField(result, this);
+ assertThat(result.getResult()).contains("annotated_key_map", "blank").doesNotContain("-10");
+
+ // only the value is annotated
+ validator = new FieldValidator(bean, TestFieldValidator.class, getField("annotatedValueMap"));
+ assertThat(validator.isEmpty()).isFalse();
+
+ result = new BeanValidationResult(MY_NAME, this);
+ annotatedValueMap = Map.of(" ", 10);
+ validator.validateField(result, this);
+ assertThat(result.getResult()).isNull();
+
+ annotatedValueMap = Map.of(" ", -10);
+ validator.validateField(result, this);
+ assertThat(result.getResult()).doesNotContain("blank").contains("annotatedValueMap", "\" \"", "-10");
+ }
+
+ @SuppressWarnings("deprecation")
+ @Test
+ public void testValidateField_testGetValue() {
+ // unannotated
+ BeanValidationResult result = new BeanValidationResult(MY_NAME, this);
+ new FieldValidator(bean, getClass(), getField(UNANNOTATED_FIELD)).validateField(result, this);
+ assertThat(result.getResult()).isNull();
+
+ // valid
+ intValue = VALID_INT;
+ result = new BeanValidationResult(MY_NAME, this);
+ new FieldValidator(bean, getClass(), getField(INT_FIELD)).validateField(result, this);
+ assertThat(result.getResult()).isNull();
+
+ // invalid
+ intValue = INVALID_INT;
+ result = new BeanValidationResult(MY_NAME, this);
+ new FieldValidator(bean, getClass(), getField(INT_FIELD)).validateField(result, this);
+ assertThat(result.getResult()).contains(INT_FIELD);
+
+ // throws an exception
+ FieldValidator validator = new FieldValidator(bean, TestFieldValidator.class, getField("exMethod"));
+ BeanValidationResult result2 = new BeanValidationResult(MY_NAME, this);
+ assertThatThrownBy(() -> validator.validateField(result2, this)).isInstanceOf(IllegalArgumentException.class)
+ .getCause().isInstanceOf(InvocationTargetException.class).getCause()
+ .hasMessage("expected exception");
+ }
+
+ @Test
+ public void testValidateField_testGetValue_ListField() {
+ // valid
+ BeanValidationResult result = new BeanValidationResult(MY_NAME, this);
+ intList = List.of(10, 20, 30, 40);
+ new FieldValidator(bean, getClass(), getField(INT_LIST_FIELD)).validateField(result, this);
+ assertThat(result.getResult()).isNull();
+
+ // invalid
+ result = new BeanValidationResult(MY_NAME, this);
+ intList = List.of(9, -8, 7, -6);
+ new FieldValidator(bean, getClass(), getField(INT_LIST_FIELD)).validateField(result, this);
+ assertThat(result.getResult()).doesNotContain("0", "9").contains("1", "-8").doesNotContain("2", "7")
+ .contains("3", "-6");
+ }
+
+ @Test
+ public void testValidateField_testGetValue_MapField() {
+ // valid
+ BeanValidationResult result = new BeanValidationResult(MY_NAME, this);
+ intMap = Map.of("ten", 10, "twenty", 20, "thirty", 30, "forty", 40);
+ new FieldValidator(bean, getClass(), getField(INT_MAP_FIELD)).validateField(result, this);
+ assertThat(result.getResult()).isNull();
+
+ // invalid
+ result = new BeanValidationResult(MY_NAME, this);
+ intMap = Map.of("ten", 9, "twenty", -8, "thirty", 7, "forty", -6);
+ new FieldValidator(bean, getClass(), getField(INT_MAP_FIELD)).validateField(result, this);
+ assertThat(result.getResult()).doesNotContain("ten", "9").contains("twenty", "-8").doesNotContain("thirty", "7")
+ .contains("forty", "-6");
+ }
+
+ @Test
+ public void testClassOnly() {
+ // class-level annotation has no bearing on a static field
+ assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "staticValue")).isEmpty())
+ .isTrue();
+
+ // field-level annotation on a static field
+ Field staticField2 = getField("staticField");
+ assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticField2))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testGetAccessor() {
+ // uses "getXxx"
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse();
+
+ // uses "isXxx"
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("boolValue")).isEmpty()).isFalse();
+ }
+
+ @Test
+ public void testGetMethod() {
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse();
+
+ // these are invalid for various reasons
+
+ Field noMethodField = getField("noMethod");
+ assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, noMethodField))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ Field staticMethodField = getField("staticMethod");
+ assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticMethodField))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testValidMethod() {
+ assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse();
+
+ // these are invalid for various reasons
+
+ Field staticMethodField = getField("staticMethod");
+ assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticMethodField))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ Field voidMethodField = getField("voidMethod");
+ assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, voidMethodField))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ Field paramMethodField = getField("parameterizedMethod");
+ assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, paramMethodField))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testIsFieldAnnotated_testSetFieldAnnotated() {
+ // annotated at the field level
+ assertThat(new FieldValidator(bean, getClass(), getField(INT_FIELD)).isFieldAnnotated()).isTrue();
+
+ // unannotated
+ assertThat(new FieldValidator(bean, getClass(), getField(UNANNOTATED_FIELD)).isFieldAnnotated()).isFalse();
+ }
+
+ public static int getStaticMethod() {
+ return -1000;
+ }
+
+ public void getVoidMethod() {
+ // do nothing
+ }
+
+ public int getParameterizedMethod(boolean flag) {
+ return 0;
+ }
+
+ public int getExMethod() {
+ throw new RuntimeException("expected exception");
+ }
+
+ @NotNull
+ public static class ClassAnnot {
+ @Getter
+ private String text;
+
+ // no "get" method
+ @SuppressWarnings("unused")
+ private String noMethod;
+
+ @Getter
+ private static int staticValue;
+ }
+}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java
new file mode 100644
index 00000000..cadcfdee
--- /dev/null
+++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java
@@ -0,0 +1,121 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.parameters.annotations.Min;
+import org.onap.policy.common.parameters.annotations.NotBlank;
+import org.onap.policy.common.parameters.annotations.NotNull;
+
+public class TestItemValidator extends ValidatorUtil {
+
+ // annotated fields - each field must have exactly one annotation
+
+ /**
+ * This annotation does not contain a method returning an array.
+ */
+ @Min(value = 0)
+ private int notArray;
+
+ /**
+ * This annotation doesn't contain any annotations that the {@link BeanValidator}
+ * recognizes.
+ */
+ @Simple
+ private int mismatch;
+
+ /**
+ * No annotations.
+ */
+ @SuppressWarnings("unused")
+ private int noAnnotations;
+
+ /**
+ * One matching annotation.
+ */
+ @NotNull
+ private int match;
+
+ /**
+ * Multiple matching annotations.
+ */
+ @NotNull
+ @NotBlank
+ private String multiMatch;
+
+
+ @Before
+ public void setUp() {
+ bean = new BeanValidator();
+ }
+
+ @Test
+ public void testGetAnnotation() {
+ // no matches
+ assertThat(new ItemValidator(bean, getAnnotType("noAnnotations"), true).isEmpty()).isTrue();
+
+ // had a match
+ assertThat(new ItemValidator(bean, getAnnotType("match"), true).checkers).hasSize(1);
+
+ // multiple matches
+ ItemValidator validator = new ItemValidator(bean, getAnnotType("multiMatch"), true);
+ assertThat(validator.checkers).hasSize(2);
+
+ BeanValidationResult result = new BeanValidationResult(MY_NAME, this);
+ validator.validateValue(result, MY_FIELD, HELLO);
+ assertThat(result.getResult()).isNull();
+
+ result = new BeanValidationResult(MY_NAME, this);
+ validator.validateValue(result, MY_FIELD, null);
+ assertThat(result.getResult()).isNotNull();
+
+ result = new BeanValidationResult(MY_NAME, this);
+ validator.validateValue(result, MY_FIELD, "");
+ assertThat(result.getResult()).isNotNull();
+ }
+
+ @Test
+ public void testItemValidatorBeanValidatorAnnotation() {
+ assertThat(new ItemValidator(bean, getAnnotType("match")).isEmpty()).isFalse();
+ }
+
+ @Test
+ public void testItemValidatorBeanValidatorAnnotationBoolean() {
+ assertThat(new ItemValidator(bean, getAnnotType("match"), true).isEmpty()).isFalse();
+
+ assertThat(new ItemValidator(bean, getAnnotType("match"), false).isEmpty()).isTrue();
+ }
+
+ // these annotations are not recognized by the BeanValidator
+
+ @Retention(RUNTIME)
+ @Target(FIELD)
+ public @interface Simple {
+
+ }
+}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java
deleted file mode 100644
index abef5528..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import java.io.FileReader;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import org.junit.Test;
-import org.onap.policy.common.parameters.testclasses.TestParametersL00;
-
-
-public class TestJsonInput {
-
- @Test
- public void testJsonInput() throws IOException {
- TestParametersL00 testParameterGroup = null;
-
- // Read the parameters from JSON using Gson
- final Gson gson = new GsonBuilder().create();
- testParameterGroup = gson.fromJson(new FileReader("src/test/resources/parameters/TestParameters.json"),
- TestParametersL00.class);
-
- GroupValidationResult validationResult = testParameterGroup.validate();
- assertTrue(validationResult.isValid());
- assertEquals("l00NameFromFile", testParameterGroup.getName());
-
- String expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt")))
- .replaceAll("\\s+", "");
- assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", ""));
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java
deleted file mode 100644
index fda37816..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-import org.onap.policy.common.parameters.testclasses.EmptyParameterGroup;
-
-public class TestParameterService {
- private static final String EMPTY_GROUP = "Empty Group";
-
- @Test
- public void testParameterService() {
- ParameterService.clear();
-
- assertFalse(ParameterService.contains("EmptyGroup"));
-
- assertThatThrownBy(() -> ParameterService.get("EmptyGroup"))
- .hasMessage("\"EmptyGroup\" not found in parameter service");
-
- ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP));
- assertTrue(ParameterService.contains(EMPTY_GROUP));
- assertNotNull(ParameterService.get(EMPTY_GROUP));
-
- assertThatThrownBy(() -> ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP)))
- .hasMessage("\"Empty Group\" already registered in parameter service");
-
- assertThatThrownBy(() -> ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), false))
- .hasMessage("\"Empty Group\" already registered in parameter service");
-
- ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), true);
- assertTrue(ParameterService.contains(EMPTY_GROUP));
-
- ParameterService.deregister(EMPTY_GROUP);
- assertFalse(ParameterService.contains(EMPTY_GROUP));
-
- ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), true);
- assertTrue(ParameterService.contains(EMPTY_GROUP));
-
- ParameterService.deregister(EMPTY_GROUP);
- assertFalse(ParameterService.contains(EMPTY_GROUP));
-
- EmptyParameterGroup epg = new EmptyParameterGroup(EMPTY_GROUP);
- ParameterService.register(epg);
- assertTrue(ParameterService.contains(EMPTY_GROUP));
- assertNotNull(ParameterService.get(EMPTY_GROUP));
-
- ParameterService.deregister(epg);
- assertFalse(ParameterService.contains(EMPTY_GROUP));
-
- assertThatThrownBy(() -> ParameterService.deregister(EMPTY_GROUP))
- .hasMessage("\"Empty Group\" not registered in parameter service");
-
- assertThatThrownBy(() -> ParameterService.get(EMPTY_GROUP))
- .hasMessage("\"Empty Group\" not found in parameter service");
-
- ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP));
- assertTrue(ParameterService.contains(EMPTY_GROUP));
- assertNotNull(ParameterService.get(EMPTY_GROUP));
-
- assertEquals(1, ParameterService.getAll().size());
- ParameterService.clear();
- assertEquals(0, ParameterService.getAll().size());
- assertFalse(ParameterService.contains(EMPTY_GROUP));
-
- assertThatThrownBy(() -> ParameterService.get(EMPTY_GROUP))
- .hasMessage("\"Empty Group\" not found in parameter service");
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java
index 9e7121cd..b19b92da 100644
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java
+++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java
@@ -1,7 +1,7 @@
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications 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.
@@ -21,25 +21,17 @@
package org.onap.policy.common.parameters;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import org.junit.Test;
import org.onap.policy.common.parameters.annotations.Max;
import org.onap.policy.common.parameters.annotations.Min;
import org.onap.policy.common.parameters.annotations.NotBlank;
import org.onap.policy.common.parameters.annotations.NotNull;
-import org.onap.policy.common.parameters.testclasses.TestParametersL00;
-import org.onap.policy.common.parameters.testclasses.TestParametersL10;
+import org.onap.policy.common.parameters.annotations.Valid;
public class TestValidation {
- private static final String L0_PARAMETERS = "l0Parameters";
-
private static final String NOT_BLANK_STRING_MESSAGE =
"field 'notBlankString' type 'java.lang.String' value '' INVALID, must be a non-blank string\n"
.replace('\'', '"');
@@ -74,177 +66,15 @@ public class TestValidation {
private long maxLong;
@Test
- public void testValidationOk() throws IOException {
- TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS);
-
- GroupValidationResult validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertTrue(validationResult.isClean());
- assertNull(validationResult.getResult());
- assertEquals(l0Parameters, validationResult.getParameterGroup());
- assertEquals(l0Parameters.getName(), validationResult.getName());
-
- String expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt")))
- .replaceAll("\\s+", "");
- assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", ""));
- }
-
- @Test
- public void testValidationObservation() throws IOException {
- TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS);
-
- l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 3);
-
- String expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt")))
- .replaceAll("\\s+", "");
-
- GroupValidationResult validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertFalse(validationResult.isClean());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 2);
-
- expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt")))
- .replaceAll("\\s+", "");
-
- validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 1);
-
- expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt")))
- .replaceAll("\\s+", "");
-
- validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 0);
-
- validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertEquals(null, validationResult.getResult());
- }
-
- @Test
- public void testValidationWarning() throws IOException {
- TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS);
-
- l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 3);
-
- String expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt")))
- .replaceAll("\\s+", "");
-
- GroupValidationResult validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 2);
-
- expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt")))
- .replaceAll("\\s+", "");
-
- validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 1);
-
- expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt")))
- .replaceAll("\\s+", "");
-
- validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 0);
-
- validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertEquals(null, validationResult.getResult());
- }
-
- @Test
- public void testValidationInvalid() throws IOException {
- TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS);
-
- l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 3);
-
- String expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt")))
- .replaceAll("\\s+", "");
-
- GroupValidationResult validationResult = l0Parameters.validate();
- assertFalse(validationResult.isValid());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 2);
-
- expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt")))
- .replaceAll("\\s+", "");
-
- validationResult = l0Parameters.validate();
- assertFalse(validationResult.isValid());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 1);
-
- expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt")))
- .replaceAll("\\s+", "");
-
- validationResult = l0Parameters.validate();
- assertFalse(validationResult.isValid());
- assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", ""));
-
- l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3);
- l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 0);
-
- validationResult = l0Parameters.validate();
- assertTrue(validationResult.isValid());
- assertEquals(null, validationResult.getResult());
- }
-
- @Test
- public void testValidationEmptySubGroup() {
- TestParametersL10 l10Parameters = new TestParametersL10("l10Parameters");
-
- l10Parameters.setL10LGenericNested0(null);
-
- GroupValidationResult validationResult = l10Parameters.validate();
- assertTrue(validationResult.isValid());
-
- assertTrue(validationResult.getResult("", "", true).contains("UNDEFINED"));
- }
-
- @Test
public void testGetValidationResult() {
Contained item = new Contained();
item.setName("item");
Container cont = new Container();
cont.item = item;
- GroupValidationResult result = cont.validate();
+ BeanValidationResult result = cont.validate();
assertEquals(ValidationStatus.INVALID, result.getStatus());
- assertTrue(result.getResult().contains(">= 1"));
+ assertThat(result.getResult()).contains("minimum");
item.minInt = 1000;
result = cont.validate();
@@ -253,7 +83,7 @@ public class TestValidation {
cont.item = null;
result = cont.validate();
assertEquals(ValidationStatus.INVALID, result.getStatus());
- assertTrue(result.getResult().contains("is null"));
+ assertThat(result.getResult()).contains("is null");
}
@Test
@@ -429,6 +259,7 @@ public class TestValidation {
private static class Container extends ParameterGroupImpl {
@NotNull
+ @Valid
private Contained item;
public Container() {
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java
deleted file mode 100644
index b02022d7..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupMissingGetter;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupPrivateGetter;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupWithArray;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupWithCollection;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupWithIllegalMapKey;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupWithIllegalMapValue;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullCollection;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullMapValue;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullSubGroup;
-import org.onap.policy.common.parameters.testclasses.ParameterGroupWithParameterGroupCollection;
-
-public class TestValidationErrors {
- @Test
- public void testBadArrayValidation() {
- ParameterGroupWithArray groupWithArray = new ParameterGroupWithArray("Illegal Array Group");
- assertTrue(groupWithArray.isValid());
- }
-
- @Test
- public void testCollectionValidation() {
- ParameterGroupWithCollection legalCollection = new ParameterGroupWithCollection("Legal Collection");
- assertTrue(legalCollection.isValid());
-
- ParameterGroupWithParameterGroupCollection illegalCollection = new ParameterGroupWithParameterGroupCollection(
- "Illegal Collection");
-
- assertThatThrownBy(illegalCollection::isValid).isInstanceOf(ParameterRuntimeException.class)
- .hasMessage("collection parameter \"parameterGroupArrayList\" is illegal,"
- + " parameter groups are not allowed as collection members");
- }
-
- @Test
- public void testNullCollection() {
- ParameterGroupWithNullCollection nullCollection = new ParameterGroupWithNullCollection("Null Collection");
-
- assertThatThrownBy(nullCollection::isValid).isInstanceOf(ParameterRuntimeException.class)
- .hasMessage("collection parameter \"nullList\" is null");
- }
-
- @Test
- public void testMapNullSubGroupValidation() {
- ParameterGroupWithNullSubGroup nullSub = new ParameterGroupWithNullSubGroup("Null sub group value");
-
- nullSub.isValid();
- assertNull(nullSub.getSubGroup());
- }
-
- @Test
- public void testMapNullValueValidation() {
- ParameterGroupWithNullMapValue nullMap = new ParameterGroupWithNullMapValue("Null Map value");
-
- assertThatThrownBy(nullMap::isValid).isInstanceOf(ParameterRuntimeException.class)
- .hasMessage("map parameter \"nullMap\" is null");
- }
-
- @Test
- public void testBadMapKeyValidation() {
- ParameterGroupWithIllegalMapKey illegalMap = new ParameterGroupWithIllegalMapKey("Illegal Map");
-
- assertThatThrownBy(illegalMap::isValid).isInstanceOf(ParameterRuntimeException.class)
- .hasMessage("map entry is not a parameter group keyed by a string, key \"1\" "
- + "in map \"badMap\" is not a string");
- }
-
- @Test
- public void testBadMapValueValidation() {
- ParameterGroupWithIllegalMapValue illegalMap = new ParameterGroupWithIllegalMapValue("Illegal Map");
-
- assertThatThrownBy(illegalMap::isValid).isInstanceOf(ParameterRuntimeException.class)
- .hasMessage("map entry is not a parameter group keyed by a string, value \"1\" in "
- + "map \"intMap\" is not a parameter group");
- }
-
- @Test
- public void testMissingGetter() {
- ParameterGroupMissingGetter badGetterName = new ParameterGroupMissingGetter("BGN");
-
- assertThatThrownBy(badGetterName::isValid).isInstanceOf(ParameterRuntimeException.class)
- .hasMessage("could not get getter method for parameter \"value\"");
- }
-
- @Test
- public void testPrivateGetter() {
- ParameterGroupPrivateGetter privateGetter = new ParameterGroupPrivateGetter("privateGetter");
-
- assertThatThrownBy(privateGetter::isValid).isInstanceOf(ParameterRuntimeException.class)
- .hasMessage("could not get getter method for parameter \"value\"");
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java
deleted file mode 100644
index 46360ef9..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.policy.common.parameters.testclasses.TestParametersL10;
-import org.onap.policy.common.parameters.testclasses.TestParametersLGeneric;
-
-public class TestValidationResults {
- private static final String NON_EXISTANT_PARAMETER = "nonExistantParameter";
- private static final String L10L_GENERIC_NESTED_MAP_VAL0 = "l10LGenericNestedMapVal0";
- private static final String L10_INT_FIELD = "l10IntField";
- private static final String ENTRY0 = "entry0";
- private static final String THIS_VALUE_IS_INVALID = "This value is invalid";
- private static final String SOMETHING_WAS_OBSERVED = "Something was observed";
- private static final String PG_MAP = "pgMap";
-
- private Map<String, ParameterGroup> pgMap = new LinkedHashMap<>();
- private ParameterGroup pg = new TestParametersL10("pg");
-
- @Before
- public void initMap() {
- pgMap.put(ENTRY0, new TestParametersLGeneric(ENTRY0));
- }
-
- @Test
- public void testGroupMapValidationResult() throws NoSuchFieldException {
- GroupMapValidationResult result = new GroupMapValidationResult(this.getClass().getDeclaredField(PG_MAP),
- pgMap);
-
- assertTrue(result.isValid());
- assertEquals(PG_MAP, result.getName());
-
- result.setResult(ValidationStatus.OBSERVATION);
- assertTrue(result.isValid());
- assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
-
- // Once the status is stepped, it can't be reset back because it is the status of map members
- result.setResult(ValidationStatus.CLEAN);
- assertTrue(result.isValid());
- assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
-
- result.setResult(ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED);
- assertTrue(result.isValid());
- assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
- assertEquals("parameter group map \"pgMap\" OBSERVATION, Something was observed", result.getResult().trim());
-
- result.setResult(ENTRY0, new GroupValidationResult(pgMap.get(ENTRY0)));
- assertTrue(result.isValid());
- assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
- assertEquals("parameter group map \"pgMap\" OBSERVATION, Something was observed", result.getResult().trim());
-
- assertThatThrownBy(() -> result.setResult("nonExistantEntry", new GroupValidationResult(pgMap.get(ENTRY0))))
- .hasMessage("no entry with name \"nonExistantEntry\" exists");
- }
-
- @Test
- public void testGroupValidationResult() throws NoSuchFieldException {
- GroupValidationResult result = new GroupValidationResult(pg);
-
- assertTrue(result.isValid());
- assertEquals(pg, result.getParameterGroup());
- assertEquals("pg", result.getName());
-
- result.setResult(ValidationStatus.OBSERVATION);
- assertTrue(result.isValid());
- assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
-
- // Once the status is stepped, it can't be reset back because it is the status of map members
- result.setResult(ValidationStatus.CLEAN);
- assertTrue(result.isValid());
- assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
-
- result.setResult(ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED);
- assertTrue(result.isValid());
- assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
- assertEquals("parameter group \"pg\" type \"org.onap.policy.common.parameters.testclasses.TestParametersL10\""
- + " OBSERVATION, Something was observed", result.getResult().trim());
-
- assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, ValidationStatus.OBSERVATION,
- SOMETHING_WAS_OBSERVED))
- .hasMessage("no parameter field exists for parameter: nonExistantParameter");
-
- result.setResult(L10_INT_FIELD, ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED);
- assertTrue(result.isValid());
-
- assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, new GroupValidationResult(pg)))
- .hasMessage("no nested parameter field exists for parameter: nonExistantParameter");
-
- assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, new GroupValidationResult(pg)))
- .hasMessage("parameter is not a nested group parameter: l10IntField");
-
- GroupMapValidationResult groupMapResult = new GroupMapValidationResult(
- this.getClass().getDeclaredField(PG_MAP), pgMap);
-
- assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, ENTRY0, groupMapResult))
- .hasMessage("no group map parameter field exists for parameter: nonExistantParameter");
-
- assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, ENTRY0, groupMapResult))
- .hasMessage("parameter is not a nested group map parameter: l10IntField");
-
- result.setResult("l10LGenericNestedMap", L10L_GENERIC_NESTED_MAP_VAL0, ValidationStatus.INVALID,
- THIS_VALUE_IS_INVALID);
- assertEquals(ValidationStatus.INVALID, result.getStatus());
-
- assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, L10L_GENERIC_NESTED_MAP_VAL0, ValidationStatus.INVALID,
- THIS_VALUE_IS_INVALID))
- .hasMessage("parameter is not a nested group map parameter: l10IntField");
-
- assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, L10L_GENERIC_NESTED_MAP_VAL0,
- ValidationStatus.INVALID, THIS_VALUE_IS_INVALID)).hasMessage(
- "no group map parameter field exists for parameter: nonExistantParameter");
-
- assertThatThrownBy(() -> result.setResult("l10LGenericNestedMap", "NonExistantKey", ValidationStatus.INVALID,
- THIS_VALUE_IS_INVALID)).hasMessage("no entry with name \"NonExistantKey\" exists");
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java
new file mode 100644
index 00000000..dcf08695
--- /dev/null
+++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java
@@ -0,0 +1,142 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.lang.annotation.Annotation;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.parameters.annotations.Min;
+import org.onap.policy.common.parameters.annotations.NotBlank;
+import org.onap.policy.common.parameters.annotations.NotNull;
+
+public class TestValueValidator extends ValidatorUtil {
+
+ private ValueValidator validator;
+
+ // these fields just provide place-holders for annotations
+
+ @NotNull
+ @NotBlank
+ private final int annotField = 1;
+
+
+ @Before
+ public void setUp() {
+ validator = new MyValueValidator();
+ }
+
+ @Test
+ public void testIsEmpty() {
+ assertThat(validator.isEmpty()).isTrue();
+
+ validator.addAnnotation(NotNull.class, (result2, fieldName, value) -> true);
+ assertThat(validator.isEmpty()).isFalse();
+ }
+
+ @Test
+ public void testValidateValue_NullValue() {
+ BeanValidationResult result = new BeanValidationResult(MY_NAME, this);
+
+ validator.validateValue(result, MY_FIELD, null);
+ assertThat(result.getResult()).isNull();
+
+ validator.addAnnotation(NotNull.class,
+ (result2, fieldName, value) -> result2.validateNotNull(fieldName, value));
+ validator.validateValue(result, MY_FIELD, null);
+ assertThat(result.getResult()).contains(MY_FIELD, "null");
+ }
+
+ @Test
+ public void testValidateValue_NotNullValue() {
+ BeanValidationResult result = new BeanValidationResult(MY_NAME, this);
+
+ validator.validateValue(result, MY_FIELD, HELLO);
+ assertThat(result.getResult()).isNull();
+
+ validator.addAnnotation(NotNull.class,
+ (result2, fieldName, value) -> result2.validateNotNull(fieldName, value));
+ validator.validateValue(result, MY_FIELD, HELLO);
+ assertThat(result.getResult()).isNull();
+ }
+
+ @Test
+ public void testAddAnnotationClassOfTChecker() {
+ // the field does not have this annotation
+ validator.addAnnotation(Min.class, (result2, fieldName, value) -> true);
+ assertThat(validator.isEmpty()).isTrue();
+
+ // "null" flag should stay true with this annotation
+ assertThat(validator.isNullAllowed()).isTrue();
+ validator.addAnnotation(NotBlank.class, (result2, fieldName, value) -> true);
+ assertThat(validator.isNullAllowed()).isTrue();
+
+ // "null" flag should become false with this annotation
+ assertThat(validator.isNullAllowed()).isTrue();
+ validator.addAnnotation(NotNull.class, (result2, fieldName, value) -> true);
+ assertThat(validator.isNullAllowed()).isFalse();
+ }
+
+ @Test
+ public void testAddAnnotationClassOfTCheckerWithAnnotOfT() {
+ // the field does not have this annotation
+ validator.addAnnotation(Min.class, (result2, fieldName, annot, value) -> true);
+ assertThat(validator.isEmpty()).isTrue();
+
+ // indicates the annotation value
+ AtomicBoolean wasNull = new AtomicBoolean(false);
+
+ // the field DOES have this annotation
+ validator.addAnnotation(NotNull.class, (result2, fieldName, annot, value) -> {
+ wasNull.set(annot instanceof NotNull);
+ return result2.validateNotNull(fieldName, value);
+ });
+ assertThat(validator.isEmpty()).isFalse();
+
+ // ensure that the checker is invoked
+ BeanValidationResult result = new BeanValidationResult(MY_NAME, this);
+ validator.validateValue(result, MY_FIELD, HELLO);
+ assertThat(result.getResult()).isNull();
+
+ assertThat(wasNull.get()).isTrue();
+ }
+
+ @Test
+ public void testGetAnnotation() {
+ assertThat(new ValueValidator().getAnnotation(NotNull.class)).isNull();
+ }
+
+ /**
+ * Checks for annotations on the "annotField" field.
+ */
+ private static class MyValueValidator extends ValueValidator {
+ @Override
+ public <T extends Annotation> T getAnnotation(Class<T> annotClass) {
+ try {
+ return TestValueValidator.class.getDeclaredField("annotField").getAnnotation(annotClass);
+ } catch (NoSuchFieldException | SecurityException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java
deleted file mode 100644
index 66656844..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.FileReader;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import org.junit.Test;
-import org.onap.policy.common.parameters.testclasses.TestParametersL00;
-import org.yaml.snakeyaml.Yaml;
-
-public class TestYamlInput {
- @Test
- public void testYamlInput() throws IOException {
- TestParametersL00 testParameterGroup = null;
-
- // Read the parameters from JSON using Gson
- final Yaml yaml = new Yaml();
- testParameterGroup = yaml.loadAs(new FileReader("src/test/resources/parameters/TestParameters.yaml"),
- TestParametersL00.class);
-
- GroupValidationResult validationResult = testParameterGroup.validate();
- assertTrue(validationResult.isValid());
- assertEquals("l00NameFromFile", testParameterGroup.getName());
-
- String expectedResult = new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt")))
- .replaceAll("\\s+", "");
- assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", ""));
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java
new file mode 100644
index 00000000..e39b5b86
--- /dev/null
+++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.parameters;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AnnotatedType;
+import java.lang.reflect.Field;
+
+/**
+ * Utilities for validator tests.
+ */
+public class ValidatorUtil {
+ protected static final String MY_NAME = "My-Name";
+ protected static final String MY_FIELD = "My-Field";
+ protected static final String HELLO = "hello";
+
+ protected BeanValidator bean;
+
+ /**
+ * Gets the single annotation for a given field.
+ *
+ * @param fieldName name of the field having the desired annotation
+ * @return the given field's annotation
+ */
+ protected Annotation getAnnot(String fieldName) {
+ return getField(fieldName).getAnnotations()[0];
+ }
+
+ /**
+ * Gets the annotated type for a given field.
+ *
+ * @param fieldName name of the field of interest
+ * @return the given field's annotated type
+ */
+ protected AnnotatedType getAnnotType(String fieldName) {
+ return getField(fieldName).getAnnotatedType();
+ }
+
+ /**
+ * Gets a field from this object.
+ *
+ * @param fieldName name of the field of interest
+ * @return the given field
+ */
+ protected Field getField(String fieldName) {
+ return getField(getClass(), fieldName);
+ }
+
+ /**
+ * Gets a field from a given class.
+ *
+ * @param clazz class containing the field
+ * @param fieldName name of the field of interest
+ * @return the given field
+ */
+ protected Field getField(Class<?> clazz, String fieldName) {
+ try {
+ return clazz.getDeclaredField(fieldName);
+
+ } catch (NoSuchFieldException | SecurityException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java
deleted file mode 100644
index d1787482..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class EmptyParameterGroup extends ParameterGroupImpl {
-
- public EmptyParameterGroup(String name) {
- super(name);
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java
deleted file mode 100644
index e6c85923..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class ParameterGroupMissingGetter extends ParameterGroupImpl {
- private String value;
-
- public ParameterGroupMissingGetter(final String name) {
- super(name);
- }
-
- public String getTheValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java
deleted file mode 100644
index 1d90ca1f..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class ParameterGroupPrivateGetter extends ParameterGroupImpl {
- private String value;
-
- public ParameterGroupPrivateGetter(final String name) {
- super(name);
- }
-
- public String getTheValue() {
- return getValue();
- }
-
- private String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java
deleted file mode 100644
index e37b47ae..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class ParameterGroupWithArray extends ParameterGroupImpl {
- private int[] intArray = {1, 2, 3};
-
- public ParameterGroupWithArray(final String name) {
- super(name);
- }
-
- public int[] getIntArray() {
- return intArray;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java
deleted file mode 100644
index ee7c1715..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class ParameterGroupWithCollection extends ParameterGroupImpl {
- private List<Integer> intArrayList = new ArrayList<>();
-
- /**
- * Create a test parameter group.
- *
- * @param name the parameter group name
- */
- public ParameterGroupWithCollection(final String name) {
- super(name);
-
- intArrayList.add(1);
- intArrayList.add(2);
- intArrayList.add(3);
- }
-
- public List<Integer> getIntArrayList() {
- return intArrayList;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java
deleted file mode 100644
index b3c7d1b7..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import org.onap.policy.common.parameters.ParameterGroup;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class ParameterGroupWithIllegalMapKey extends ParameterGroupImpl {
- private Map<Integer, ParameterGroup> badMap = new LinkedHashMap<>();
-
- /**
- * Create a test parameter group.
- * @param name the parameter group name
- */
- public ParameterGroupWithIllegalMapKey(final String name) {
- super(name);
-
- badMap.put(1, new TestParametersLGeneric("One"));
- badMap.put(2, new TestParametersLGeneric("Two"));
- badMap.put(3, new TestParametersLGeneric("Three"));
- }
-
- public Map<Integer, ParameterGroup> getBadMap() {
- return badMap;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java
deleted file mode 100644
index 4df708a4..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class ParameterGroupWithIllegalMapValue extends ParameterGroupImpl {
- private Map<String, Integer> intMap = new LinkedHashMap<>();
-
- /**
- * Create a test parameter group.
- * @param name the parameter group name
- */
- public ParameterGroupWithIllegalMapValue(final String name) {
- super(name);
-
- intMap.put("One", 1);
- intMap.put("Two", 2);
- intMap.put("Three", 3);
- }
-
- public Map<String, Integer> getIntMap() {
- return intMap;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java
deleted file mode 100644
index 35752c75..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import java.util.List;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class ParameterGroupWithNullCollection extends ParameterGroupImpl {
- private List<Integer> nullList = null;
-
- /**
- * Create a test parameter group.
- * @param name the parameter group name
- */
- public ParameterGroupWithNullCollection(final String name) {
- super(name);
- }
-
- public List<Integer> getNullList() {
- return nullList;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java
deleted file mode 100644
index 08c799f5..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.onap.policy.common.parameters.ParameterGroup;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-
-public class ParameterGroupWithParameterGroupCollection extends ParameterGroupImpl {
- private List<ParameterGroup> parameterGroupArrayList = new ArrayList<>();
-
- /**
- * Create a test parameter group.
- * @param name the parameter group name
- */
- public ParameterGroupWithParameterGroupCollection(final String name) {
- super(name);
-
- parameterGroupArrayList.add(new TestParametersLGeneric("Generic0"));
- parameterGroupArrayList.add(new TestParametersLGeneric("Generic1"));
- parameterGroupArrayList.add(new TestParametersLGeneric("Generic2"));
- }
-
- public List<ParameterGroup> getParameterGroupArrayList() {
- return parameterGroupArrayList;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java
deleted file mode 100644
index 51440546..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.parameters.GroupValidationResult;
-import org.onap.policy.common.parameters.ParameterConstants;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-import org.onap.policy.common.parameters.ValidationStatus;
-
-public class TestParametersL00 extends ParameterGroupImpl {
- private static final String L00_INT_FIELD = "l00IntField";
- private static final String L00_STRING_FIELD = "l00StringField";
-
- private static final String A_CONSTANT = "A Constant";
-
- private int l00IntField = 0;
- private String l00StringField = "Legal " + this.getClass().getName();
- private TestParametersL10 l00L10Nested = new TestParametersL10("l00L10Nested");
- private TestParametersLGeneric l00LGenericNested = new TestParametersLGeneric("l00LGenericNested");
- private Map<String, TestParametersLGeneric> l00LGenericNestedMap = new LinkedHashMap<>();
- private boolean isSomeFlag;
- private boolean someNonIsFlag;
-
- /**
- * Default constructor.
- */
- public TestParametersL00() {
- super(A_CONSTANT);
- }
-
- /**
- * Create a test parameter group.
- *
- * @param name the parameter group name
- */
- public TestParametersL00(final String name) {
- super(name);
-
- TestParametersLGeneric l00LGenericNestedMapVal0 = new TestParametersLGeneric("l00LGenericNestedMapVal0");
- l00LGenericNestedMap.put(l00LGenericNestedMapVal0.getName(), l00LGenericNestedMapVal0);
- TestParametersLGeneric l00LGenericNestedMapVal1 = new TestParametersLGeneric("l00LGenericNestedMapVal1");
- l00LGenericNestedMap.put(l00LGenericNestedMapVal1.getName(), l00LGenericNestedMapVal1);
- }
-
- public int getL00IntField() {
- return l00IntField;
- }
-
- public String getL00StringField() {
- return l00StringField;
- }
-
- public TestParametersL10 getL00L10Nested() {
- return l00L10Nested;
- }
-
- public TestParametersLGeneric getL00LGenericNested() {
- return l00LGenericNested;
- }
-
- public Map<String, TestParametersLGeneric> getL00LGenericNestedMap() {
- return l00LGenericNestedMap;
- }
-
- public boolean isSomeFlag() {
- return isSomeFlag;
- }
-
- public boolean isSomeNonIsFlag() {
- return someNonIsFlag;
- }
-
- public void setSomeFlag(boolean isSomeFlag) {
- this.isSomeFlag = isSomeFlag;
- }
-
- public void setL00IntField(int l00IntField) {
- this.l00IntField = l00IntField;
- }
-
- public void setL00StringField(String l00StringField) {
- this.l00StringField = l00StringField;
- }
-
- public void setL00L10Nested(TestParametersL10 l00l10Nested) {
- l00L10Nested = l00l10Nested;
- }
-
- public void setL00LGenericNested(TestParametersLGeneric l00lGenericNested) {
- l00LGenericNested = l00lGenericNested;
- }
-
- public void setL00LGenericNestedMap(Map<String, TestParametersLGeneric> l00lGenericNestedMap) {
- l00LGenericNestedMap = l00lGenericNestedMap;
- }
-
- /**
- * Trigger a validation message.
- *
- * @param triggerStatus Validation status to trigger
- * @param level Number of levels to recurse before stopping
- */
- public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) {
- if (level == 0) {
- return;
- } else {
- level--;
- }
-
- switch (triggerStatus) {
- case CLEAN:
- l00StringField = "Legal " + this.getClass().getName();
- l00IntField = 0;
- break;
- case OBSERVATION:
- l00StringField = "aString";
- l00IntField = 2;
- break;
- case WARNING:
- l00StringField = L00_STRING_FIELD;
- l00IntField = 3;
- break;
- case INVALID:
- l00StringField = "";
- l00IntField = -1;
- break;
- default:
- break;
- }
-
- l00L10Nested.triggerValidationStatus(triggerStatus, level);
- l00LGenericNested.triggerValidationStatus(triggerStatus, level);
-
- for (TestParametersLGeneric nestedParameterGroup : l00LGenericNestedMap.values()) {
- nestedParameterGroup.triggerValidationStatus(triggerStatus, level);
- }
-
- }
-
- @Override
- public GroupValidationResult validate() {
- GroupValidationResult validationResult = super.validate();
-
- if (StringUtils.isBlank(getName())) {
- validationResult.setResult("name", ValidationStatus.INVALID, "name must be a non-blank string");
- }
-
- if (StringUtils.isBlank(l00StringField)) {
- validationResult.setResult(L00_STRING_FIELD, ValidationStatus.INVALID,
- "l00StringField must be a non-blank string");
- } else if (l00StringField.equals(L00_STRING_FIELD)) {
- validationResult.setResult(L00_STRING_FIELD, ValidationStatus.WARNING,
- "using the field name for the parameter value is dangerous");
- } else if (l00StringField.equals("aString")) {
- validationResult.setResult(L00_STRING_FIELD, ValidationStatus.OBSERVATION,
- "this value for name is unhelpful");
- } else {
- validationResult.setResult(L00_STRING_FIELD, ValidationStatus.CLEAN,
- ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString());
- }
-
- if (l00IntField < 0) {
- validationResult.setResult(L00_INT_FIELD, ValidationStatus.INVALID,
- "l00IntField must be a positive integer");
- } else if (l00IntField > 2) {
- validationResult.setResult(L00_INT_FIELD, ValidationStatus.WARNING,
- "values greater than 2 are not recommended");
- } else if (l00IntField == 2) {
- validationResult.setResult(L00_INT_FIELD, ValidationStatus.OBSERVATION, "this field has been set to 2");
- } else {
- validationResult.setResult(L00_INT_FIELD, ValidationStatus.CLEAN,
- ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString());
- }
-
- validationResult.setResult("l00L10Nested", l00L10Nested.validate());
- validationResult.setResult("l00LGenericNested", l00LGenericNested.validate());
-
- for (Entry<String, TestParametersLGeneric> nestedGroupEntry : l00LGenericNestedMap.entrySet()) {
- validationResult.setResult("l00LGenericNestedMap", nestedGroupEntry.getKey(),
- nestedGroupEntry.getValue().validate());
- }
-
- return validationResult;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java
deleted file mode 100644
index 7276b504..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
- * ================================================================================
- * 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.parameters.testclasses;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.parameters.GroupValidationResult;
-import org.onap.policy.common.parameters.ParameterConstants;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-import org.onap.policy.common.parameters.ValidationStatus;
-
-public class TestParametersL10 extends ParameterGroupImpl {
- private static final String L10_INT_FIELD = "l10IntField";
- private static final String L10_STRING_FIELD = "l10StringField";
-
- private int l10IntField = 0;
- private String l10StringField = "Legal " + this.getClass().getName();
- private TestParametersLGeneric l10LGenericNested0 = new TestParametersLGeneric("l10LGenericNested0");
- private TestParametersLGeneric l10LGenericNested1 = new TestParametersLGeneric("l10LGenericNested1");
- private Map<String, TestParametersLGeneric> l10LGenericNestedMap = new LinkedHashMap<>();
-
- /**
- * Default constructor.
- */
- public TestParametersL10() {
- // Default Constructor
- }
-
- /**
- * Create a test parameter group.
- *
- * @param name the parameter group name
- */
- public TestParametersL10(final String name) {
- super(name);
-
- TestParametersLGeneric l10LGenericNestedMapVal0 = new TestParametersLGeneric("l10LGenericNestedMapVal0");
- l10LGenericNestedMap.put(l10LGenericNestedMapVal0.getName(), l10LGenericNestedMapVal0);
- TestParametersLGeneric l10LGenericNestedMapVal1 = new TestParametersLGeneric("l10LGenericNestedMapVal1");
- l10LGenericNestedMap.put(l10LGenericNestedMapVal1.getName(), l10LGenericNestedMapVal1);
- }
-
- public int getL10IntField() {
- return l10IntField;
- }
-
- public String getL10StringField() {
- return l10StringField;
- }
-
- public TestParametersLGeneric getL10LGenericNested0() {
- return l10LGenericNested0;
- }
-
- public TestParametersLGeneric getL10LGenericNested1() {
- return l10LGenericNested1;
- }
-
- public Map<String, TestParametersLGeneric> getL10LGenericNestedMap() {
- return l10LGenericNestedMap;
- }
-
- public void setL10IntField(int l10IntField) {
- this.l10IntField = l10IntField;
- }
-
- public void setL10StringField(String l10StringField) {
- this.l10StringField = l10StringField;
- }
-
- public void setL10LGenericNested0(TestParametersLGeneric l10lGenericNested0) {
- l10LGenericNested0 = l10lGenericNested0;
- }
-
- public void setL10LGenericNested1(TestParametersLGeneric l10lGenericNested1) {
- l10LGenericNested1 = l10lGenericNested1;
- }
-
- public void setL10LGenericNestedMap(Map<String, TestParametersLGeneric> l10lGenericNestedMap) {
- l10LGenericNestedMap = l10lGenericNestedMap;
- }
-
- /**
- * Trigger a validation message.
- *
- * @param level Number of levels to recurse before stopping
- */
- public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) {
- if (level == 0) {
- return;
- }
- else {
- level--;
- }
-
- switch (triggerStatus) {
- case CLEAN:
- l10StringField = "Legal " + this.getClass().getName();
- l10IntField = 0;
- break;
- case OBSERVATION:
- l10StringField = "aString";
- l10IntField = 2;
- break;
- case WARNING:
- l10StringField = L10_STRING_FIELD;
- l10IntField = 3;
- break;
- case INVALID:
- l10StringField = "";
- l10IntField = -1;
- break;
- default:
- break;
- }
-
- l10LGenericNested0.triggerValidationStatus(triggerStatus, level);
- l10LGenericNested1.triggerValidationStatus(triggerStatus, level);
-
- for (TestParametersLGeneric nestedParameterGroup : l10LGenericNestedMap.values()) {
- nestedParameterGroup.triggerValidationStatus(triggerStatus, level);
- }
- }
-
- @Override
- public GroupValidationResult validate() {
- GroupValidationResult validationResult = super.validate();
-
- if (StringUtils.isBlank(l10StringField)) {
- validationResult.setResult(L10_STRING_FIELD, ValidationStatus.INVALID,
- "l10StringField must be a non-blank string");
- } else if (l10StringField.equals(L10_STRING_FIELD)) {
- validationResult.setResult(L10_STRING_FIELD, ValidationStatus.WARNING,
- "using the field name for the parameter value is dangerous");
- } else if (l10StringField.equals("aString")) {
- validationResult.setResult(L10_STRING_FIELD, ValidationStatus.OBSERVATION,
- "this value for name is unhelpful");
- } else {
- validationResult.setResult(L10_STRING_FIELD, ValidationStatus.CLEAN,
- ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString());
- }
-
- if (l10IntField < 0) {
- validationResult.setResult(L10_INT_FIELD, ValidationStatus.INVALID,
- "l10IntField must be a positive integer");
- } else if (l10IntField > 2) {
- validationResult.setResult(L10_INT_FIELD, ValidationStatus.WARNING,
- "values greater than 2 are not recommended");
- } else if (l10IntField == 2) {
- validationResult.setResult(L10_INT_FIELD, ValidationStatus.OBSERVATION, "this field has been set to 2");
- } else {
- validationResult.setResult(L10_INT_FIELD, ValidationStatus.CLEAN,
- ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString());
- }
-
- if (l10LGenericNested0 != null) {
- validationResult.setResult("l10LGenericNested0", l10LGenericNested0.validate());
- }
- validationResult.setResult("l10LGenericNested1", l10LGenericNested1.validate());
-
- for (Entry<String, TestParametersLGeneric> nestedGroupEntry : l10LGenericNestedMap.entrySet()) {
- validationResult.setResult("l10LGenericNestedMap", nestedGroupEntry.getKey(),
- nestedGroupEntry.getValue().validate());
- }
-
- return validationResult;
- }
-}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java
deleted file mode 100644
index f9d6cdc4..00000000
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters.testclasses;
-
-import org.onap.policy.common.parameters.GroupValidationResult;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-import org.onap.policy.common.parameters.ValidationStatus;
-import org.onap.policy.common.parameters.annotations.NotBlank;
-import org.onap.policy.common.parameters.annotations.NotNull;
-
-public class TestParametersLGeneric extends ParameterGroupImpl {
- private static final String LGENERIC_INT_FIELD = "lgenericIntField";
- private static final String LGENERIC_STRING_FIELD = "lgenericStringField";
-
- private int lgenericIntField = 0;
-
- @NotNull @NotBlank
- private String lgenericStringField = "Legal " + this.getClass().getName();
-
- /**
- * Default constructor.
- */
- public TestParametersLGeneric() {
- // Default Constructor
- }
-
- /**
- * Create a test parameter group.
- *
- * @param name the parameter group name
- */
- public TestParametersLGeneric(final String name) {
- super(name);
- }
-
- public int getLgenericIntField() {
- return lgenericIntField;
- }
-
- public String getLgenericStringField() {
- return lgenericStringField;
- }
-
- public void setLgenericIntField(int lgenericIntField) {
- this.lgenericIntField = lgenericIntField;
- }
-
- public void setLgenericStringField(String lgenericStringField) {
- this.lgenericStringField = lgenericStringField;
- }
-
- /**
- * Trigger a validation message.
- *
- * @param level Number of levels to recurse before stopping
- */
- public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) {
- if (level == 0) {
- return;
- }
-
- switch (triggerStatus) {
- case CLEAN:
- lgenericStringField = "Legal " + this.getClass().getName();
- lgenericIntField = 0;
- break;
- case OBSERVATION:
- lgenericStringField = "aString";
- lgenericIntField = 2;
- break;
- case WARNING:
- lgenericStringField = LGENERIC_STRING_FIELD;
- lgenericIntField = 3;
- break;
- case INVALID:
- lgenericStringField = "";
- lgenericIntField = -1;
- break;
- default:
- break;
- }
-
- }
-
- @Override
- public GroupValidationResult validate() {
- GroupValidationResult validationResult = super.validate();
-
- if (LGENERIC_STRING_FIELD.equals(lgenericStringField)) {
- validationResult.setResult(LGENERIC_STRING_FIELD, ValidationStatus.WARNING,
- "using the field name for the parameter value is dangerous");
- } else if ("aString".equals(lgenericStringField)) {
- validationResult.setResult(LGENERIC_STRING_FIELD, ValidationStatus.OBSERVATION,
- "this value for name is unhelpful");
- }
-
- if (lgenericIntField < 0) {
- validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.INVALID,
- "lgenericIntField must be a positive integer");
- } else if (lgenericIntField > 2) {
- validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.WARNING,
- "values greater than 2 are not recommended");
- } else if (lgenericIntField == 2) {
- validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.OBSERVATION,
- "this field has been set to 2");
- }
-
- return validationResult;
- }
-}
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt b/common-parameters/src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt
deleted file mode 100644
index 64af7247..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-parameter group "l00NameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" CLEAN, parameter group has status CLEAN
- field "l00IntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "l00StringField" type "java.lang.String" value "l00 string field value from file" CLEAN, parameter has status CLEAN
- parameter group "l00L10NestedNameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" CLEAN, parameter group has status CLEAN
- field "l10IntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "l10StringField" type "java.lang.String" value "l00 L10 nested string field value from file" CLEAN, parameter has status CLEAN
- parameter group "l10LGenericNested0NameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "l10 generic nested 0 string field value from file" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l10LGenericNested0NameFromFile" CLEAN, parameter has status CLEAN
- parameter group "l10LGenericNested1NameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "l10 generic nested 1 string field value from file" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l10LGenericNested1NameFromFile" CLEAN, parameter has status CLEAN
- parameter group map "l10LGenericNestedMap" CLEAN, parameter group map has status CLEAN
- parameter group "L10Entry0Name" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "L10Entry0 value from file" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "L10Entry0Name" CLEAN, parameter has status CLEAN
- parameter group "L10Entry1Name" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "L10Entry1 value from file" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "L10Entry1Name" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l00L10NestedNameFromFile" CLEAN, parameter has status CLEAN
- parameter group "l00GenericNestedNameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "l00 generic nested string field value from file" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l00GenericNestedNameFromFile" CLEAN, parameter has status CLEAN
- parameter group map "l00LGenericNestedMap" CLEAN, parameter group map has status CLEAN
- parameter group "L00Entry0Name" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "L00Entry0 value from file" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "L00Entry0Name" CLEAN, parameter has status CLEAN
- parameter group "L00Entry1Name" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "L00Entry1 value from file" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "L00Entry1Name" CLEAN, parameter has status CLEAN
- field "isSomeFlag" type "boolean" value "false" CLEAN, parameter has status CLEAN
- field "someNonIsFlag" type "boolean" value "false" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l00NameFromFile" CLEAN, parameter has status CLEAN
- \ No newline at end of file
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt
deleted file mode 100644
index d6b43312..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" CLEAN, parameter group has status CLEAN
- field "l00IntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "l00StringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersL00" CLEAN, parameter has status CLEAN
- parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" CLEAN, parameter group has status CLEAN
- field "l10IntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "l10StringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersL10" CLEAN, parameter has status CLEAN
- parameter group "l10LGenericNested0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l10LGenericNested0" CLEAN, parameter has status CLEAN
- parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l10LGenericNested1" CLEAN, parameter has status CLEAN
- parameter group map "l10LGenericNestedMap" CLEAN, parameter group map has status CLEAN
- parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l10LGenericNestedMapVal0" CLEAN, parameter has status CLEAN
- parameter group "l10LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l10LGenericNestedMapVal1" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l00L10Nested" CLEAN, parameter has status CLEAN
- parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l00LGenericNested" CLEAN, parameter has status CLEAN
- parameter group map "l00LGenericNestedMap" CLEAN, parameter group map has status CLEAN
- parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l00LGenericNestedMapVal0" CLEAN, parameter has status CLEAN
- parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN
- field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN
- field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l00LGenericNestedMapVal1" CLEAN, parameter has status CLEAN
- field "isSomeFlag" type "boolean" value "false" CLEAN, parameter has status CLEAN
- field "someNonIsFlag" type "boolean" value "false" CLEAN, parameter has status CLEAN
- field "name" type "java.lang.String" value "l0Parameters" CLEAN, parameter has status CLEAN
- \ No newline at end of file
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt
deleted file mode 100644
index dcc3cee3..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" INVALID, parameter group has status INVALID
- field "l00IntField" type "int" value "-1" INVALID, l00IntField must be a positive integer
- field "l00StringField" type "java.lang.String" value "" INVALID, l00StringField must be a non-blank string
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt
deleted file mode 100644
index ae627926..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" OBSERVATION, parameter group has status OBSERVATION
- field "l00IntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "l00StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt
deleted file mode 100644
index 14a65aa8..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" WARNING, parameter group has status WARNING
- field "l00IntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "l00StringField" type "java.lang.String" value "l00StringField" WARNING, using the field name for the parameter value is dangerous
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt
deleted file mode 100644
index 412a36c1..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" INVALID, parameter group has status INVALID
- field "l00IntField" type "int" value "-1" INVALID, l00IntField must be a positive integer
- field "l00StringField" type "java.lang.String" value "" INVALID, l00StringField must be a non-blank string
- parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" INVALID, parameter group has status INVALID
- field "l10IntField" type "int" value "-1" INVALID, l10IntField must be a positive integer
- field "l10StringField" type "java.lang.String" value "" INVALID, l10StringField must be a non-blank string
- parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
- parameter group map "l00LGenericNestedMap" INVALID, parameter group map has status INVALID
- parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
- parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string \ No newline at end of file
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt
deleted file mode 100644
index c1989226..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" OBSERVATION, parameter group has status OBSERVATION
- field "l00IntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "l00StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" OBSERVATION, parameter group has status OBSERVATION
- field "l10IntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "l10StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group map "l00LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION
- parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt
deleted file mode 100644
index 380ded8f..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" WARNING, parameter group has status WARNING
- field "l00IntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "l00StringField" type "java.lang.String" value "l00StringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" WARNING, parameter group has status WARNING
- field "l10IntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "l10StringField" type "java.lang.String" value "l10StringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
- parameter group map "l00LGenericNestedMap" WARNING, parameter group map has status WARNING
- parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous \ No newline at end of file
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt
deleted file mode 100644
index 12bce5c3..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" INVALID, parameter group has status INVALID
- field "l00IntField" type "int" value "-1" INVALID, l00IntField must be a positive integer
- field "l00StringField" type "java.lang.String" value "" INVALID, l00StringField must be a non-blank string
- parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" INVALID, parameter group has status INVALID
- field "l10IntField" type "int" value "-1" INVALID, l10IntField must be a positive integer
- field "l10StringField" type "java.lang.String" value "" INVALID, l10StringField must be a non-blank string
- parameter group "l10LGenericNested0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
- parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
- parameter group map "l10LGenericNestedMap" INVALID, parameter group map has status INVALID
- parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
- parameter group "l10LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
- parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
- parameter group map "l00LGenericNestedMap" INVALID, parameter group map has status INVALID
- parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
- parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID
- field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer
- field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string \ No newline at end of file
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt
deleted file mode 100644
index 36517cef..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" OBSERVATION, parameter group has status OBSERVATION
- field "l00IntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "l00StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" OBSERVATION, parameter group has status OBSERVATION
- field "l10IntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "l10StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l10LGenericNested0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group map "l10LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION
- parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l10LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group map "l00LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION
- parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
- parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION
- field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2
- field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful
diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt
deleted file mode 100644
index 28747670..00000000
--- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" WARNING, parameter group has status WARNING
- field "l00IntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "l00StringField" type "java.lang.String" value "l00StringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" WARNING, parameter group has status WARNING
- field "l10IntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "l10StringField" type "java.lang.String" value "l10StringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l10LGenericNested0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
- parameter group map "l10LGenericNestedMap" WARNING, parameter group map has status WARNING
- parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l10LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
- parameter group map "l00LGenericNestedMap" WARNING, parameter group map has status WARNING
- parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
- parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING
- field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended
- field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous \ No newline at end of file
diff --git a/gson/pom.xml b/gson/pom.xml
index 1ef8c9a7..3518224d 100644
--- a/gson/pom.xml
+++ b/gson/pom.xml
@@ -2,8 +2,8 @@
============LICENSE_START=======================================================
ONAP Policy Engine - Common Modules
================================================================================
- Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2019 Nordix Foundation.
+ Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved.
+ Modifications Copyright (C) 2019, 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.
@@ -18,128 +18,25 @@
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">
+<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>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
-
<artifactId>gson</artifactId>
<description>Common Utilities</description>
<packaging>jar</packaging>
<dependencies>
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.glassfish.jersey.core</groupId>
- <artifactId>jersey-server</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito2</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <groupId>jakarta.ws.rs</groupId>
+ <artifactId>jakarta.ws.rs-api</artifactId>
</dependency>
</dependencies>
-
- <build>
- <pluginManagement>
- <plugins>
- <!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.jacoco</groupId>
- <artifactId>
- jacoco-maven-plugin
- </artifactId>
- <versionRange>
- [0.7.1.201405082137,)
- </versionRange>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <plugin>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>onap-java-style</id>
- <goals>
- <goal>check</goal>
- </goals>
- <phase>process-sources</phase>
- <configuration>
- <!-- Use Google Java Style Guide:
- https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml
- with minor changes -->
- <configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
- <!-- <sourceDirectory> is needed so that checkstyle ignores the generated sources directory -->
- <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
- <includeResources>true</includeResources>
- <includeTestSourceDirectory>true</includeTestSourceDirectory>
- <includeTestResources>true</includeTestResources>
- <excludes>
- </excludes>
- <consoleOutput>true</consoleOutput>
- <failsOnViolation>true</failsOnViolation>
- <violationSeverity>warning</violationSeverity>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.onap.oparent</groupId>
- <artifactId>checkstyle</artifactId>
- <version>${oparent.version}</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
- </plugin>
- </plugins>
- </build>
</project>
diff --git a/gson/src/main/java/org/onap/policy/common/gson/DoubleConverter.java b/gson/src/main/java/org/onap/policy/common/gson/DoubleConverter.java
index 81803ff2..4d10bd13 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/DoubleConverter.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/DoubleConverter.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -25,18 +25,17 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
/**
* Converter for Double values. By default, GSON treats all Objects that are numbers, as
* Double. This converts Doubles to Integer or Long, if possible. It converts stand-alone
* Doubles, as well as those found within Arrays and Maps.
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DoubleConverter {
- private DoubleConverter() {
- // do nothing
- }
-
/**
* Performs in-place conversion of all values in a list.
*
@@ -98,7 +97,7 @@ public class DoubleConverter {
}
Double num = (Double) value;
- long longval = num.longValue();
+ var longval = num.longValue();
if (Double.compare(num.doubleValue(), longval) != 0) {
// it isn't integral - return unchanged value
@@ -106,7 +105,7 @@ public class DoubleConverter {
}
// it's integral - determine if it's an integer or a long
- int intval = (int) longval;
+ var intval = (int) longval;
if (intval == longval) {
return intval;
diff --git a/gson/src/main/java/org/onap/policy/common/gson/GsonMessageBodyHandler.java b/gson/src/main/java/org/onap/policy/common/gson/GsonMessageBodyHandler.java
index 75d58f2f..a693b7f4 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/GsonMessageBodyHandler.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/GsonMessageBodyHandler.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -22,6 +23,13 @@ package org.onap.policy.common.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.ext.MessageBodyReader;
+import jakarta.ws.rs.ext.MessageBodyWriter;
+import jakarta.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -30,13 +38,13 @@ import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.OffsetDateTime;
+import java.time.OffsetTime;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
import lombok.AccessLevel;
import lombok.Getter;
import org.slf4j.Logger;
@@ -85,7 +93,14 @@ public class GsonMessageBodyHandler implements MessageBodyReader<Object>, Messag
* @return the configured builder
*/
public static GsonBuilder configBuilder(GsonBuilder builder) {
- return builder.disableHtmlEscaping().registerTypeAdapterFactory(new MapDoubleAdapterFactory());
+ return builder.disableHtmlEscaping().registerTypeAdapterFactory(new MapDoubleAdapterFactory())
+ .registerTypeAdapter(Instant.class, new InstantTypeAdapter())
+ .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter())
+ .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeTypeAdapter())
+ .registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter())
+ .registerTypeAdapter(OffsetTime.class, new OffsetTimeTypeAdapter())
+ .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
+ .registerTypeAdapter(ZoneOffset.class, new ZoneOffsetTypeAdapter());
}
@Override
@@ -102,7 +117,7 @@ public class GsonMessageBodyHandler implements MessageBodyReader<Object>, Messag
public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
- try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
+ try (var writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
Type jsonType = (type.equals(genericType) ? type : genericType);
gson.toJson(object, jsonType, writer);
}
@@ -138,7 +153,7 @@ public class GsonMessageBodyHandler implements MessageBodyReader<Object>, Messag
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
- try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
+ try (var streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
Type jsonType = (type.equals(genericType) ? type : genericType);
return gson.fromJson(streamReader, jsonType);
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafGranularAuthFilter.java b/gson/src/main/java/org/onap/policy/common/gson/InstantAsMillisTypeAdapter.java
index 183e5ae7..c38a3e9b 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafGranularAuthFilter.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/InstantAsMillisTypeAdapter.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -18,29 +18,37 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.common.endpoints.http.server.test;
+package org.onap.policy.common.gson;
-import javax.servlet.http.HttpServletRequest;
-import org.onap.policy.common.endpoints.http.server.aaf.AafGranularAuthFilter;
-import org.onap.policy.common.utils.network.NetworkUtil;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.time.Instant;
-public class TestAafGranularAuthFilter extends AafGranularAuthFilter {
+/**
+ * GSON Type Adapter for "Instant" fields, that encodes them as milliseconds.
+ */
+public class InstantAsMillisTypeAdapter extends TypeAdapter<Instant> {
@Override
- protected String getRole(HttpServletRequest request) {
- String expectedPerm = this.getPermissionTypeRoot()
- + request.getRequestURI().replace('/', '.') + "|"
- + NetworkUtil.getHostname() + "|"
- + request.getMethod().toLowerCase();
- if (!expectedPerm.equals(super.getRole(request))) {
- throw new IllegalStateException("unexpected AAF granular permission");
+ public void write(JsonWriter out, Instant value) throws IOException {
+ if (value == null) {
+ out.nullValue();
} else {
- return "user";
+ out.value(value.toEpochMilli());
}
}
@Override
- public String getPermissionTypeRoot() {
- return "org.onap.policy";
+ public Instant read(JsonReader in) throws IOException {
+ if (in.peek() == JsonToken.NULL) {
+ in.nextNull();
+ return null;
+ } else {
+ var millis = in.nextLong();
+ return Instant.ofEpochMilli(millis);
+ }
}
-} \ No newline at end of file
+}
diff --git a/gson/src/main/java/org/onap/policy/common/gson/InstantTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/InstantTypeAdapter.java
new file mode 100644
index 00000000..bad66af3
--- /dev/null
+++ b/gson/src/main/java/org/onap/policy/common/gson/InstantTypeAdapter.java
@@ -0,0 +1,36 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import java.time.Instant;
+
+/**
+ * GSON Type Adapter for "Instant" fields, that uses the standard ISO_INSTANT formatter.
+ */
+public class InstantTypeAdapter extends StringTypeAdapter<Instant> {
+
+ /**
+ * Constructs an adapter.
+ */
+ public InstantTypeAdapter() {
+ super("date", Instant::parse, Instant::toString);
+ }
+}
diff --git a/gson/src/main/java/org/onap/policy/common/gson/JacksonFieldAdapterFactory.java b/gson/src/main/java/org/onap/policy/common/gson/JacksonFieldAdapterFactory.java
index 3458a590..18157b03 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/JacksonFieldAdapterFactory.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/JacksonFieldAdapterFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -54,7 +54,7 @@ public class JacksonFieldAdapterFactory implements TypeAdapterFactory {
return null;
}
- ClassWalker data = new ClassWalker();
+ var data = new ClassWalker();
data.walkClassHierarchy(clazz);
if (data.getInProps(Field.class).isEmpty() && data.getOutProps(Field.class).isEmpty()) {
diff --git a/gson/src/main/java/org/onap/policy/common/gson/JacksonMethodAdapterFactory.java b/gson/src/main/java/org/onap/policy/common/gson/JacksonMethodAdapterFactory.java
index de962316..b7414004 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/JacksonMethodAdapterFactory.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/JacksonMethodAdapterFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -58,7 +58,7 @@ public class JacksonMethodAdapterFactory implements TypeAdapterFactory {
return null;
}
- ClassWalker data = new ClassWalker();
+ var data = new ClassWalker();
data.walkClassHierarchy(clazz);
if (data.getInProps(Method.class).isEmpty() && data.getOutProps(Method.class).isEmpty()
diff --git a/gson/src/main/java/org/onap/policy/common/gson/LocalDateTimeTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/LocalDateTimeTypeAdapter.java
new file mode 100644
index 00000000..5dc597e2
--- /dev/null
+++ b/gson/src/main/java/org/onap/policy/common/gson/LocalDateTimeTypeAdapter.java
@@ -0,0 +1,39 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+/**
+ * GSON Type Adapter for "LocalDateTime" fields, that uses the standard
+ * ISO_LOCAL_DATE_TIME formatter, by default.
+ */
+public class LocalDateTimeTypeAdapter extends StringTypeAdapter<LocalDateTime> {
+
+ public LocalDateTimeTypeAdapter() {
+ this(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
+ }
+
+ public LocalDateTimeTypeAdapter(DateTimeFormatter formatter) {
+ super("date", string -> LocalDateTime.parse(string, formatter), value -> value.format(formatter));
+ }
+}
diff --git a/gson/src/main/java/org/onap/policy/common/gson/LocalDateTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/LocalDateTypeAdapter.java
new file mode 100644
index 00000000..0f666e5e
--- /dev/null
+++ b/gson/src/main/java/org/onap/policy/common/gson/LocalDateTypeAdapter.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+
+public class LocalDateTypeAdapter extends StringTypeAdapter<LocalDate> {
+
+ public LocalDateTypeAdapter() {
+ this(DateTimeFormatter.ISO_LOCAL_DATE);
+ }
+
+ public LocalDateTypeAdapter(DateTimeFormatter formatter) {
+ super("date", string -> LocalDate.parse(string, formatter), value -> value.format(formatter));
+ }
+}
diff --git a/gson/src/main/java/org/onap/policy/common/gson/MapDoubleAdapterFactory.java b/gson/src/main/java/org/onap/policy/common/gson/MapDoubleAdapterFactory.java
index bd031999..057e97f8 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/MapDoubleAdapterFactory.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/MapDoubleAdapterFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -51,24 +51,36 @@ public class MapDoubleAdapterFactory implements TypeAdapterFactory {
}
private <T> boolean isMapType(TypeToken<T> type) {
- if (type.getRawType() != Map.class) {
+ if (!Map.class.isAssignableFrom(type.getRawType())) {
return false;
}
+ // only supports Map<String,Object>
+
+ if (!(type.getType() instanceof ParameterizedType)) {
+ // untyped - assume the parameters are the correct type
+ return true;
+ }
+
Type[] actualParams = ((ParameterizedType) type.getType()).getActualTypeArguments();
- // only supports Map<String,Object>
return (actualParams[0] == String.class && actualParams[1] == Object.class);
}
private <T> boolean isListType(TypeToken<T> type) {
- if (type.getRawType() != List.class) {
+ if (!List.class.isAssignableFrom(type.getRawType())) {
return false;
}
+ // only supports List<Object>
+
+ if (!(type.getType() instanceof ParameterizedType)) {
+ // untyped - assume the parameters are the correct type
+ return true;
+ }
+
Type[] actualParams = ((ParameterizedType) type.getType()).getActualTypeArguments();
- // only supports List<Object>
return (actualParams[0] == Object.class);
}
@@ -100,7 +112,7 @@ public class MapDoubleAdapterFactory implements TypeAdapterFactory {
@Override
public T read(JsonReader in) throws IOException {
- T value = delegate.read(in);
+ var value = delegate.read(in);
DoubleConverter.convertFromDouble(value);
diff --git a/gson/src/main/java/org/onap/policy/common/gson/OffsetDateTimeTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/OffsetDateTimeTypeAdapter.java
new file mode 100644
index 00000000..3f046b01
--- /dev/null
+++ b/gson/src/main/java/org/onap/policy/common/gson/OffsetDateTimeTypeAdapter.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import java.time.OffsetDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class OffsetDateTimeTypeAdapter extends StringTypeAdapter<OffsetDateTime> {
+
+ public OffsetDateTimeTypeAdapter() {
+ this(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
+ }
+
+ public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) {
+ super("date", string -> OffsetDateTime.parse(string, formatter), value -> value.format(formatter));
+ }
+}
diff --git a/gson/src/main/java/org/onap/policy/common/gson/OffsetTimeTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/OffsetTimeTypeAdapter.java
new file mode 100644
index 00000000..895b9de6
--- /dev/null
+++ b/gson/src/main/java/org/onap/policy/common/gson/OffsetTimeTypeAdapter.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import java.time.OffsetTime;
+import java.time.format.DateTimeFormatter;
+
+public class OffsetTimeTypeAdapter extends StringTypeAdapter<OffsetTime> {
+
+ public OffsetTimeTypeAdapter() {
+ this(DateTimeFormatter.ISO_OFFSET_TIME);
+ }
+
+ public OffsetTimeTypeAdapter(DateTimeFormatter formatter) {
+ super("time", string -> OffsetTime.parse(string, formatter), value -> value.format(formatter));
+ }
+}
diff --git a/gson/src/main/java/org/onap/policy/common/gson/StringTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/StringTypeAdapter.java
new file mode 100644
index 00000000..22481697
--- /dev/null
+++ b/gson/src/main/java/org/onap/policy/common/gson/StringTypeAdapter.java
@@ -0,0 +1,76 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import com.google.gson.JsonParseException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.util.function.Function;
+
+/**
+ * GSON Type Adapter for fields that are encoded as Strings.
+ */
+public class StringTypeAdapter<T> extends TypeAdapter<T> {
+ private final String exMessage;
+ private final Function<String, T> deserializer;
+ private final Function<T, String> serializer;
+
+ /**
+ * Constructs an adapter.
+ *
+ * @param type type of value, used in exception messages
+ * @param deserializer function used to deserialize a String into a value
+ * @param serializer function used to serialize a value into a String
+ */
+ public StringTypeAdapter(String type, Function<String, T> deserializer, Function<T, String> serializer) {
+ this.exMessage = "invalid " + type;
+ this.deserializer = deserializer;
+ this.serializer = serializer;
+ }
+
+ @Override
+ public T read(JsonReader in) throws IOException {
+ try {
+ if (in.peek() == JsonToken.NULL) {
+ in.nextNull();
+ return null;
+ } else {
+ return deserializer.apply(in.nextString());
+ }
+
+ } catch (RuntimeException e) {
+ throw new JsonParseException(exMessage, e);
+ }
+ }
+
+ @Override
+ public void write(JsonWriter out, T value) throws IOException {
+ if (value == null) {
+ out.nullValue();
+ } else {
+ String text = serializer.apply(value);
+ out.value(text);
+ }
+ }
+}
diff --git a/gson/src/main/java/org/onap/policy/common/gson/ZoneOffsetTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/ZoneOffsetTypeAdapter.java
new file mode 100644
index 00000000..60758ff3
--- /dev/null
+++ b/gson/src/main/java/org/onap/policy/common/gson/ZoneOffsetTypeAdapter.java
@@ -0,0 +1,30 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import java.time.ZoneOffset;
+
+public class ZoneOffsetTypeAdapter extends StringTypeAdapter<ZoneOffset> {
+
+ public ZoneOffsetTypeAdapter() {
+ super("zone", ZoneOffset::of, ZoneOffset::toString);
+ }
+}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafAuthFilter.java b/gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java
index 27d45c8d..928fae95 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafAuthFilter.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -18,30 +18,30 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.common.endpoints.http.server.test;
+package org.onap.policy.common.gson;
-import javax.servlet.http.HttpServletRequest;
-import org.onap.policy.common.endpoints.http.server.aaf.AafAuthFilter;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
-public class TestAafAuthFilter extends AafAuthFilter {
-
- @Override
- protected String getRole(HttpServletRequest request) {
- String expectedPerm = "test|test|" + request.getMethod().toLowerCase();
- if (!expectedPerm.equals(super.getRole(request))) {
- throw new IllegalStateException("unexpected permission");
- } else {
- return "user";
- }
- }
+/**
+ * GSON Type Adapter for "ZonedDateTime" fields, that uses the standard
+ * ISO_ZONED_DATE_TIME formatter.
+ */
+public class ZonedDateTimeTypeAdapter extends StringTypeAdapter<ZonedDateTime> {
- @Override
- protected String getPermissionType(HttpServletRequest request) {
- return "test";
+ /**
+ * Constructs an adapter that uses the ISO_ZONED_DATE_TIME formatter.
+ */
+ public ZonedDateTimeTypeAdapter() {
+ this(DateTimeFormatter.ISO_ZONED_DATE_TIME);
}
- @Override
- protected String getPermissionInstance(HttpServletRequest request) {
- return "test";
+ /**
+ * Constructs an adapter that uses the specified formatter for reading and writing.
+ *
+ * @param formatter date-time formatter
+ */
+ public ZonedDateTimeTypeAdapter(DateTimeFormatter formatter) {
+ super("date", string -> ZonedDateTime.parse(string, formatter), value -> value.format(formatter));
}
-} \ No newline at end of file
+}
diff --git a/gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java b/gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java
index 174b4912..af4a746c 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -24,11 +24,12 @@ import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
+import com.google.re2j.Pattern;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.function.Supplier;
-import java.util.regex.Pattern;
+import lombok.Getter;
import org.onap.policy.common.gson.annotation.GsonJsonProperty;
/**
@@ -49,6 +50,7 @@ public class Adapter {
/**
* Name of the property within the json structure containing the item.
*/
+ @Getter
private final String propName;
/**
@@ -69,6 +71,7 @@ public class Adapter {
/**
* Name of the item being lifted - used when throwing exceptions.
*/
+ @Getter
private final String fullName;
/**
@@ -83,7 +86,10 @@ public class Adapter {
this.gson = gson;
this.fullName = getQualifiedName(field);
- field.setAccessible(true);
+ /*
+ * Turning off sonar, as this is required for emulation of "jackson".
+ */
+ field.setAccessible(true); // NOSONAR
}
/**
@@ -100,7 +106,10 @@ public class Adapter {
this.gson = gson;
this.fullName = getQualifiedName(accessor);
- accessor.setAccessible(true);
+ /*
+ * Turning off sonar, as this is required for emulation of "jackson".
+ */
+ accessor.setAccessible(true); // NOSONAR
}
/**
@@ -121,8 +130,8 @@ public class Adapter {
ConvInfo wtr = writer;
- @SuppressWarnings("rawtypes")
- TypeAdapter conv = (wtr.clazz == clazz ? wtr.getConverter() : gson.getAdapter(clazz));
+ TypeAdapter<Object> conv =
+ (wtr.clazz == clazz ? wtr.getConverter() : (TypeAdapter<Object>) gson.getAdapter(clazz));
return conv.toJsonTree(object);
}
@@ -137,14 +146,6 @@ public class Adapter {
return reader.getConverter().fromJsonTree(tree);
}
- public final String getPropName() {
- return propName;
- }
-
- public final String getFullName() {
- return fullName;
- }
-
/**
* Makes an error message, appending the item's full name to the message prefix.
*
@@ -310,36 +311,33 @@ public class Adapter {
/**
* Type on which the converter works.
*/
- @SuppressWarnings("rawtypes")
- private TypeToken type;
+ private TypeToken<?> type;
/**
* Class of object on which the converter works.
*/
- @SuppressWarnings("rawtypes")
- private Class clazz;
+ private Class<?> clazz;
/**
* Converter to use, initialized lazily.
*/
- @SuppressWarnings("rawtypes")
- private TypeAdapter conv = null;
+ private TypeAdapter<Object> conv = null;
/**
* Constructs the object.
*
* @param type type of object to be converted
*/
- public ConvInfo(@SuppressWarnings("rawtypes") TypeToken type) {
+ public ConvInfo(TypeToken<?> type) {
this.type = type;
this.clazz = type.getRawType();
}
- @SuppressWarnings({"rawtypes", "unchecked"})
- public final TypeAdapter getConverter() {
+ @SuppressWarnings("unchecked")
+ public final TypeAdapter<Object> getConverter() {
if (conv == null) {
// race condition here, but it's ok to overwrite a previous value
- this.conv = gson.getAdapter(type);
+ this.conv = (TypeAdapter<Object>) gson.getAdapter(type);
}
return conv;
diff --git a/gson/src/main/java/org/onap/policy/common/gson/internal/ClassWalker.java b/gson/src/main/java/org/onap/policy/common/gson/internal/ClassWalker.java
index ef4eaae3..954d3f4c 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/internal/ClassWalker.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/internal/ClassWalker.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -30,6 +30,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import lombok.Getter;
import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
@@ -79,23 +80,16 @@ public class ClassWalker {
* Method having {@link GsonJsonAnyGetter} annotation. Overwritten as new "any-getters"
* are identified.
*/
+ @Getter
private Method anyGetter = null;
/**
* Method having {@link GsonJsonAnySetter} annotation. Overwritten as new "any-setters"
* are identified.
*/
+ @Getter
private Method anySetter = null;
-
- public Method getAnyGetter() {
- return anyGetter;
- }
-
- public Method getAnySetter() {
- return anySetter;
- }
-
/**
* Gets the names of input properties that are not being ignored.
*
diff --git a/gson/src/main/java/org/onap/policy/common/gson/internal/FieldDeserializer.java b/gson/src/main/java/org/onap/policy/common/gson/internal/FieldDeserializer.java
index 14a432d1..123b0195 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/internal/FieldDeserializer.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/internal/FieldDeserializer.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -49,7 +49,10 @@ public class FieldDeserializer extends Adapter implements Deserializer {
this.field = field;
- field.setAccessible(true);
+ /*
+ * Turning off sonar, as this is required for emulation of "jackson".
+ */
+ field.setAccessible(true); // NOSONAR
}
@Override
@@ -62,7 +65,10 @@ public class FieldDeserializer extends Adapter implements Deserializer {
Object value = fromJsonTree(jsonEl);
try {
- field.set(target, value);
+ /*
+ * Turning off sonar, as this is required for emulation of "jackson".
+ */
+ field.set(target, value); // NOSONAR
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new JsonParseException(makeError(SET_ERR), e);
diff --git a/gson/src/main/java/org/onap/policy/common/gson/internal/FieldSerializer.java b/gson/src/main/java/org/onap/policy/common/gson/internal/FieldSerializer.java
index 1c9d8b37..348ef5a0 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/internal/FieldSerializer.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/internal/FieldSerializer.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -50,7 +50,10 @@ public class FieldSerializer extends Adapter implements Serializer {
this.field = field;
- field.setAccessible(true);
+ /*
+ * Turning off sonar, as this is required for emulation of "jackson".
+ */
+ field.setAccessible(true); // NOSONAR
}
@Override
diff --git a/gson/src/main/java/org/onap/policy/common/gson/internal/JacksonTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/internal/JacksonTypeAdapter.java
index 1171fd4d..34d61f47 100644
--- a/gson/src/main/java/org/onap/policy/common/gson/internal/JacksonTypeAdapter.java
+++ b/gson/src/main/java/org/onap/policy/common/gson/internal/JacksonTypeAdapter.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,7 +22,6 @@ package org.onap.policy.common.gson.internal;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
@@ -78,7 +77,7 @@ public class JacksonTypeAdapter<T> extends TypeAdapter<T> {
JsonElement tree = delegate.toJsonTree(value);
if (tree.isJsonObject()) {
- JsonObject jsonObj = tree.getAsJsonObject();
+ var jsonObj = tree.getAsJsonObject();
// serialize each item from the value into the target tree
for (Serializer serializer : serializers) {
@@ -92,10 +91,10 @@ public class JacksonTypeAdapter<T> extends TypeAdapter<T> {
@Override
public T read(JsonReader in) throws IOException {
JsonElement tree = elementAdapter.read(in);
- T object = delegate.fromJsonTree(tree);
+ var object = delegate.fromJsonTree(tree);
if (tree.isJsonObject()) {
- JsonObject jsonObj = tree.getAsJsonObject();
+ var jsonObj = tree.getAsJsonObject();
// deserialize each item from the tree into the target object
for (Deserializer dser : deserializers) {
diff --git a/gson/src/test/java/org/onap/policy/common/gson/DoubleConverterTest.java b/gson/src/test/java/org/onap/policy/common/gson/DoubleConverterTest.java
index c81a5cd6..f4e3a76b 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/DoubleConverterTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/DoubleConverterTest.java
@@ -59,7 +59,7 @@ public class DoubleConverterTest {
assertEquals("[list, null, 21]", list.toString());
// map
- Map<String,Object> map = new LinkedHashMap<>();
+ Map<String, Object> map = new LinkedHashMap<>();
map.put("map-A", "map-value");
map.put("map-B", null);
map.put("map-C", 22.0);
@@ -88,13 +88,13 @@ public class DoubleConverterTest {
@Test
public void testConvertFromDoubleMap() {
// null is ok
- DoubleConverter.convertFromDouble((Map<String,Object>) null);
+ DoubleConverter.convertFromDouble((Map<String, Object>) null);
- Map<String,Object> map = new LinkedHashMap<>();
+ Map<String, Object> map = new LinkedHashMap<>();
map.put("keyA", "valueA");
map.put("keyB", 200.0);
- Map<String,Object> nested = new LinkedHashMap<>();
+ Map<String, Object> nested = new LinkedHashMap<>();
map.put("keyC", nested);
nested.put("nested-key", 201.0);
diff --git a/gson/src/test/java/org/onap/policy/common/gson/GsonMessageBodyHandlerTest.java b/gson/src/test/java/org/onap/policy/common/gson/GsonMessageBodyHandlerTest.java
index f1740ac1..fc101430 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/GsonMessageBodyHandlerTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/GsonMessageBodyHandlerTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -20,15 +21,24 @@
package org.onap.policy.common.gson;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import jakarta.ws.rs.core.MediaType;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;
-import javax.ws.rs.core.MediaType;
+import java.util.UUID;
+import lombok.ToString;
import org.junit.Before;
import org.junit.Test;
@@ -160,7 +170,34 @@ public class GsonMessageBodyHandlerTest {
assertEquals(12.5, map.props.get("doubleVal"));
}
+ @Test
+ public void testInterestingFields() throws IOException {
+ InterestingFields data = new InterestingFields();
+ data.instant = Instant.ofEpochMilli(1583249713500L);
+ data.uuid = UUID.fromString("a850cb9f-3c5e-417c-abfd-0679cdcd1ab0");
+ data.localDate = LocalDateTime.of(2020, 2, 3, 4, 5, 6, 789000000);
+ data.zonedDate = ZonedDateTime.of(2020, 2, 3, 4, 5, 6, 789000000, ZoneId.of("US/Eastern"));
+
+ ByteArrayOutputStream outstr = new ByteArrayOutputStream();
+ hdlr.writeTo(data, data.getClass(), data.getClass(), null, null, null, outstr);
+
+ // ensure fields are encoded as expected
+
+ // @formatter:off
+ assertThat(outstr.toString(StandardCharsets.UTF_8))
+ .contains("\"2020-03-03T15:35:13.500Z\"")
+ .contains("\"2020-02-03T04:05:06.789\"")
+ .contains("\"2020-02-03T04:05:06.789-05:00[US/Eastern]\"")
+ .contains("a850cb9f-3c5e-417c-abfd-0679cdcd1ab0");
+ // @formatter:on
+
+ Object obj2 = hdlr.readFrom(Object.class, data.getClass(), null, null, null,
+ new ByteArrayInputStream(outstr.toByteArray()));
+ assertEquals(data.toString(), obj2.toString());
+ }
+
+ @ToString
public static class MyObject {
private int id;
@@ -171,11 +208,6 @@ public class GsonMessageBodyHandlerTest {
public MyObject(int id) {
this.id = id;
}
-
- @Override
- public String toString() {
- return "MyObject [id=" + id + "]";
- }
}
private static class MyMap {
@@ -186,4 +218,12 @@ public class GsonMessageBodyHandlerTest {
return props.toString();
}
}
+
+ @ToString
+ private static class InterestingFields {
+ private LocalDateTime localDate;
+ private Instant instant;
+ private UUID uuid;
+ private ZonedDateTime zonedDate;
+ }
}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/InstantAsMillisTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/InstantAsMillisTypeAdapterTest.java
new file mode 100644
index 00000000..c48919a7
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/InstantAsMillisTypeAdapterTest.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import java.time.Instant;
+import lombok.ToString;
+import org.junit.Test;
+
+public class InstantAsMillisTypeAdapterTest {
+ private static Gson gson =
+ new GsonBuilder().registerTypeAdapter(Instant.class, new InstantAsMillisTypeAdapter()).create();
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.instant = Instant.ofEpochMilli(1583249713500L);
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).doesNotContain("nanos").contains("1583249713500").doesNotContain("\"1583249713500\"")
+ .doesNotContain("T");
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // null output
+ data.instant = null;
+ json = gson.toJson(data);
+ data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // null input
+ data2 = gson.fromJson("{\"instant\":null}", InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+ }
+
+
+ @ToString
+ private static class InterestingFields {
+ private Instant instant;
+ }
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/InstantTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/InstantTypeAdapterTest.java
new file mode 100644
index 00000000..68f54ed8
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/InstantTypeAdapterTest.java
@@ -0,0 +1,63 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import java.time.Instant;
+import lombok.ToString;
+import org.junit.Test;
+
+public class InstantTypeAdapterTest {
+ private static Gson gson =
+ new GsonBuilder().registerTypeAdapter(Instant.class, new InstantTypeAdapter()).create();
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.instant = Instant.ofEpochMilli(1583249713500L);
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).doesNotContain("nanos").contains("\"2020-03-03T15:35:13.500Z\"")
+ .doesNotContain("1583249713500");
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // try when the date-time string is invalid
+ String json2 = json.replace("2020", "invalid-date");
+ assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
+ .hasMessageContaining("invalid date");
+ }
+
+
+ @ToString
+ private static class InterestingFields {
+ private Instant instant;
+ }
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java b/gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java
index 3ce16964..9d8d3495 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modificaitons 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.
@@ -31,6 +32,7 @@ import com.google.gson.JsonElement;
import java.lang.reflect.GenericArrayType;
import java.util.LinkedList;
import java.util.TreeMap;
+import lombok.ToString;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -80,39 +82,29 @@ public class JacksonExclusionStrategyTest {
@Test
public void testIsManaged() {
- assertTrue(JacksonExclusionStrategy.isManaged(Data.class));
- assertTrue(JacksonExclusionStrategy.isManaged(Intfc.class));
- assertTrue(JacksonExclusionStrategy.isManaged(com.google.gson.TypeAdapter.class));
-
- // generic classes
- assertFalse(JacksonExclusionStrategy.isManaged(new Data[0].getClass()));
- assertFalse(JacksonExclusionStrategy.isManaged(Enum.class));
- assertFalse(JacksonExclusionStrategy.isManaged(boolean.class));
- assertFalse(JacksonExclusionStrategy.isManaged(byte.class));
- assertFalse(JacksonExclusionStrategy.isManaged(short.class));
- assertFalse(JacksonExclusionStrategy.isManaged(int.class));
- assertFalse(JacksonExclusionStrategy.isManaged(long.class));
- assertFalse(JacksonExclusionStrategy.isManaged(float.class));
- assertFalse(JacksonExclusionStrategy.isManaged(double.class));
- assertFalse(JacksonExclusionStrategy.isManaged(char.class));
- assertFalse(JacksonExclusionStrategy.isManaged(Boolean.class));
- assertFalse(JacksonExclusionStrategy.isManaged(Byte.class));
- assertFalse(JacksonExclusionStrategy.isManaged(Short.class));
- assertFalse(JacksonExclusionStrategy.isManaged(Integer.class));
- assertFalse(JacksonExclusionStrategy.isManaged(Long.class));
- assertFalse(JacksonExclusionStrategy.isManaged(Float.class));
- assertFalse(JacksonExclusionStrategy.isManaged(Double.class));
- assertFalse(JacksonExclusionStrategy.isManaged(Character.class));
- assertFalse(JacksonExclusionStrategy.isManaged(String.class));
- assertFalse(JacksonExclusionStrategy.isManaged(MyMap.class));
- assertFalse(JacksonExclusionStrategy.isManaged(MyList.class));
- assertFalse(JacksonExclusionStrategy.isManaged(MyJson.class));
- assertFalse(JacksonExclusionStrategy.isManaged(GenericArrayType.class));
+ // these classes SHOULD be managed
+ Class<?>[] managed = {Data.class, Intfc.class, com.google.gson.TypeAdapter.class};
+
+ for (Class<?> clazz : managed) {
+ assertTrue(clazz.getName(), JacksonExclusionStrategy.isManaged(clazz));
+ }
+
+ // generic classes should NOT be managed
+ Class<?>[] unmanaged = {
+ new Data[0].getClass(), Enum.class, boolean.class, byte.class, short.class, int.class,
+ long.class, float.class, double.class, char.class, Boolean.class, Byte.class, Short.class,
+ Integer.class, Long.class, Float.class, Double.class, Character.class, String.class,
+ MyMap.class, MyList.class, MyJson.class, GenericArrayType.class};
+
+ for (Class<?> clazz : unmanaged) {
+ assertFalse(clazz.getName(), JacksonExclusionStrategy.isManaged(clazz));
+ }
}
/**
* Used to verify that no fields are exposed.
*/
+ @ToString
public static class Data {
private int id;
public String text;
@@ -132,13 +124,9 @@ public class JacksonExclusionStrategyTest {
public void setText(String text) {
this.text = text;
}
-
- @Override
- public String toString() {
- return "Data [id=" + id + ", text=" + text + "]";
- }
}
+ @ToString(callSuper = true)
public static class Derived extends Data {
protected String value;
@@ -149,11 +137,6 @@ public class JacksonExclusionStrategyTest {
public void setValue(String value) {
this.value = value;
}
-
- @Override
- public String toString() {
- return "Derived [value=" + value + ", " + super.toString() + "]";
- }
}
/**
@@ -193,6 +176,7 @@ public class JacksonExclusionStrategyTest {
/**
* Used to verify that JsonElements are not managed.
*/
+ @SuppressWarnings("deprecation")
public static class MyJson extends JsonElement {
@Override
public JsonElement deepCopy() {
diff --git a/gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java b/gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java
index bbeb1e26..dc62186b 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -31,6 +31,7 @@ import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
+import lombok.ToString;
import org.junit.Test;
import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
import org.onap.policy.common.gson.annotation.GsonJsonProperty;
@@ -137,6 +138,7 @@ public class JacksonFieldAdapterFactoryTest {
return text.replaceFirst("@\\w+", "@");
}
+ @ToString
private static class Data {
@GsonJsonProperty("my-id")
private int id;
@@ -155,21 +157,12 @@ public class JacksonFieldAdapterFactoryTest {
public void setId(int id) {
this.id = id;
}
-
- @Override
- public String toString() {
- return "Data [id=" + id + ", text=" + text + "]";
- }
}
+ @ToString(callSuper = true)
private static class Derived extends Data {
// not serialized
private String unserialized;
-
- @Override
- public String toString() {
- return "Derived [unserialized=" + unserialized + ", toString()=" + super.toString() + "]";
- }
}
private static class DataList {
diff --git a/gson/src/test/java/org/onap/policy/common/gson/JacksonHandlerTest.java b/gson/src/test/java/org/onap/policy/common/gson/JacksonHandlerTest.java
index 18a6fc73..7131817d 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/JacksonHandlerTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/JacksonHandlerTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 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.
@@ -26,13 +27,14 @@ import static org.junit.Assert.assertTrue;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
+import jakarta.ws.rs.core.MediaType;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
-import javax.ws.rs.core.MediaType;
+import lombok.ToString;
import org.junit.Test;
import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
@@ -109,6 +111,7 @@ public class JacksonHandlerTest {
/**
* This class includes all policy-specific gson annotations.
*/
+ @ToString
public static class Data {
protected int id;
@@ -147,11 +150,6 @@ public class JacksonHandlerTest {
props.put(name, value);
}
-
- @Override
- public String toString() {
- return "Data [id=" + id + ", value=" + value + ", props=" + props + "]";
- }
}
private static class MyMap {
diff --git a/gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java b/gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java
index 6377420d..7afb0e5a 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -32,6 +32,7 @@ import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import java.util.Map;
import java.util.TreeMap;
+import lombok.ToString;
import org.junit.Test;
import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
@@ -117,6 +118,7 @@ public class JacksonMethodAdapterFactoryTest {
assertEquals("{'id':500,'nested':{'value':'bye bye'}}".replace('\'', '"'), result);
}
+ @ToString
protected static class Data {
private int id;
private String text;
@@ -142,13 +144,9 @@ public class JacksonMethodAdapterFactoryTest {
public void unused(String text) {
// do nothing
}
-
- @Override
- public String toString() {
- return "Data [id=" + id + ", text=" + text + "]";
- }
}
+ @ToString(callSuper = true)
protected static class Derived extends Data {
// overrides private field from Data
@@ -174,11 +172,6 @@ public class JacksonMethodAdapterFactoryTest {
map.put(key, value);
}
-
- @Override
- public String toString() {
- return "Derived [text=" + text + ", map=" + map + ", toString()=" + super.toString() + "]";
- }
}
/**
@@ -258,6 +251,7 @@ public class JacksonMethodAdapterFactoryTest {
/**
* Used to test serialization of non-static nested classes.
*/
+ @ToString
protected static class Container {
private int id;
private Nested nested;
@@ -283,12 +277,8 @@ public class JacksonMethodAdapterFactoryTest {
return nested;
}
- @Override
- public String toString() {
- return "Container [id=" + id + ", nested=" + nested + "]";
- }
-
+ @ToString
protected class Nested {
private String value;
@@ -299,11 +289,6 @@ public class JacksonMethodAdapterFactoryTest {
public String getValue() {
return value;
}
-
- @Override
- public String toString() {
- return "Nested [value=" + value + "]";
- }
}
}
}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/LocalDateTimeTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/LocalDateTimeTypeAdapterTest.java
new file mode 100644
index 00000000..2778a4ba
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/LocalDateTimeTypeAdapterTest.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import java.time.LocalDateTime;
+import lombok.ToString;
+import org.junit.Test;
+
+public class LocalDateTimeTypeAdapterTest {
+ private static Gson gson =
+ new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter()).create();
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.date = LocalDateTime.of(2020, 2, 3, 4, 5, 6, 789000000);
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).doesNotContain("year").contains("\"2020-02-03T04:05:06.789\"");
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // try when the date-time string is invalid
+ String json2 = json.replace("2020", "invalid-date");
+ assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
+ .hasMessageContaining("invalid date");
+
+ // null output
+ data.date = null;
+ json = gson.toJson(data);
+ data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // null input
+ data2 = gson.fromJson("{\"date\":null}", InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+ }
+
+
+ @ToString
+ private static class InterestingFields {
+ private LocalDateTime date;
+ }
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/LocalDateTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/LocalDateTypeAdapterTest.java
new file mode 100644
index 00000000..17acf5e6
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/LocalDateTypeAdapterTest.java
@@ -0,0 +1,73 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import java.time.LocalDate;
+import lombok.ToString;
+import org.junit.Test;
+
+public class LocalDateTypeAdapterTest {
+ private static Gson gson =
+ new GsonBuilder().registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()).create();
+ private static final String TEST_DATE = "2020-01-01";
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.date = LocalDate.parse(TEST_DATE);
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).doesNotContain("year").contains(TEST_DATE);
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // try when the date-time string is invalid
+ String json2 = json.replace("2020", "invalid-date");
+ assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
+ .hasMessageContaining("invalid date");
+
+ // null output
+ data.date = null;
+ json = gson.toJson(data);
+ data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // null input
+ data2 = gson.fromJson("{\"date\":null}", InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+ }
+
+ @ToString
+ private static class InterestingFields {
+ private LocalDate date;
+ }
+
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/MapDoubleAdapterFactoryTest.java b/gson/src/test/java/org/onap/policy/common/gson/MapDoubleAdapterFactoryTest.java
index 79631c5c..30d99466 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/MapDoubleAdapterFactoryTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/MapDoubleAdapterFactoryTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -21,6 +21,7 @@
package org.onap.policy.common.gson;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -104,8 +105,8 @@ public class MapDoubleAdapterFactoryTest {
map = gson.fromJson(json, MyDoubleMap.class);
// everything should still be Double - check by simply accessing
- map.data.get("plainDouble");
- map.data.get("doubleAsInt");
+ assertNotNull(map.data.get("plainDouble"));
+ assertNotNull(map.data.get("doubleAsInt"));
}
@Test
diff --git a/gson/src/test/java/org/onap/policy/common/gson/OffsetDateTimeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/OffsetDateTimeAdapterTest.java
new file mode 100644
index 00000000..a0bcb1b2
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/OffsetDateTimeAdapterTest.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import java.time.OffsetDateTime;
+import lombok.ToString;
+import org.junit.Test;
+
+public class OffsetDateTimeAdapterTest {
+ private static Gson gson =
+ new GsonBuilder().registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter()).create();
+ private static final String TEST_DATE = "2020-01-01T12:00:00.999+05:00";
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.date = OffsetDateTime.parse(TEST_DATE);
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).doesNotContain("year").contains(TEST_DATE);
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // try when the date-time string is invalid
+ String json2 = json.replace("2020", "invalid-date");
+ assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
+ .hasMessageContaining("invalid date");
+
+ // null output
+ data.date = null;
+ json = gson.toJson(data);
+ data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // null input
+ data2 = gson.fromJson("{\"date\":null}", InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+ }
+
+ @ToString
+ private static class InterestingFields {
+ private OffsetDateTime date;
+ }
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/OffsetTimeTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/OffsetTimeTypeAdapterTest.java
new file mode 100644
index 00000000..8098af98
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/OffsetTimeTypeAdapterTest.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import java.time.OffsetTime;
+import lombok.ToString;
+import org.junit.Test;
+
+public class OffsetTimeTypeAdapterTest {
+ private static Gson gson =
+ new GsonBuilder().registerTypeAdapter(OffsetTime.class, new OffsetTimeTypeAdapter()).create();
+ private static final String TEST_TIME = "12:00:00.999+05:00";
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.time = OffsetTime.parse(TEST_TIME);
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).doesNotContain("foo").contains(TEST_TIME);
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // try when the date-time string is invalid
+ String json2 = json.replace("12", "invalid-time");
+ assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
+ .hasMessageContaining("invalid time");
+
+ // null output
+ data.time = null;
+ json = gson.toJson(data);
+ data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // null input
+ data2 = gson.fromJson("{\"time\":null}", InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+ }
+
+ @ToString
+ private static class InterestingFields {
+ private OffsetTime time;
+ }
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/StringTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/StringTypeAdapterTest.java
new file mode 100644
index 00000000..f35677cd
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/StringTypeAdapterTest.java
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.ToString;
+import org.junit.Test;
+
+public class StringTypeAdapterTest {
+ private static Gson gson = new GsonBuilder().registerTypeAdapter(MyData.class, new MyAdapter()).create();
+ private static final int TEST_NUM1 = 10;
+ private static final int TEST_NUM3 = 30;
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.data1 = new MyData(TEST_NUM1);
+ data.data2 = null;
+ data.data3 = new MyData(TEST_NUM3);
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).contains("10", "30");
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // try when the string is invalid
+ String json2 = json.replace("30", "invalid-value");
+ assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
+ .hasMessageContaining("invalid data");
+
+ // null output
+ data = new InterestingFields();
+ json = gson.toJson(data);
+ data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // null input
+ data2 = gson.fromJson("{\"data1\":null, \"data1\":null, \"data1\":null}", InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // empty input
+ data2 = gson.fromJson("{}", InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+ }
+
+ @Getter
+ @ToString
+ @AllArgsConstructor
+ private static class MyData {
+ private int num;
+ }
+
+ @ToString
+ private static class InterestingFields {
+ private MyData data1;
+ private MyData data2;
+ private MyData data3;
+ }
+
+ private static class MyAdapter extends StringTypeAdapter<MyData> {
+ public MyAdapter() {
+ super("data", string -> new MyData(Integer.parseInt(string)), data -> String.valueOf(data.num));
+ }
+ }
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/ZoneOffsetTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/ZoneOffsetTypeAdapterTest.java
new file mode 100644
index 00000000..d9a33169
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/ZoneOffsetTypeAdapterTest.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import java.time.ZoneOffset;
+import lombok.ToString;
+import org.junit.Test;
+
+public class ZoneOffsetTypeAdapterTest {
+ private static Gson gson =
+ new GsonBuilder().registerTypeAdapter(ZoneOffset.class, new ZoneOffsetTypeAdapter()).create();
+ private static final String TEST_ZONE = "+05:00";
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.zone = ZoneOffset.of(TEST_ZONE);
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).doesNotContain("foo").contains(TEST_ZONE);
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // try when the date-time string is invalid
+ String json2 = json.replace("05", "invalid-zone");
+ assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
+ .hasMessageContaining("invalid zone");
+
+ // null output
+ data.zone = null;
+ json = gson.toJson(data);
+ data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // null input
+ data2 = gson.fromJson("{\"zone\":null}", InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+ }
+
+ @ToString
+ private static class InterestingFields {
+ private ZoneOffset zone;
+ }
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapterTest.java
new file mode 100644
index 00000000..032533eb
--- /dev/null
+++ b/gson/src/test/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapterTest.java
@@ -0,0 +1,63 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.gson;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import lombok.ToString;
+import org.junit.Test;
+
+public class ZonedDateTimeTypeAdapterTest {
+ private static Gson gson =
+ new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeTypeAdapter()).create();
+
+ @Test
+ public void test() {
+ InterestingFields data = new InterestingFields();
+ data.date = ZonedDateTime.of(2020, 2, 3, 4, 5, 6, 789000000, ZoneId.of("US/Eastern"));
+
+ String json = gson.toJson(data);
+
+ // instant should be encoded as a number, without quotes
+ assertThat(json).doesNotContain("year").contains("\"2020-02-03T04:05:06.789-05:00[US/Eastern]\"");
+
+ InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
+ assertEquals(data.toString(), data2.toString());
+
+ // try when the date-time string is invalid
+ String json2 = json.replace("2020", "invalid-date");
+ assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
+ .hasMessageContaining("invalid date");
+ }
+
+
+ @ToString
+ private static class InterestingFields {
+ private ZonedDateTime date;
+ }
+}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java
index 9d80c860..fd999951 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 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.
@@ -42,7 +43,7 @@ import org.onap.policy.common.gson.annotation.GsonJsonProperty;
import org.onap.policy.common.gson.internal.Adapter.Factory;
import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
import org.onap.policy.common.gson.internal.DataAdapterFactory.DerivedData;
-import org.powermock.reflect.Whitebox;
+import org.springframework.test.util.ReflectionTestUtils;
public class AdapterTest {
private static final String GET_INVALID_NAME = "get$InvalidName";
@@ -83,12 +84,12 @@ public class AdapterTest {
@BeforeClass
public static void setUpBeforeClass() {
- saveFactory = Whitebox.getInternalState(Adapter.class, FACTORY_FIELD);
+ saveFactory = (Factory) ReflectionTestUtils.getField(Adapter.class, FACTORY_FIELD);
}
@After
public void tearDown() {
- Whitebox.setInternalState(Adapter.class, FACTORY_FIELD, saveFactory);
+ ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, saveFactory);
}
@Test
@@ -98,7 +99,7 @@ public class AdapterTest {
// return an invalid field name
Factory factory = mock(Factory.class);
when(factory.getName(any(Field.class))).thenReturn("$invalidFieldName");
- Whitebox.setInternalState(Adapter.class, FACTORY_FIELD, factory);
+ ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
assertFalse(Adapter.isManaged(field(VALUE_NAME)));
}
@@ -108,7 +109,7 @@ public class AdapterTest {
// return an invalid method name
Factory factory = mock(Factory.class);
- Whitebox.setInternalState(Adapter.class, FACTORY_FIELD, factory);
+ ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
when(factory.getName(any(Method.class))).thenReturn(GET_INVALID_NAME);
assertFalse(Adapter.isManaged(mget(GET_VALUE_NAME)));
@@ -240,7 +241,7 @@ public class AdapterTest {
// return an invalid field name
Factory factory = mock(Factory.class);
when(factory.getName(any(Field.class))).thenReturn("$invalidFieldName");
- Whitebox.setInternalState(Adapter.class, FACTORY_FIELD, factory);
+ ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
assertEquals(null, Adapter.detmPropName(field(VALUE_NAME)));
}
@@ -257,7 +258,7 @@ public class AdapterTest {
// return an invalid method name
Factory factory = mock(Factory.class);
- Whitebox.setInternalState(Adapter.class, FACTORY_FIELD, factory);
+ ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
when(factory.getName(any(Method.class))).thenReturn(GET_INVALID_NAME);
assertEquals(null, Adapter.detmGetterPropName(mget(GET_VALUE_NAME)));
@@ -273,7 +274,7 @@ public class AdapterTest {
// return an invalid method name
Factory factory = mock(Factory.class);
- Whitebox.setInternalState(Adapter.class, FACTORY_FIELD, factory);
+ ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
when(factory.getName(any(Method.class))).thenReturn(SET_INVALID_NAME);
assertEquals(null, Adapter.detmSetterPropName(mset(SET_VALUE_NAME)));
diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/DataAdapterFactory.java b/gson/src/test/java/org/onap/policy/common/gson/internal/DataAdapterFactory.java
index 2799d8ba..d2cdf7f8 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/internal/DataAdapterFactory.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/internal/DataAdapterFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -35,6 +35,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import lombok.ToString;
/**
* Factory used with test Data.
@@ -54,6 +55,7 @@ public class DataAdapterFactory implements TypeAdapterFactory {
/**
* Object handled by this factory.
*/
+ @ToString
public static class Data {
private int id;
@@ -72,16 +74,12 @@ public class DataAdapterFactory implements TypeAdapterFactory {
public void setId(int id) {
this.id = id;
}
-
- @Override
- public String toString() {
- return "Data [id=" + id + "]";
- }
}
/**
* Object derived from Data.
*/
+ @ToString(callSuper = true)
public static class DerivedData extends Data {
private String text;
@@ -101,11 +99,6 @@ public class DataAdapterFactory implements TypeAdapterFactory {
public void setText(String text) {
this.text = text;
}
-
- @Override
- public String toString() {
- return "DerivedData [text=" + text + ", toString()=" + super.toString() + "]";
- }
}
/**
diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java
index 509ddb79..acb241e6 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java
@@ -1,8 +1,8 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -61,18 +61,18 @@ public class FieldDeserializerTest {
// no value in tree - text remains unchanged
text = INITIAL_VALUE;
deser.getFromTree(json, this);
- assertEquals(text, INITIAL_VALUE);
+ assertEquals(INITIAL_VALUE, text);
// null value in tree - text remains unchanged
json.add(TEXT_FIELD_NAME, JsonNull.INSTANCE);
deser.getFromTree(json, this);
- assertEquals(text, INITIAL_VALUE);
+ assertEquals(INITIAL_VALUE, text);
// now assign a value - text should be changed now
json.addProperty(TEXT_FIELD_NAME, NEW_VALUE);
deser.getFromTree(json, this);
- assertEquals(text, NEW_VALUE);
+ assertEquals(NEW_VALUE, text);
/*
* check list field
diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java
index cc5ef928..156e4ef3 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -89,7 +89,9 @@ public class FieldSerializerTest {
text = "world";
- assertThatThrownBy(() -> ser.addToTree(this, new JsonObject())).isInstanceOf(JsonParseException.class)
+ JsonObject obj = new JsonObject();
+
+ assertThatThrownBy(() -> ser.addToTree(this, obj)).isInstanceOf(JsonParseException.class)
.hasMessage(FieldSerializer.GET_ERR + FieldSerializerTest.class.getName() + ".text");
}
}
diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java
index 6be4e590..5e73d06e 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -33,6 +33,7 @@ import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
+import lombok.ToString;
import org.junit.Before;
import org.junit.Test;
@@ -138,6 +139,7 @@ public class JacksonTypeAdapterTest {
assertEquals("read text", data);
}
+ @ToString
private static class Data {
private String id;
private String value;
@@ -155,11 +157,6 @@ public class JacksonTypeAdapterTest {
this.id = id;
this.value = value;
}
-
- @Override
- public String toString() {
- return "Data [id=" + id + ", value=" + value + "]";
- }
}
private abstract static class NamedSer implements Serializer {
diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/MethodAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/MethodAdapterTest.java
index 9f39e3ce..6c13865d 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/internal/MethodAdapterTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/internal/MethodAdapterTest.java
@@ -1,8 +1,8 @@
-/*
+/*--
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -26,7 +26,6 @@ import static org.junit.Assert.assertEquals;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import org.junit.Test;
-import org.onap.policy.common.gson.internal.MethodAdapter;
public class MethodAdapterTest {
private static final Gson gson = new Gson();
@@ -36,16 +35,16 @@ public class MethodAdapterTest {
@Test
public void testMethodAdapter_testInvoke() throws Exception {
MethodAdapter adapter =
- new MethodAdapter(gson, MethodAdapterTest.class.getDeclaredMethod("getValue"), String.class);
+ new MethodAdapter(gson, MethodAdapterTest.class.getDeclaredMethod("getValue"), String.class);
assertEquals("hello", adapter.invoke(this));
MethodAdapter adapter2 = new MethodAdapter(gson,
- MethodAdapterTest.class.getDeclaredMethod("setValue", String.class), String.class);
+ MethodAdapterTest.class.getDeclaredMethod("setValue", String.class), String.class);
adapter2.invoke(this, "world");
assertEquals("world", saved);
assertThatThrownBy(() -> adapter2.invoke(this, 100)).isInstanceOf(JsonParseException.class)
- .hasMessage(MethodAdapter.INVOKE_ERR + MethodAdapterTest.class.getName() + ".setValue");
+ .hasMessage(MethodAdapter.INVOKE_ERR + MethodAdapterTest.class.getName() + ".setValue");
}
public String getValue() {
diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/MethodDeserializerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/MethodDeserializerTest.java
index 338644ae..7fcfca18 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/internal/MethodDeserializerTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/internal/MethodDeserializerTest.java
@@ -1,8 +1,8 @@
-/*
+/*--
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -32,7 +32,6 @@ import java.util.List;
import org.junit.Test;
import org.onap.policy.common.gson.JacksonExclusionStrategy;
import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-import org.onap.policy.common.gson.internal.MethodDeserializer;
public class MethodDeserializerTest {
private static final String PROP_NAME = "text";
@@ -43,7 +42,7 @@ public class MethodDeserializerTest {
private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
+ .setExclusionStrategies(new JacksonExclusionStrategy()).create();
private MethodDeserializer deser;
diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/MethodSerializerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/MethodSerializerTest.java
index 586bf54d..ed240513 100644
--- a/gson/src/test/java/org/onap/policy/common/gson/internal/MethodSerializerTest.java
+++ b/gson/src/test/java/org/onap/policy/common/gson/internal/MethodSerializerTest.java
@@ -1,8 +1,8 @@
-/*
+/*--
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -31,7 +31,6 @@ import java.util.List;
import org.junit.Test;
import org.onap.policy.common.gson.JacksonExclusionStrategy;
import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-import org.onap.policy.common.gson.internal.MethodSerializer;
public class MethodSerializerTest {
private static final String PROP_NAME = "text";
@@ -40,7 +39,7 @@ public class MethodSerializerTest {
private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
+ .setExclusionStrategies(new JacksonExclusionStrategy()).create();
private MethodSerializer ser;
diff --git a/integrity-audit/pom.xml b/integrity-audit/pom.xml
index 30547f97..46215b65 100644
--- a/integrity-audit/pom.xml
+++ b/integrity-audit/pom.xml
@@ -2,7 +2,8 @@
============LICENSE_START=======================================================
ONAP Policy Engine - Common Modules
================================================================================
- Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ 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.
@@ -18,10 +19,7 @@
============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">
+<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>
@@ -32,40 +30,13 @@
<parent>
<groupId>org.onap.policy.common</groupId>
<artifactId>common-modules</artifactId>
- <version>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
<name>Integrity Audit</name>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-ext</artifactId>
- <version>1.8.0-beta4</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>javax.persistence</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>eclipselink</artifactId>
- </dependency>
- <dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>utils</artifactId>
<version>${project.version}</version>
@@ -77,93 +48,23 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>ONAP-Logging</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-ext</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ <scope>test</scope>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>onap-java-style</id>
- <goals>
- <goal>check</goal>
- </goals>
- <phase>process-sources</phase>
- <configuration>
- <!-- Use Google Java Style Guide:
- https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml
- with minor changes -->
- <configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
- <!-- <sourceDirectory> is needed so that checkstyle ignores the generated sources directory -->
- <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
- <includeResources>true</includeResources>
- <includeTestSourceDirectory>true</includeTestSourceDirectory>
- <includeTestResources>true</includeTestResources>
- <excludes>
- </excludes>
- <consoleOutput>true</consoleOutput>
- <failsOnViolation>true</failsOnViolation>
- <violationSeverity>warning</violationSeverity>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.onap.oparent</groupId>
- <artifactId>checkstyle</artifactId>
- <version>${oparent.version}</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
- </plugin>
- </plugins>
- <pluginManagement>
- <plugins>
- <!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.jacoco</groupId>
- <artifactId>
- jacoco-maven-plugin
- </artifactId>
- <versionRange>
- [0.7.1.201405082137,)
- </versionRange>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
</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
index 25335540..03fbdb57 100644
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java
+++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,7 +22,6 @@ package org.onap.policy.common.ia;
import java.util.Collections;
import java.util.Comparator;
-import java.util.Date;
import java.util.List;
import java.util.Properties;
import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
@@ -149,10 +148,12 @@ public class AuditThread extends Thread {
*/
runUntilInterrupted();
+ } catch (InterruptedException e) {
+ handleAuditLoopException(e);
+ Thread.currentThread().interrupt();
+
} catch (Exception e) {
- String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + e.getMessage();
- logger.error(MessageCodes.EXCEPTION_ERROR, e, msg);
- integrityAudit.setThreadInitialized(false);
+ handleAuditLoopException(e);
}
dbDao.destroy();
@@ -160,16 +161,24 @@ public class AuditThread extends Thread {
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 {
- boolean auditCompleted = false;
+ var auditCompleted = false;
- DbAudit dbAudit = new DbAudit(dbDao);
+ var dbAudit = new DbAudit(dbDao);
IntegrityAuditEntity entityCurrentlyDesignated;
IntegrityAuditEntity thisEntity;
integrityAudit.setThreadInitialized(true); // An exception will set it to false
- while (true) {
+ var interrupted = false;
+
+ while (!interrupted) {
try {
/*
* It may have been awhile since we last cycled through this loop, so refresh
@@ -208,16 +217,17 @@ public class AuditThread extends Thread {
if (isInterruptedException(e)) {
String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + "; Stopping.";
logger.error(MessageCodes.EXCEPTION_ERROR, e, msg);
- break;
- }
+ Thread.currentThread().interrupt();
+ interrupted = true;
- 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);
+ } 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);
+ }
}
-
}
}
@@ -345,10 +355,10 @@ public class AuditThread extends Thread {
IntegrityAuditEntity thisEntity = null;
- int designatedEntityIndex = -1;
- int entityIndex = 0;
- int priorCandidateIndex = -1;
- int subsequentCandidateIndex = -1;
+ var designatedEntityIndex = -1;
+ var entityIndex = 0;
+ var priorCandidateIndex = -1;
+ var subsequentCandidateIndex = -1;
for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) {
@@ -559,7 +569,7 @@ public class AuditThread extends Thread {
*/
List<IntegrityAuditEntity> integrityAuditEntityList =
dbDao.getIntegrityAuditEntities(this.persistenceUnit, this.nodeType);
- int listSize = integrityAuditEntityList.size();
+ var listSize = integrityAuditEntityList.size();
if (logger.isDebugEnabled()) {
logger.debug("getIntegrityAuditEntityList: Got " + listSize + " IntegrityAuditEntity records");
}
@@ -632,10 +642,10 @@ public class AuditThread extends Thread {
+ integrityAuditEntity.getLastUpdated());
}
- boolean stale = false;
+ var stale = false;
- Date currentTime = AuditorTime.getInstance().getDate();
- Date lastUpdated = integrityAuditEntity.getLastUpdated();
+ var currentTime = AuditorTime.getInstance().getDate();
+ var lastUpdated = integrityAuditEntity.getLastUpdated();
/*
* If lastUpdated is null, we assume that the audit never ran for that node.
@@ -688,8 +698,8 @@ public class AuditThread extends Thread {
long timeDifference;
- Date currentTime = AuditorTime.getInstance().getDate();
- Date lastUpdated = thisEntity.getLastUpdated();
+ var currentTime = AuditorTime.getInstance().getDate();
+ var lastUpdated = thisEntity.getLastUpdated();
long lastUpdatedTime = lastUpdated.getTime();
timeDifference = currentTime.getTime() - lastUpdatedTime;
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
index 95eecbc3..5bfedaac 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,11 +21,14 @@
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 {
/**
@@ -41,15 +44,8 @@ public class AuditorTime {
private static Supplier<CurrentTime> supplier = () -> currentTime;
/**
- * Constructor.
- */
- private AuditorTime() {
- super();
- }
-
- /**
* Get instance.
- *
+ *
* @return the CurrentTime singleton
*/
public static CurrentTime getInstance() {
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java
index 4e718a60..22ffa08e 100644
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java
+++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java
@@ -1,8 +1,9 @@
-/*
+/*--
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +21,7 @@
package org.onap.policy.common.ia;
+import jakarta.persistence.Table;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
@@ -29,7 +31,6 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
-import javax.persistence.Table;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.builder.RecursiveToStringStyle;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
@@ -60,16 +61,11 @@ public class DbAudit {
*/
public DbAudit(DbDao dbDao) {
- if (logger.isDebugEnabled()) {
- logger.debug("Constructor: Entering");
- }
+ logger.debug("Constructor: Entering");
this.dbDao = dbDao;
- if (logger.isDebugEnabled()) {
- logger.debug("Constructor: Exiting");
- }
-
+ logger.debug("Constructor: Exiting");
}
/**
@@ -128,7 +124,7 @@ public class DbAudit {
* nodes. Since the audit is run in a round-robin, every instance will be compared against
* every other instance.
*/
- IntegrityAuditEntity myIae = dbDao.getMyIntegrityAuditEntity();
+ var myIae = dbDao.getMyIntegrityAuditEntity();
if (myIae == null) {
@@ -153,8 +149,6 @@ public class DbAudit {
if (logger.isDebugEnabled()) {
logger.debug("dbAudit: Exiting");
}
-
- return; // all done
}
private void compareList(String persistenceUnit, List<IntegrityAuditEntity> iaeList, IntegrityAuditEntity myIae,
@@ -181,22 +175,8 @@ public class DbAudit {
compareMineWithTheirs(persistenceUnit, iaeList, myIae, misMatchedMap, clazzName, myEntries);
// Time check
- if ((AuditorTime.getInstance().getMillis() - startTime) >= DB_AUDIT_UPDATE_MS) {
- // update the timestamp
- dbDao.setLastUpdated();
- // reset the startTime
- startTime = AuditorTime.getInstance().getMillis();
- } else {
- // sleep a couple seconds to break up the activity
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Sleeping " + DB_AUDIT_SLEEP_MS + "ms");
- }
- sleep();
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Waking from sleep");
- }
- }
- } // end: for(String clazzName: classNameList)
+ startTime = timeCheck("First", startTime);
+ }
// check if misMatchedMap is empty
if (misMatchedMap.isEmpty()) {
@@ -204,8 +184,6 @@ public class DbAudit {
if (logger.isDebugEnabled()) {
logger.debug("dbAudit: Exiting, misMatchedMap is empty");
}
- // we are done
- return;
} else {
if (logger.isDebugEnabled()) {
logger.debug("dbAudit: Doing another comparison; misMatchedMap.size()=" + misMatchedMap.size());
@@ -246,7 +224,7 @@ public class DbAudit {
* again for all nodes later.
*/
compareMineWithTheirs(myEntries, theirEntries, clazzName, misMatchedMap);
- } // end for (IntegrityAuditEntity iae : iaeList)
+ }
}
private void compareMineWithTheirs(Map<Object, Object> myEntries, Map<Object, Object> theirEntries,
@@ -265,13 +243,32 @@ public class DbAudit {
}
}
+ 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) {
- Properties theirProperties = new Properties();
+ var theirProperties = new Properties();
theirProperties.put(IntegrityAuditProperties.DB_DRIVER, iae.getJdbcDriver());
theirProperties.put(IntegrityAuditProperties.DB_URL, iae.getJdbcUrl());
@@ -298,7 +295,7 @@ public class DbAudit {
logger.debug("dbAudit: Second comparison; traversing classNameSet, size=" + classNameSet.size());
}
- int errorCount = 0;
+ var errorCount = 0;
for (String clazzName : classNameSet) {
@@ -317,24 +314,10 @@ public class DbAudit {
errorCount += recompareMineWithTheirs(resourceName, persistenceUnit, iaeList, myIae, clazzName,
keySet, myEntries);
// Time check
- if ((AuditorTime.getInstance().getMillis() - startTime) >= DB_AUDIT_UPDATE_MS) {
- // update the timestamp
- dbDao.setLastUpdated();
- // reset the startTime
- startTime = AuditorTime.getInstance().getMillis();
- } else {
- // sleep a couple seconds to break up the activity
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Second comparison; sleeping " + DB_AUDIT_SLEEP_MS + "ms");
- }
- sleep();
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Second comparison; waking from sleep");
- }
- }
- } // end: for(String clazzName: classNameList)
+ startTime = timeCheck("Second", startTime);
+ }
- if (errorCount != 0) {
+ 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);
@@ -345,7 +328,7 @@ public class DbAudit {
IntegrityAuditEntity myIae, String clazzName, Set<Object> keySet, Map<Object, Object> myEntries)
throws IntegrityAuditException {
- int errorCount = 0;
+ var errorCount = 0;
for (IntegrityAuditEntity iae : iaeList) {
if (iae.getId() == myIae.getId()) {
if (logger.isDebugEnabled()) {
@@ -381,7 +364,7 @@ public class DbAudit {
return 0;
}
- StringBuilder keyBuilder = new StringBuilder();
+ var keyBuilder = new StringBuilder();
for (Object key : misMatchedKeySet) {
keyBuilder.append(key.toString());
keyBuilder.append(", ");
@@ -477,13 +460,17 @@ public class DbAudit {
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).toString()
+ + new ReflectionToStringBuilder(entry1, ToStringStyle.SHORT_PREFIX_STYLE)
+ "\n Entry 2 (short prefix style): " + resourceName2 + ": "
- + new ReflectionToStringBuilder(entry2, ToStringStyle.SHORT_PREFIX_STYLE).toString()
+ + (entry2 != null
+ ? new ReflectionToStringBuilder(entry2, ToStringStyle.SHORT_PREFIX_STYLE).toString()
+ : "null")
+ "\n Entry 1 (recursive style): " + resourceName1 + ": "
- + new ReflectionToStringBuilder(entry1, new RecursiveToStringStyle()).toString()
+ + new ReflectionToStringBuilder(entry1, new RecursiveToStringStyle())
+ "\n Entry 2 (recursive style): " + resourceName2 + ": "
- + new ReflectionToStringBuilder(entry2, new RecursiveToStringStyle()).toString();
+ + (entry2 != null
+ ? new ReflectionToStringBuilder(entry2, new RecursiveToStringStyle()).toString()
+ : "null");
logger.debug(msg);
} catch (ClassNotFoundException e) {
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java
index 80177b30..ad96432d 100644
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java
+++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +21,15 @@
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;
@@ -27,28 +37,15 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.function.BiConsumer;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.Persistence;
-import javax.persistence.PersistenceUnitUtil;
-import javax.persistence.Query;
-import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Root;
-import javax.persistence.metamodel.ManagedType;
-import javax.persistence.metamodel.Metamodel;
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(DbDao.class.getName());
+ private static final Logger logger = FlexLogger.getLogger();
private String resourceName;
private String persistenceUnit;
@@ -59,7 +56,7 @@ public class DbDao {
private String nodeType;
private Properties properties = null;
- private EntityManagerFactory emf;
+ private final EntityManagerFactory emf;
/*
* Supports designation serialization.
@@ -78,14 +75,14 @@ public class DbDao {
* DB SELECT String.
*/
private static final String SELECT_STRING = "Select i from IntegrityAuditEntity i "
- + "where i.resourceName=:rn and i.persistenceUnit=:pu";
+ + "where i.resourceName=:rn and i.persistenceUnit=:pu";
/**
* DbDao Constructor.
*
- * @param resourceName the resource name
+ * @param resourceName the resource name
* @param persistenceUnit the persistence unit
- * @param properties the properties
+ * @param properties the properties
* @throws IntegrityAuditException if an error occurs
*/
public DbDao(String resourceName, String persistenceUnit, Properties properties) throws IntegrityAuditException {
@@ -95,15 +92,14 @@ public class DbDao {
/**
* DbDao Constructor.
*
- * @param resourceName the resource name
+ * @param resourceName the resource name
* @param persistenceUnit the persistence unit
- * @param properties the properties
- * @param lastUpdateDate may be {@code null}
- * @param altDbUrl may be {@code null}
+ * @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 {
+ throws IntegrityAuditException {
logger.debug("DbDao contructor: enter");
validateProperties(resourceName, persistenceUnit, properties);
@@ -125,14 +121,14 @@ public class DbDao {
/**
* validateProperties will validate the properties.
*
- * @param resourceName the rseource name
+ * @param resourceName the rseource name
* @param persistenceUnit the persistence unit
- * @param properties the properties
+ * @param properties the properties
* @throws IntegrityAuditPropertiesException if an error occurs
*/
private void validateProperties(String resourceName, String persistenceUnit, Properties properties)
- throws IntegrityAuditPropertiesException {
- StringBuilder badparams = new StringBuilder();
+ throws IntegrityAuditPropertiesException {
+ var badparams = new StringBuilder();
if (IntegrityAudit.parmsAreBad(resourceName, persistenceUnit, properties, badparams)) {
String msg = "DbDao: Bad parameters: badparams" + badparams;
throw new IntegrityAuditPropertiesException(msg);
@@ -146,7 +142,7 @@ public class DbDao {
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);
+ + this.persistenceUnit + "\nproperties: " + this.properties);
}
/**
@@ -158,21 +154,9 @@ public class DbDao {
public Map<Object, Object> getAllMyEntries(String className) {
logger.debug("getAllMyEntries: Entering, className=" + className);
HashMap<Object, Object> resultMap = new HashMap<>();
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
- CriteriaBuilder 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
-
- PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
- for (Object o : objectList) {
- Object key = util.getIdentifier(o);
- resultMap.put(key, o);
- }
+ getObjectsFromCriteriaBuilder(className, emf, em, resultMap);
} catch (Exception e) {
logger.error("getAllEntries encountered exception: ", e);
}
@@ -185,14 +169,14 @@ public class DbDao {
* getAllMyEntries gets all entries for a class.
*
* @param className the name of the class
- * @param keySet the keys to get the entries for
+ * @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<>();
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
Class<?> clazz = Class.forName(className);
for (Object key : keySet) {
@@ -209,11 +193,11 @@ public class DbDao {
}
/**
- * getAllEntries gets all entriesfor a particular persistence unit adn className.
+ * 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
+ * @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) {
@@ -221,21 +205,11 @@ public class DbDao {
logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n className=" + className);
HashMap<Object, Object> resultMap = new HashMap<>();
- EntityManagerFactory theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
- EntityManager em = theEmf.createEntityManager();
+ var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
+ var em = theEmf.createEntityManager();
+
try {
- CriteriaBuilder 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();
-
- PersistenceUnitUtil util = theEmf.getPersistenceUnitUtil();
- for (Object o : objectList) {
- Object key = util.getIdentifier(o);
- resultMap.put(key, o);
- }
+ getObjectsFromCriteriaBuilder(className, theEmf, em, resultMap);
} catch (Exception e) {
logger.error("getAllEntries encountered exception:", e);
}
@@ -252,18 +226,18 @@ public class DbDao {
* 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
+ * @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) {
+ Set<Object> keySet) {
logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n properties= " + properties
- + ",\n className=" + className + ",\n keySet= " + keySet);
- EntityManagerFactory theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
- EntityManager em = theEmf.createEntityManager();
+ + ",\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);
@@ -286,34 +260,35 @@ public class DbDao {
* unit and node type.
*
* @param persistenceUnit the persistence unit
- * @param nodeType the node type
+ * @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 {
+ throws DbDaoTransactionException {
logger.debug("getIntegrityAuditEntities: Entering, persistenceUnit=" + persistenceUnit + ",\n nodeType= "
- + nodeType);
+ + nodeType);
try {
- EntityManager em = emf.createEntityManager();
- // Start a transaction
- EntityTransaction et = em.getTransaction();
+ List<IntegrityAuditEntity> iaeList;
+ try (var em = emf.createEntityManager()) {
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
- et.begin();
+ et.begin();
- // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
- // found, create a new entry
- Query iaequery = em
+ // 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);
+ iaequery.setParameter("pu", persistenceUnit);
+ iaequery.setParameter("nt", nodeType);
- List<IntegrityAuditEntity> iaeList = iaequery.getResultList();
+ iaeList = iaequery.getResultList();
- // commit transaction
- et.commit();
- em.close();
+ // commit transaction
+ et.commit();
+ }
logger.debug("getIntegrityAuditEntities: Exit, iaeList=" + iaeList);
return iaeList;
} catch (Exception e) {
@@ -332,17 +307,17 @@ public class DbDao {
*/
public IntegrityAuditEntity getMyIntegrityAuditEntity() throws DbDaoTransactionException {
- return updateIae("getMyIntegrityAuditEntity", this.resourceName, this.persistenceUnit, (em,iae) -> {
+ 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");
+ + " 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);
+ + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit);
}
});
}
@@ -357,17 +332,18 @@ public class DbDao {
*/
public IntegrityAuditEntity getIntegrityAuditEntity(long id) throws DbDaoTransactionException {
try {
- EntityManager em = emf.createEntityManager();
+ IntegrityAuditEntity iae;
+ try (var em = emf.createEntityManager()) {
- // Start a transaction
- EntityTransaction et = em.getTransaction();
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
- et.begin();
+ et.begin();
- IntegrityAuditEntity iae = em.find(IntegrityAuditEntity.class, id);
+ iae = em.find(IntegrityAuditEntity.class, id);
- et.commit();
- em.close();
+ et.commit();
+ }
return iae;
} catch (Exception e) {
@@ -385,7 +361,7 @@ public class DbDao {
public Set<String> getPersistenceClassNames() {
logger.debug("DbDao: getPersistenceClassNames() entry");
HashSet<String> returnList = new HashSet<>();
- final Metamodel mm = emf.getMetamodel();
+ final var mm = emf.getMetamodel();
logger.debug("\n" + persistenceUnit + " persistence unit classes:");
for (final ManagedType<?> managedType : mm.getManagedTypes()) {
Class<?> clazz = managedType.getJavaType();
@@ -400,11 +376,11 @@ public class DbDao {
* Register the IntegrityAudit instance.
*
* @param altDbUrl alternate DB URL to be placed into the record, or {@code null} to use the
- * default
+ * default
*/
private void register(String altDbUrl) throws DbDaoTransactionException {
- updateIae("register", this.resourceName, this.persistenceUnit, (em,iae) -> {
+ 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
@@ -412,12 +388,12 @@ public class DbDao {
// 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");
+ + " 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");
+ + " to IntegrityAuditEntity table");
iae2 = new IntegrityAuditEntity();
iae2.setResourceName(this.resourceName);
iae2.setPersistenceUnit(this.persistenceUnit);
@@ -450,23 +426,23 @@ public class DbDao {
/**
* Set designated.
*
- * @param resourceName the resource name
+ * @param resourceName the resource name
* @param persistenceUnit the persistence unit
- * @param desig true if is designated
+ * @param desig true if is designated
* @throws DbDaoTransactionException if an error occurs
*/
public void setDesignated(String resourceName, String persistenceUnit, boolean desig)
- throws DbDaoTransactionException {
+ throws DbDaoTransactionException {
logger.debug("setDesignated: enter, resourceName: " + resourceName + ", persistenceUnit: " + persistenceUnit
- + ", designated: " + desig);
+ + ", designated: " + desig);
- updateIae("setDesignated", resourceName, persistenceUnit, (em,iae) -> {
+ 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");
+ + " exists and designated be updated");
iae.setDesignated(desig);
em.persist(iae);
@@ -475,7 +451,7 @@ public class DbDao {
} 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);
+ + " resource " + resourceName + WITH_PERSISTENCE_MESSAGE + persistenceUnit);
}
});
@@ -484,50 +460,49 @@ public class DbDao {
/**
* 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 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
+ * @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 {
+ BiConsumer<EntityManager, IntegrityAuditEntity> updater)
+ throws DbDaoTransactionException {
try {
- EntityManager em = emf.createEntityManager();
+ IntegrityAuditEntity iae;
+ try (var em = emf.createEntityManager()) {
- // Start a transaction
- EntityTransaction et = em.getTransaction();
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
- et.begin();
+ et.begin();
- // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
- // found, create a new entry
- Query iaequery = em.createQuery(SELECT_STRING);
- iaequery.setParameter("rn", resourceName);
- iaequery.setParameter("pu", persistenceUnit);
+ // 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);
- @SuppressWarnings("rawtypes")
- List iaeList = iaequery.getResultList();
- IntegrityAuditEntity iae;
+ List<IntegrityAuditEntity> iaeList = iaequery.getResultList();
- if (!iaeList.isEmpty()) {
- // ignores multiple results
- iae = (IntegrityAuditEntity) iaeList.get(0);
+ if (!iaeList.isEmpty()) {
+ // ignores multiple results
+ iae = iaeList.get(0);
- } else {
- // If it does not exist
- iae = null;
- }
+ } else {
+ // If it does not exist
+ iae = null;
+ }
- updater.accept(em, iae);
+ updater.accept(em, iae);
- // close the transaction
- et.commit();
- // close the EntityManager
- em.close();
+ // close the transaction
+ et.commit();
+ }
return iae;
@@ -546,15 +521,15 @@ public class DbDao {
*/
public void setLastUpdated() throws DbDaoTransactionException {
logger.debug("setLastUpdated: enter, resourceName: " + this.resourceName + ", persistenceUnit: "
- + this.persistenceUnit);
+ + this.persistenceUnit);
- updateIae("setLastUpdated", this.resourceName, this.persistenceUnit, (em,iae) -> {
+ 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");
+ + " exists and lastUpdated be updated");
iae.setLastUpdated(AuditorTime.getInstance().getDate());
em.persist(iae);
@@ -563,7 +538,7 @@ public class DbDao {
} 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);
+ + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit);
}
});
}
@@ -578,26 +553,27 @@ public class DbDao {
if (!IntegrityAudit.isUnitTesting()) {
String msg = DBDAO_MESSAGE + "deleteAllIntegrityAuditEntities() "
- + "should only be invoked during JUnit testing";
+ + "should only be invoked during JUnit testing";
logger.error(msg);
throw new DbDaoTransactionException(msg);
}
- EntityManager em = emf.createEntityManager();
- // Start a transaction
- EntityTransaction et = em.getTransaction();
+ int returnCode;
+ try (var em = emf.createEntityManager()) {
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
- et.begin();
+ et.begin();
- // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
- // found, create a new entry
- Query iaequery = em.createQuery("Delete from IntegrityAuditEntity");
+ // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
+ // found, create a new entry
+ var iaequery = em.createQuery("Delete from IntegrityAuditEntity");
- int returnCode = iaequery.executeUpdate();
+ returnCode = iaequery.executeUpdate();
- // commit transaction
- et.commit();
- em.close();
+ // commit transaction
+ et.commit();
+ }
logger.info("deleteAllIntegrityAuditEntities: returnCode=" + returnCode);
@@ -623,69 +599,65 @@ public class DbDao {
* designations from interleaved changeDesignated() invocations from different resources
* (entities), because it prevents "dirty" and "non-repeatable" reads.
*
- * <p>See http://www.objectdb.com/api/java/jpa/LockModeType
+ * <p>See www.objectdb.com/api/java/jpa/LockModeType
*
* <p>and
*
- * <p>http://stackoverflow.com/questions/2120248/how-to-synchronize-a-static-
+ * <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 {
+ throws DbDaoTransactionException {
if (logger.isDebugEnabled()) {
logger.debug("changeDesignated: Entering, resourceName=" + resourceName + ", persistenceUnit="
- + persistenceUnit + ", nodeType=" + nodeType);
+ + persistenceUnit + ", nodeType=" + nodeType);
}
long startTime = AuditorTime.getInstance().getMillis();
synchronized (lock) {
-
- EntityManager em = null;
- try {
-
- em = emf.createEntityManager();
- em.getTransaction().begin();
-
- /*
- * Define query
- */
- Query query = em.createQuery(
+ 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) {
- if (em != null) {
- em.getTransaction().rollback();
-
- String msg = "DbDao: changeDesignated() caught Exception, message=" + e.getMessage();
- logger.error(msg + e);
- throw new DbDaoTransactionException(msg, e);
- } else {
- String msg = "DbDao: changeDesignated() caught Exception, message="
+ 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(msg + e);
- throw new DbDaoTransactionException(msg, e);
+ }
+ logger.error(errorMsg + e);
+ throw new DbDaoTransactionException(errorMsg, e);
}
}
@@ -693,32 +665,58 @@ public class DbDao {
if (logger.isDebugEnabled()) {
logger.debug("changeDesignated: Exiting; time expended="
- + (AuditorTime.getInstance().getMillis() - startTime) + "ms");
+ + (AuditorTime.getInstance().getMillis() - startTime) + "ms");
}
}
private void setDesignatedEntity(String resourceName, Query query) {
for (Object o : query.getResultList()) {
- if (!(o instanceof IntegrityAuditEntity)) {
+ if (!(o instanceof IntegrityAuditEntity integrityAuditEntity)) {
continue;
}
- IntegrityAuditEntity integrityAuditEntity = (IntegrityAuditEntity) o;
if (integrityAuditEntity.getResourceName().equals(resourceName)) {
if (logger.isDebugEnabled()) {
logger.debug("changeDesignated: Designating resourceName="
- + integrityAuditEntity.getResourceName());
+ + integrityAuditEntity.getResourceName());
}
integrityAuditEntity.setDesignated(true);
} else {
if (logger.isDebugEnabled()) {
logger.debug("changeDesignated: Removing designation from resourceName="
- + integrityAuditEntity.getResourceName());
+ + 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/IntegrityAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java
index 41aea118..66ab307c 100644
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java
+++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,6 +21,8 @@
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;
@@ -34,8 +36,12 @@ public class IntegrityAudit {
private static final Logger logger = FlexLogger.getLogger(IntegrityAudit.class);
- private static boolean isUnitTesting;
- private boolean isThreadInitialized = false;
+ @Getter
+ @Setter
+ private static boolean unitTesting;
+
+ @Getter
+ private boolean threadInitialized = false;
AuditThread auditThread = null;
@@ -54,6 +60,7 @@ public class IntegrityAudit {
* indicated period
*
*/
+ @Getter
private int integrityAuditPeriodSeconds;
/**
@@ -68,7 +75,7 @@ public class IntegrityAudit {
throws IntegrityAuditException {
logger.info("Constructor: Entering and checking for nulls");
- StringBuilder parmList = new StringBuilder();
+ 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);
@@ -94,13 +101,6 @@ public class IntegrityAudit {
}
/**
- * Used during JUnit testing by AuditPeriodTest.java
- */
- public int getIntegrityAuditPeriodSeconds() {
- return integrityAuditPeriodSeconds;
- }
-
- /**
* Determine if the nodeType conforms to the required node types.
*/
public static boolean isNodeTypeEnum(String nt) {
@@ -237,21 +237,9 @@ public class IntegrityAudit {
logger.info("stopAuditThread: Exiting");
}
- public boolean isThreadInitialized() {
- return isThreadInitialized;
- }
-
public void setThreadInitialized(boolean isThreadInitialized) {
logger.info("setThreadInitialized: Setting isThreadInitialized=" + isThreadInitialized);
- this.isThreadInitialized = isThreadInitialized;
- }
-
- public static boolean isUnitTesting() {
- return isUnitTesting;
- }
-
- public static void setUnitTesting(boolean isUnitTesting) {
- IntegrityAudit.isUnitTesting = isUnitTesting;
+ this.threadInitialized = isThreadInitialized;
}
/**
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java
index 365afd25..cd80f56f 100644
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java
+++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,14 +21,18 @@
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 = "javax.persistence.jdbc.driver";
- public static final String DB_URL = "javax.persistence.jdbc.url";
- public static final String DB_USER = "javax.persistence.jdbc.user";
- public static final String DB_PWD = "javax.persistence.jdbc.password"; //NOSONAR
+ 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";
@@ -38,9 +43,4 @@ public class IntegrityAuditProperties {
PDP_XACML, PDP_DROOLS, PAP, PAP_ADMIN, LOGPARSER, BRMS_GATEWAY, ASTRA_GATEWAY, ELK_SERVER, PYPDP
}
-
- private IntegrityAuditProperties() {
-
- }
-
}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java
index c1046828..64ec7fd0 100644
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java
+++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,41 +21,48 @@
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 javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.NamedQueries;
-import javax.persistence.NamedQuery;
-import javax.persistence.PrePersist;
-import javax.persistence.PreUpdate;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
-/*
- * The Entity class to for management of IntegrityAudits
- */
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
import org.onap.policy.common.ia.AuditorTime;
@Entity
@Table(name = "IntegrityAuditEntity")
-@NamedQueries({@NamedQuery(name = " IntegrityAuditEntity.findAll", query = "SELECT e FROM IntegrityAuditEntity e "),
- @NamedQuery(name = "IntegrityAuditEntity.deleteAll", query = "DELETE FROM IntegrityAuditEntity WHERE 1=1")})
-
+@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;
- private static boolean isUnitTesting;
+ @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)
@@ -92,17 +100,12 @@ public class IntegrityAuditEntity implements Serializable {
@Column(name = "lastUpdated")
private Date lastUpdated;
-
- public IntegrityAuditEntity() {
- // Empty constructor
- }
-
/**
* Pre persist.
*/
@PrePersist
public void prePersist() {
- Date date = AuditorTime.getInstance().getDate();
+ var date = AuditorTime.getInstance().getDate();
this.createdDate = date;
this.lastUpdated = date;
}
@@ -112,106 +115,6 @@ public class IntegrityAuditEntity implements Serializable {
this.lastUpdated = AuditorTime.getInstance().getDate();
}
- public long getId() {
- return id;
- }
-
- public String getPersistenceUnit() {
- return persistenceUnit;
- }
-
- public void setPersistenceUnit(String persistenceUnit) {
- this.persistenceUnit = persistenceUnit;
- }
-
- public String getSite() {
- return site;
- }
-
- public void setSite(String site) {
- this.site = site;
- }
-
- public String getNodeType() {
- return nodeType;
- }
-
- public void setNodeType(String nodeType) {
- this.nodeType = nodeType;
- }
-
- public String getResourceName() {
- return resourceName;
- }
-
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
-
- public boolean isDesignated() {
- return designated;
- }
-
- public void setDesignated(boolean designated) {
- this.designated = designated;
- }
-
- public String getJdbcDriver() {
- return jdbcDriver;
- }
-
- public void setJdbcDriver(String jdbcDriver) {
- this.jdbcDriver = jdbcDriver;
- }
-
- public String getJdbcUrl() {
- return jdbcUrl;
- }
-
- public void setJdbcUrl(String jdbcUrl) {
- this.jdbcUrl = jdbcUrl;
- }
-
- public String getJdbcUser() {
- return jdbcUser;
- }
-
- public void setJdbcUser(String jdbcUser) {
- this.jdbcUser = jdbcUser;
- }
-
- public String getJdbcPassword() {
- return jdbcPassword;
- }
-
- public void setJdbcPassword(String jdbcPassword) {
- this.jdbcPassword = jdbcPassword;
- }
-
- public Date getLastUpdated() {
- return lastUpdated;
- }
-
- public void setLastUpdated(Date lastUpdated) {
- this.lastUpdated = lastUpdated;
- }
-
- public Date getCreatedDate() {
- return createdDate;
- }
-
- public void setCreatedDate(Date created) {
- this.createdDate = created;
- }
-
- public static boolean isUnitTesting() {
- return isUnitTesting;
- }
-
- public static void setUnitTesting(boolean isUnitTesting) {
- IntegrityAuditEntity.isUnitTesting = isUnitTesting;
- }
-
private void writeObject(ObjectOutputStream out) throws IOException {
if (isUnitTesting()) {
/*
diff --git a/integrity-audit/src/main/resources/META-INF/persistence.xml b/integrity-audit/src/main/resources/META-INF/persistence.xml
index 33c701b1..63fea7b1 100644
--- a/integrity-audit/src/main/resources/META-INF/persistence.xml
+++ b/integrity-audit/src/main/resources/META-INF/persistence.xml
@@ -4,13 +4,14 @@
Integrity Audit
================================================================================
Copyright (C) 2017 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.
@@ -19,28 +20,28 @@
============LICENSE_END=========================================================
-->
-<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
- <persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
- <!-- Limited use for generating the DB and schema files for iatest DB -
- uses eclipselink -->
- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
- <class>org.onap.policy.common.ia.jpa.IntegrityAuditEntity</class>
- <class>org.onap.policy.common.ia.jpa.IaTestEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <property name="javax.persistence.schema-generation.database.action"
- value="drop-and-create" />
- </properties>
- </persistence-unit>
+<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_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.eclipse.persistence.jpa.PersistenceProvider</provider>
- <class>org.onap.policy.common.ia.jpa.IntegrityAuditEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <!-- none -->
- </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/logback.xml b/integrity-audit/src/main/resources/logback.xml
deleted file mode 100644
index 040309b9..00000000
--- a/integrity-audit/src/main/resources/logback.xml
+++ /dev/null
@@ -1,256 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- Integrity Audit
- ================================================================================
- 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=========================================================
- -->
-
-<configuration
- scan="true"
- scanPeriod="3 seconds"
- debug="true">
- <!--<jmxConfigurator /> -->
- <!-- directory path for all other type logs -->
- <property
- name="logDir"
- value="${POLICY_LOGS}" />
-
- <!-- directory path for debugging type logs -->
- <property
- name="debugDir"
- value="${POLICY_LOGS}" />
-
- <!-- 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="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.rolling.RollingFileAppender">
- <file>${logDirectory}/${auditLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <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.rolling.RollingFileAppender">
- <file>${logDirectory}/${metricsLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <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.rolling.RollingFileAppender">
- <file>${logDirectory}/${errorLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>ERROR</level>
- </filter>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <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.rolling.RollingFileAppender">
- <file>${debugLogDirectory}/${debugLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>INFO</level>
- </filter>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
- <appender
- name="asyncEELFDebug"
- class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFDebug" />
- <includeCallerData>true</includeCallerData>
- </appender>
-
-
- <!-- ============================================================================ -->
- <!-- EELF loggers -->
- <!-- ============================================================================ -->
-
- <logger
- name="com.att.eelf.audit"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFAudit" />
- </logger>
-
- <logger
- name="com.att.eelf.metrics"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFMetrics" />
- </logger>
-
- <logger
- name="com.att.eelf.error"
- level="error"
- additivity="false">
- <appender-ref ref="asyncEELFError" />
- </logger>
-
- <logger
- name="com.att.eelf.debug"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFDebug" />
- </logger>
-
-
- <!-- <root level="INFO"> -->
- <root level="INFO">
- <appender-ref ref="asyncEELFDebug" />
- <appender-ref ref="asyncEELFError" />
- </root>
-
-</configuration>
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
index 99cf4b2a..ad154d33 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -30,12 +30,10 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
-
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
-import org.junit.Ignore;
import org.junit.Test;
import org.onap.policy.common.ia.jpa.IaTestEntity;
import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
@@ -419,7 +417,6 @@ public class DbAuditCompareEntriesTest extends IntegrityAuditTestBase {
/*
* Tests that comparison algorithm works for each entity in the database
*/
- @Ignore
@Test
public void testCompareAllDbEntities() throws Exception {
logger.info("testCompareAllDbEntities: Entering");
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
index 220b0635..c48ec0e3 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -24,13 +25,12 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.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 javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
-
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -53,6 +53,7 @@ public 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;
@@ -240,7 +241,7 @@ public class DbAuditTest extends IntegrityAuditTestBase {
assertFalse(dbglog.getExtracted().isEmpty());
String mismatchIndex = dbglog.getExtracted().get(dbglog.getExtracted().size() - 1);
- int mismatchEntries = mismatchIndex.trim().split(",").length;
+ int mismatchEntries = COMMA_PAT.split(mismatchIndex.trim()).length;
logger.info("mismatchTest: mismatchIndex found: '" + mismatchIndex + "'" + " mismatachEntries = "
+ mismatchEntries);
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
index ef21e831..9f2103d7 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -25,26 +26,18 @@ import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-/*
- * All JUnits are designed to run in the local development environment
- * where they have write privileges and can execute time-sensitive
- * tasks.
- */
-
+import 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 javax.persistence.PersistenceUnitUtil;
-import javax.persistence.Query;
-import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Root;
-
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -65,7 +58,7 @@ public class DbDaoTest extends IntegrityAuditTestBase {
private static final String SITE_B = "SiteB";
private static final String ENTITY_CLASS_NAME = "org.onap.policy.common.ia.jpa.IntegrityAuditEntity";
- private static String resourceName = "pdp0";
+ private static final String resourceName = "pdp0";
private DbDao dbDao;
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
index 959a4e7c..5944443e 100644
--- 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
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 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.
@@ -24,7 +25,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
-
import org.junit.AfterClass;
import org.junit.Test;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -95,7 +95,7 @@ public class DefaultLoggingPatternTest {
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);
+ .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/IntegrityAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java
index c9ff6854..9550017e 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,10 +21,10 @@
package org.onap.policy.common.ia;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.util.Properties;
-
import org.junit.Test;
public class IntegrityAuditTest {
@@ -41,7 +41,7 @@ public class IntegrityAuditTest {
StringBuilder badParams = new StringBuilder();
IntegrityAudit.parmsAreBad(null, SOMETHING, null, badParams);
- assertFalse("".equals(badParams.toString()));
+ assertNotEquals("", badParams.toString());
assertTrue(badParams.toString().contains(RESOURCE_NAME));
assertTrue(badParams.toString().contains(PROPERTIES));
@@ -51,14 +51,14 @@ public class IntegrityAuditTest {
props.put(IntegrityAuditProperties.DB_DRIVER, "test_db_driver");
IntegrityAudit.parmsAreBad(null, SOMETHING, props, badParams);
- assertFalse("".equals(badParams.toString()));
+ 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);
- assertFalse("".equals(badParams.toString()));
+ assertNotEquals("", badParams.toString());
assertFalse(badParams.toString().contains(RESOURCE_NAME));
assertFalse(badParams.toString().contains(PROPERTIES));
@@ -66,7 +66,7 @@ public class IntegrityAuditTest {
props.put(IntegrityAuditProperties.NODE_TYPE, "bogus");
badParams = new StringBuilder();
IntegrityAudit.parmsAreBad("someting", SOMETHING, props, badParams);
- assertFalse("".equals(badParams.toString()));
+ 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
index 1866bba0..f5a32777 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 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.
@@ -25,6 +26,10 @@ import static org.junit.Assert.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;
@@ -36,18 +41,14 @@ import java.util.Properties;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.Persistence;
import org.onap.policy.common.utils.jpa.EntityMgrCloser;
import org.onap.policy.common.utils.jpa.EntityMgrFactoryCloser;
import org.onap.policy.common.utils.jpa.EntityTransCloser;
import org.onap.policy.common.utils.test.log.logback.ExtractAppender;
import org.onap.policy.common.utils.time.CurrentTime;
import org.onap.policy.common.utils.time.TestTime;
-import org.powermock.reflect.Whitebox;
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
@@ -177,6 +178,7 @@ public class IntegrityAuditTestBase {
* @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
@@ -188,7 +190,7 @@ public class IntegrityAuditTestBase {
IntegrityAuditTestBase.dbUrl = dbUrl;
// save data that we have to restore at the end of the test
- savedTime = Whitebox.getInternalState(AuditorTime.class, TIME_SUPPLY_FIELD);
+ savedTime = (Supplier<CurrentTime>) ReflectionTestUtils.getField(AuditorTime.class, TIME_SUPPLY_FIELD);
savedDebugLevel = debugLogger.getLevel();
savedErrorLevel = errorLogger.getLevel();
@@ -208,7 +210,7 @@ public class IntegrityAuditTestBase {
// done
em = emf.createEntityManager();
- Whitebox.setInternalState(AuditorTime.class, TIME_SUPPLY_FIELD, timeSupplier);
+ ReflectionTestUtils.setField(AuditorTime.class, TIME_SUPPLY_FIELD, timeSupplier);
debugLogger.setLevel(Level.DEBUG);
errorLogger.setLevel(Level.ERROR);
}
@@ -220,7 +222,7 @@ public class IntegrityAuditTestBase {
IntegrityAudit.setUnitTesting(false);
- Whitebox.setInternalState(AuditorTime.class, TIME_SUPPLY_FIELD, savedTime);
+ ReflectionTestUtils.setField(AuditorTime.class, TIME_SUPPLY_FIELD, savedTime);
debugLogger.setLevel(savedDebugLevel);
errorLogger.setLevel(savedErrorLevel);
@@ -243,7 +245,7 @@ public class IntegrityAuditTestBase {
// Clean up the DB
try (EntityTransCloser etc = new EntityTransCloser(em.getTransaction())) {
- EntityTransaction et = etc.getTransation();
+ EntityTransaction et = etc.getTransaction();
em.createQuery("Delete from IntegrityAuditEntity").executeUpdate();
@@ -290,7 +292,7 @@ public class IntegrityAuditTestBase {
EntityTransCloser etc = new EntityTransCloser(emc.getManager().getTransaction())) {
EntityManager entmgr = emc.getManager();
- EntityTransaction entrans = etc.getTransation();
+ EntityTransaction entrans = etc.getTransaction();
// Clean up the DB
entmgr.createQuery("Delete from " + tableName).executeUpdate();
@@ -304,8 +306,7 @@ public class IntegrityAuditTestBase {
* Verifies that items appear within the log, in order. A given item may appear more than once.
* In addition, the log may contain extra items; those are ignored.
*
- * @param textre regular expression used to extract an item from a line in the log. The first
- * "capture" group of the regular expression is assumed to contain the extracted item
+ * @param 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
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
index 4a4824c5..8a34909a 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,26 +21,25 @@
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;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.NamedQueries;
-import javax.persistence.NamedQuery;
-import javax.persistence.PrePersist;
-import javax.persistence.PreUpdate;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
-
@Entity
@Table(name = "IaTestEntity")
@NamedQueries({@NamedQuery(name = " IaTestEntity.findAll", query = "SELECT e FROM IaTestEntity e "),
- @NamedQuery(name = "IaTestEntity.deleteAll", query = "DELETE FROM IaTestEntity WHERE 1=1")})
+ @NamedQuery(name = "IaTestEntity.deleteAll", query = "DELETE FROM IaTestEntity WHERE 1=1")})
public class IaTestEntity implements Serializable {
private static final long serialVersionUID = 1L;
diff --git a/integrity-audit/src/test/resources/logback.xml b/integrity-audit/src/test/resources/logback.xml
deleted file mode 100644
index 8f493cff..00000000
--- a/integrity-audit/src/test/resources/logback.xml
+++ /dev/null
@@ -1,262 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- Integrity Audit
- ================================================================================
- 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
- scan="true"
- scanPeriod="3 seconds"
- 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.rolling.RollingFileAppender">
- <file>${logDirectory}/${auditLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <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.rolling.RollingFileAppender">
- <file>${logDirectory}/${metricsLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <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.rolling.RollingFileAppender">
- <file>${logDirectory}/${errorLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>ERROR</level>
- </filter>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <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.rolling.RollingFileAppender">
- <file>${debugLogDirectory}/${debugLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>DEBUG</level>
- </filter>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
- <appender
- name="asyncEELFDebug"
- class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFDebug" />
- <includeCallerData>true</includeCallerData>
- </appender>
-
-
- <!-- ============================================================================ -->
- <!-- EELF loggers -->
- <!-- ============================================================================ -->
-
- <logger
- name="com.att.eelf.audit"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFAudit" />
- </logger>
-
- <logger
- name="com.att.eelf.metrics"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFMetrics" />
- </logger>
-
- <logger
- name="com.att.eelf.error"
- level="error"
- additivity="false">
- <appender-ref ref="asyncEELFError" />
- </logger>
-
- <!-- <logger name="com.att.eelf.debug" level="info" additivity="false"> -->
- <logger
- name="com.att.eelf.debug"
- level="debug"
- additivity="false">
- <appender-ref ref="asyncEELFDebug" />
- </logger>
-
-
- <!-- <root level="INFO"> -->
- <root level="DEBUG">
- <appender-ref ref="asyncEELFDebug" />
- <appender-ref ref="asyncEELFError" />
- </root>
-
-</configuration>
diff --git a/integrity-monitor/pom.xml b/integrity-monitor/pom.xml
index 5d718053..3e5ff3a3 100644
--- a/integrity-monitor/pom.xml
+++ b/integrity-monitor/pom.xml
@@ -2,7 +2,8 @@
============LICENSE_START=======================================================
ONAP Policy Engine - Common Modules
================================================================================
- Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ 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.
@@ -30,44 +31,13 @@
<parent>
<groupId>org.onap.policy.common</groupId>
<artifactId>common-modules</artifactId>
- <version>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
<name>Integrity Monitor</name>
<dependencies>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito2</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>javax.persistence</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>eclipselink</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>utils</artifactId>
<version>${project.version}</version>
@@ -79,11 +49,6 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>ONAP-Logging</artifactId>
<version>${project.version}</version>
@@ -91,45 +56,12 @@
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
- <version>1.1.3</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
-
- <build>
- <pluginManagement>
- <plugins>
- <!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.jacoco</groupId>
- <artifactId>
- jacoco-maven-plugin
- </artifactId>
- <versionRange>
- [0.7.1.201405082137,)
- </versionRange>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
</project>
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
index 717ae7a3..7031c50a 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +21,14 @@
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;
@@ -31,16 +40,13 @@ 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 javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.FlushModeType;
-import javax.persistence.LockModeType;
-import javax.persistence.Persistence;
-import javax.persistence.Query;
+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;
@@ -59,6 +65,9 @@ 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;
@@ -69,8 +78,8 @@ public class IntegrityMonitor {
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 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";
@@ -83,26 +92,27 @@ public class IntegrityMonitor {
boolean alarmExists = false;
/*
- * Error message that is written by the dependencyCheck() method. It is made available
- * externally through the evaluateSanity() method.
+ * 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 EntityManagerFactory emf;
- private EntityManager em;
+ 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 volatile Thread fpManager = null;
+ private AtomicReference<Thread> fpManager = new AtomicReference<>();
// The forward progress counter is incremented as the
// process being monitored makes forward progress
@@ -148,14 +158,16 @@ public class IntegrityMonitor {
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);
+ 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;
- private static boolean isUnitTesting = false;
+ @Getter
+ @Setter
+ private static boolean unitTesting = false;
// can turn on health checking of dependents via jmx test() call by setting
// this property to true
@@ -191,30 +203,31 @@ public class IntegrityMonitor {
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 sub-class. A class can extend the IntegrityMonitor class if there is a need to override any of the
+ * 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
+ * @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
- // sub-class
+ // subclass
if (instance != null) {
- String msg = "IM object exists and only one instance allowed";
+ var msg = "IM object exists and only one instance allowed";
logger.error("{}", msg);
throw new IntegrityMonitorException("IntegrityMonitor constructor exception: " + msg);
}
- instance = this;
- IntegrityMonitor.resourceName = resourceName;
+ setInstance(this, resourceName);
/*
* Validate that the properties file contains all the needed properties. Throws an
@@ -229,14 +242,6 @@ public class IntegrityMonitor {
// Create the entity manager factory
//
emf = Persistence.createEntityManagerFactory(getPersistenceUnit(), properties);
- //
- // Did it get created?
- //
- if (emf == null) {
- logger.error("Error creating IM entity manager factory with persistence unit: {}",
- getPersistenceUnit());
- throw new IntegrityMonitorException("Unable to create IM Entity Manager Factory");
- }
// add entry to forward progress and resource registration tables in DB
@@ -249,71 +254,14 @@ public class IntegrityMonitor {
try {
// if ForwardProgress entry exists for resourceName, update it. If
// not found, create a new entry
- Query fquery = em.createQuery(QUERY_STRING);
- fquery.setParameter("rn", resourceName);
-
- @SuppressWarnings("rawtypes")
- List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ForwardProgressEntity fpx = null;
- if (!fpList.isEmpty()) {
- // ignores multiple results
- fpx = (ForwardProgressEntity) 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();
- }
+ createOrUpdateForwardProgress(resourceName);
// if ResourceRegistration entry exists for resourceName, update it.
// If not found, create a new entry
- Query rquery = em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn");
- rquery.setParameter("rn", resourceName);
-
- @SuppressWarnings("rawtypes")
- List rrList = rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ResourceRegistrationEntity rrx = null;
- if (!rrList.isEmpty()) {
- // ignores multiple results
- rrx = (ResourceRegistrationEntity) 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();
- }
+ createOrUpdateResourceReg(resourceName, jmxUrl, et);
} catch (Exception e) {
- logger.error("IntegrityMonitor constructor DB table update failed with exception: ", e);
+ logger.error("IntegrityMonitor constructor DB table update threw an exception");
try {
if (et.isActive()) {
synchronized (imFlushLock) {
@@ -326,36 +274,115 @@ public class IntegrityMonitor {
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.
+ /*
+ * 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);
}
+ }
- // create management bean
+ protected void makeManagementBean(String resourceName) {
try {
new ComponentAdmin(resourceName, this, stateManager);
} catch (Exception e) {
- logger.error("ComponentAdmin constructor exception: {}", e.toString(), e);
+ logger.error("ComponentAdmin constructor exception: {}", e, e);
}
+ }
- // set now as the last time the refreshStateAudit ran
- IntegrityMonitor.this.refreshStateAuditLastRunDate = MonitorTime.getInstance().getDate();
-
- fpManager = new Thread(this::runFpManager);
- fpManager.start();
-
+ private static void setInstance(IntegrityMonitor newInstance, String newResourceName) {
+ instance = newInstance;
+ resourceName = newResourceName;
}
/**
@@ -363,12 +390,12 @@ public class IntegrityMonitor {
* 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
+ * @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 {
+ throws IntegrityMonitorException {
synchronized (getInstanceLock) {
logger.debug("getInstance() called - resourceName= {}", resourceName);
@@ -379,7 +406,8 @@ public class IntegrityMonitor {
if (instance == null) {
logger.debug("Creating new instance of IntegrityMonitor");
- instance = new IntegrityMonitor(resourceName, properties);
+ // note: new() will populate "instance"
+ new IntegrityMonitor(resourceName, properties);
}
return instance;
}
@@ -395,7 +423,7 @@ public class IntegrityMonitor {
logger.debug("getInstance() called");
if (instance == null) {
String msg = "No IntegrityMonitor instance exists."
- + " Please use the method IntegrityMonitor.getInstance(String resourceName, Properties properties)";
+ + " Please use the method IntegrityMonitor.getInstance(String resourceName, Properties properties)";
throw new IntegrityMonitorPropertiesException(msg);
} else {
return instance;
@@ -411,7 +439,7 @@ public class IntegrityMonitor {
synchronized (getInstanceLock) {
if (isUnitTesting() && instance != null && instance.fpManager != null) {
// Stop the FPManager thread
- Thread fpm = instance.fpManager;
+ Thread fpm = instance.fpManager.get();
instance.fpManager = null;
fpm.interrupt();
@@ -426,7 +454,7 @@ public class IntegrityMonitor {
if (fpm.isAlive()) {
logger.error("IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
throw new IntegrityMonitorException(
- "IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
+ "IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
}
instance = null;
@@ -438,7 +466,7 @@ public class IntegrityMonitor {
private static String getJmxUrlFromProps() throws IntegrityMonitorException {
// get the jmx remote port and construct the JMX URL
- Properties systemProps = System.getProperties();
+ var systemProps = System.getProperties();
String jmxPort = systemProps.getProperty("com.sun.management.jmxremote.port");
String jmxErrMsg;
if (jmxPort == null) {
@@ -447,7 +475,7 @@ public class IntegrityMonitor {
throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg);
}
- int port = 0;
+ var port = 0;
try {
port = Integer.parseInt(jmxPort);
} catch (NumberFormatException e) {
@@ -462,12 +490,12 @@ public class IntegrityMonitor {
jmxFqdn = InetAddress.getLocalHost().getCanonicalHostName();
}
} catch (Exception e) {
- String msg = "getJmxUrl could not get hostname";
+ var msg = "getJmxUrl could not get hostname";
logger.error("{}", msg, e);
throw new IntegrityMonitorException("getJmxUrl Exception: " + msg);
}
if (jmxFqdn == null) {
- String msg = "getJmxUrl encountered null hostname";
+ var msg = "getJmxUrl encountered null hostname";
logger.error("{}", msg);
throw new IntegrityMonitorException("getJmxUrl error: " + msg);
}
@@ -506,7 +534,7 @@ public class IntegrityMonitor {
}
// check standby state and throw exception if cold standby
if ((stateManager.getStandbyStatus() != null)
- && stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
+ && 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);
@@ -531,21 +559,22 @@ public class IntegrityMonitor {
String errorMsg =
withinTransaction(dep + ": ForwardProgressEntity DB operation failed with exception: ", () -> {
- Query query = em.createQuery(
- "Select p from ForwardProgressEntity p where p.resourceName=:resource");
+ TypedQuery<ForwardProgressEntity> query = em.createQuery(
+ "Select p from ForwardProgressEntity p where p.resourceName=:resource",
+ ForwardProgressEntity.class);
query.setParameter(LC_RESOURCE_STRING, dep);
- @SuppressWarnings("rawtypes")
- List fpList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT)
- .getResultList();
+ List<ForwardProgressEntity> fpList = query.setLockMode(LockModeType.NONE)
+ .setFlushMode(FlushModeType.COMMIT).getResultList();
if (!fpList.isEmpty()) {
// exists
- forwardProgressEntity.set((ForwardProgressEntity) fpList.get(0));
+ 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);
+ logger.debug("Found entry in ForwardProgressEntity table for dependent Resource={}",
+ dep);
return null;
} else {
@@ -553,18 +582,20 @@ public class IntegrityMonitor {
}
});
- if (errorMsg == null) {
+ if (StringUtils.isEmpty(errorMsg)) {
errorMsg = withinTransaction(dep + ": StateManagementEntity DB read failed with exception: ", () -> {
// query if StateManagement entry exists for dependent resource
- Query query = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource");
+ TypedQuery<StateManagementEntity> query =
+ em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource",
+ StateManagementEntity.class);
query.setParameter(LC_RESOURCE_STRING, dep);
- @SuppressWarnings("rawtypes")
- List smList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ List<StateManagementEntity> smList =
+ query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!smList.isEmpty()) {
// exist
- stateManagementEntity.set((StateManagementEntity) smList.get(0));
+ stateManagementEntity.set(smList.get(0));
// refresh the object from DB in case cached data was
// returned
em.refresh(stateManagementEntity.get());
@@ -577,12 +608,12 @@ public class IntegrityMonitor {
}
// verify that the ForwardProgress is current (check last_updated)
- if (errorMsg == null) {
+ if (StringUtils.isEmpty(errorMsg)) {
checkForwardProgress(dep, forwardProgressEntity.get(), stateManagementEntity.get());
}
// check operation, admin and standby states of dependent resource
- if (errorMsg == null) {
+ if (StringUtils.isEmpty(errorMsg)) {
errorMsg = checkDependentStates(dep, stateManagementEntity.get());
}
@@ -594,45 +625,38 @@ public class IntegrityMonitor {
/**
* Runs an action within a transaction.
*
- * @param exMsg message to log and return if an exception occurs
+ * @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) {
- String errorMsg = null;
-
// Start a transaction
EntityTransaction et = em.getTransaction();
et.begin();
try {
- errorMsg = action.get();
- if (errorMsg != null) {
- logger.error("{}", errorMsg);
- }
-
+ var errorMsg = action.get();
+ logger.error("{}", errorMsg);
synchronized (imFlushLock) {
et.commit();
}
-
+ return errorMsg;
} catch (RuntimeException ex) {
// log an error
- errorMsg = exMsg;
- logger.error("{}", errorMsg, ex);
+ logger.error("{}", exMsg, ex);
synchronized (imFlushLock) {
if (et.isActive()) {
et.rollback();
}
}
+ return exMsg;
}
-
- return errorMsg;
}
private void checkForwardProgress(String dep, ForwardProgressEntity forwardProgressEntity,
- StateManagementEntity stateManagementEntity) {
+ StateManagementEntity stateManagementEntity) {
if (forwardProgressEntity != null && stateManagementEntity != null) {
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
long diffMs = date.getTime() - forwardProgressEntity.getLastUpdated().getTime();
logger.debug("IntegrityMonitor.stateCheck(): diffMs = {}", diffMs);
@@ -646,15 +670,13 @@ public class IntegrityMonitor {
}
} else {
+ String msg;
if (forwardProgressEntity == null) {
- String msg = STATE_CHECK_STRING + dep
- + "; " + " forwardProgressEntity == null.";
- logger.error("{}", msg);
+ msg = STATE_CHECK_STRING + dep + "; " + " forwardProgressEntity == null.";
} else {
- String msg = STATE_CHECK_STRING + dep
- + "; " + " stateManagementEntity == null.";
- logger.error("{}", msg);
+ msg = STATE_CHECK_STRING + dep + "; " + " stateManagementEntity == null.";
}
+ logger.error("{}", msg);
}
}
@@ -663,15 +685,15 @@ public class IntegrityMonitor {
if (stateManagementEntity != null) {
if ((stateManager.getAdminState() != null)
- && stateManagementEntity.getAdminState().equals(StateManagement.LOCKED)) {
+ && stateManagementEntity.getAdminState().equals(StateManagement.LOCKED)) {
errorMsg = dep + ": resource is administratively locked";
logger.error("{}", errorMsg);
} else if ((stateManager.getOpState() != null)
- && stateManagementEntity.getOpState().equals(StateManagement.DISABLED)) {
+ && 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)) {
+ && stateManagementEntity.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
errorMsg = dep + ": resource is cold standby";
logger.error("{}", errorMsg);
}
@@ -690,20 +712,20 @@ public class IntegrityMonitor {
}
private String fpCheck2(String dep) {
- Query fquery = em.createQuery(QUERY_STRING);
+ TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
fquery.setParameter("rn", dep);
- @SuppressWarnings("rawtypes")
- List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ List<ForwardProgressEntity> fpList =
+ fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
ForwardProgressEntity fpx;
if (!fpList.isEmpty()) {
// ignores multiple results
- fpx = (ForwardProgressEntity) fpList.get(0);
+ 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());
+ fpx.getLastUpdated());
}
long currTime = MonitorTime.getInstance().getMillis();
// if dependent resource FPC has not been updated, consider it
@@ -733,9 +755,9 @@ public class IntegrityMonitor {
ArrayList<ForwardProgressEntity> fpList = new ArrayList<>();
withinTransaction("getAllForwardProgessEntity DB read failed with exception: ", () -> {
- Query fquery = em.createQuery("Select e from ForwardProgressEntity e");
+ var fquery = em.createQuery("Select e from ForwardProgressEntity e");
fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList()
- .forEach(obj -> fpList.add((ForwardProgressEntity) obj));
+ .forEach(obj -> fpList.add((ForwardProgressEntity) obj));
return null;
});
@@ -744,10 +766,10 @@ public class IntegrityMonitor {
}
logger.debug("getAllForwardProgressEntity: fpList.size(): {}", fpList.size());
- int index = 0;
+ var index = 0;
for (ForwardProgressEntity fpe : fpList) {
logger.debug("getAllForwardProgressEntity: fpList.get({}).getResourceName(): {}", index++,
- fpe.getResourceName());
+ fpe.getResourceName());
}
return fpList;
@@ -759,9 +781,8 @@ public class IntegrityMonitor {
// 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));
+ String errorMsg = withinTransaction(dep + ": ResourceRegistrationEntity DB read failed with exception: ",
+ () -> getJmxUrlFromDb(dep, jmxUrl));
if (jmxUrl.get() != null) {
errorMsg = jmxCheck2(dep, jmxUrl.get(), errorMsg);
@@ -772,25 +793,24 @@ public class IntegrityMonitor {
private String getJmxUrlFromDb(String dep, AtomicReference<String> jmxUrl) {
// query if ResourceRegistration entry exists for resourceName
- Query rquery = em.createQuery(
- "Select r from ResourceRegistrationEntity r where r.resourceName=:rn");
+ TypedQuery<ResourceRegistrationEntity> rquery =
+ em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn",
+ ResourceRegistrationEntity.class);
rquery.setParameter("rn", dep);
- @SuppressWarnings("rawtypes")
- List rrList = rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT)
- .getResultList();
- ResourceRegistrationEntity rrx = null;
+ List<ResourceRegistrationEntity> rrList =
+ rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ ResourceRegistrationEntity rrx;
if (!rrList.isEmpty()) {
// ignores multiple results
- rrx = (ResourceRegistrationEntity) rrList.get(0);
+ 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());
+ logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl.get(), rrx.getCreatedDate());
}
return null;
@@ -806,7 +826,7 @@ public class IntegrityMonitor {
jmxAgentConnection = new JmxAgentConnection(jmxUrl);
MBeanServerConnection mbeanServer = jmxAgentConnection.getMBeanConnection();
ComponentAdminMBean admin =
- JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class);
+ JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class);
// invoke the test method via the jmx proxy
admin.test();
@@ -834,7 +854,7 @@ public class IntegrityMonitor {
synchronized (dependencyCheckLock) {
// Start with the error message empty
- StringBuilder errorMsg = new StringBuilder();
+ var errorMsg = new StringBuilder();
/*
* Before we check dependency groups we need to check subsystemTest.
@@ -846,18 +866,17 @@ public class IntegrityMonitor {
dependencyOk = checkDependencies(errorMsg) && dependencyOk;
/*
- * We have checked all the dependency groups. If all are ok and subsystemTest
- * passed, dependencyFailure == false
+ * 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.
+ * 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);
}
@@ -893,10 +912,8 @@ public class IntegrityMonitor {
// 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());
+ 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);
@@ -924,7 +941,7 @@ public class IntegrityMonitor {
* @return {@code true} if the dependencies are OK, {@code false} otherwise
*/
private boolean checkDependencies(StringBuilder errorMsg) {
- boolean dependencyOk = true;
+ var dependencyOk = true;
// check state of resources in dependency groups
for (String group : depGroups) {
@@ -936,7 +953,7 @@ public class IntegrityMonitor {
}
// check the next group
- } // end for (String group : depGroups)
+ }
return dependencyOk;
}
@@ -944,7 +961,7 @@ public class IntegrityMonitor {
/**
* Checks if a dependency group has an error.
*
- * @param group group to be checked
+ * @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
*/
@@ -954,12 +971,12 @@ public class IntegrityMonitor {
// ignore empty group
return false;
}
- String[] dependencies = group.split(",");
+ String[] dependencies = COMMA_PAT.split(group);
if (logger.isDebugEnabled()) {
logger.debug("group dependencies = {}", Arrays.toString(dependencies));
}
- int realDepCount = 0;
- int failDepCount = 0;
+ var realDepCount = 0;
+ var failDepCount = 0;
for (String dep : dependencies) {
dep = dep.trim();
if (dep.isEmpty()) {
@@ -974,7 +991,7 @@ public class IntegrityMonitor {
appendSeparator(errorMsg);
errorMsg.append(failMsg);
}
- } // end for (String dep : dependencies)
+ }
// if all dependencies in a group are failed, set this
// resource's state to disable dependency
@@ -1005,16 +1022,16 @@ public class IntegrityMonitor {
* Disables the dependency group.
*
* @param errorMsg error messages are appended to this
- * @param group group of interest
+ * @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))) {
+ + "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();
@@ -1033,12 +1050,11 @@ public class IntegrityMonitor {
private void dependenciesGood(StringBuilder errorMsg) {
try {
- logger.debug(
- "All dependency groups have at least one viable member. Updating this resource's state"
- + " to enableNoDependency");
+ 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))) {
+ && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
+ || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
// Note: redundant calls are made by
// refreshStateAudit
this.stateManager.enableNoDependency();
@@ -1057,8 +1073,8 @@ public class IntegrityMonitor {
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))) {
+ && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
+ || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
// Note: redundant calls are made by refreshStateAudit
this.stateManager.enableNoDependency();
}
@@ -1073,7 +1089,7 @@ public class IntegrityMonitor {
}
private void appendSeparator(StringBuilder errorMsg) {
- if (errorMsg.length() != 0) {
+ if (!errorMsg.isEmpty()) {
errorMsg.append(',');
}
}
@@ -1099,9 +1115,8 @@ public class IntegrityMonitor {
* 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.
*
- * @throws IntegrityMonitorException if an error occurs
*/
- public void subsystemTest() throws IntegrityMonitorException {
+ public void subsystemTest() {
// Testing provided by subsystem
logger.debug("IntegrityMonitor subsystemTest() OK");
}
@@ -1123,8 +1138,8 @@ public class IntegrityMonitor {
// check standby state and throw exception if locked
if ((stateManager.getStandbyStatus() != null)
- && (stateManager.getStandbyStatus().equals(StateManagement.HOT_STANDBY)
- || stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY))) {
+ && (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);
@@ -1144,26 +1159,28 @@ public class IntegrityMonitor {
if (getAllNotWellMap() != null) {
if (!(getAllNotWellMap().isEmpty())) {
/*
- * An entity has reported that it is not well. We must not allow the the forward
- * progress counter to advance.
+ * An entity has reported that it is not well. We must not allow the forward progress counter to
+ * advance.
*/
- String msg = "allNotWellMap:";
- for (Entry<String, String> entry : allNotWellMap.entrySet()) {
- msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue());
- }
- logger.error("endTransaction: allNotWellMap is NOT EMPTY. Not advancing forward"
- + "progress counter. \n{}\n", msg);
+ 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())) {
- String msg = "allSeemsWellMap:";
- for (Entry<String, String> entry : allSeemsWellMap.entrySet()) {
- msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue());
- }
+ var msg = new StringBuilder("allSeemsWellMap:");
+ buildMapString(msg, allSeemsWellMap);
logger.debug(
- "endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY. "
- + "Advancing forward progress counter. \n{}\n", msg);
+ """
+ endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY.
+ Advancing forward progress counter.
+ {}
+ """, msg);
}
}
// increment local FPC
@@ -1171,6 +1188,15 @@ public class IntegrityMonitor {
}
}
+ 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 {
@@ -1183,20 +1209,20 @@ public class IntegrityMonitor {
try {
// query if ForwardProgress entry exists for resourceName
- Query fquery = em.createQuery(QUERY_STRING);
+ TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
fquery.setParameter("rn", resourceName);
- @SuppressWarnings("rawtypes")
- List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ List<ForwardProgressEntity> fpList =
+ fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
ForwardProgressEntity fpx;
if (!fpList.isEmpty()) {
// ignores multiple results
- fpx = (ForwardProgressEntity) fpList.get(0);
+ 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);
+ resourceName, fpx.getFpcCount(), fpx.getLastUpdated(), fpCounter);
}
fpx.setFpcCount(fpCounter);
em.persist(fpx);
@@ -1219,16 +1245,11 @@ public class IntegrityMonitor {
} catch (Exception e1) {
logger.error(EXCEPTION_STRING, e1);
}
- logger.error("writeFpc DB table commit failed with exception: {}", e);
+ logger.error("writeFpc DB table commit failed with exception");
throw e;
}
}
- // retrieve state manager reference
- public final StateManagement getStateManager() {
- return this.stateManager;
- }
-
/**
* Read and validate properties.
*
@@ -1241,28 +1262,24 @@ public class IntegrityMonitor {
checkNonNull(prop, IntegrityMonitorProperties.DB_USER);
checkNonNull(prop, IntegrityMonitorProperties.DB_PWD);
- setLong(prop, IntegrityMonitorProperties.FP_MONITOR_INTERVAL,
- value -> monitorIntervalMs = toMillis(value));
+ setLong(prop, IntegrityMonitorProperties.FP_MONITOR_INTERVAL, value -> monitorIntervalMs = toMillis(value));
- setInt(prop, IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD,
- value -> failedCounterThreshold = value);
+ setInt(prop, value -> failedCounterThreshold = value);
- setLong(prop, IntegrityMonitorProperties.TEST_TRANS_INTERVAL,
- value -> testTransIntervalMs = toMillis(value));
+ setLong(prop, IntegrityMonitorProperties.TEST_TRANS_INTERVAL, value -> testTransIntervalMs = toMillis(value));
- setLong(prop, IntegrityMonitorProperties.WRITE_FPC_INTERVAL,
- value -> writeFpcIntervalMs = 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 semi-colon separated list of groups
+ // 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 = depGroupsValue.split(";");
+ depGroups = SEMICOLON_PAT.split(depGroupsValue);
if (logger.isDebugEnabled()) {
logger.debug("dependency groups property = {}", Arrays.toString(depGroups));
}
@@ -1285,14 +1302,13 @@ public class IntegrityMonitor {
setLong(prop, IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL,
value -> maxFpcUpdateIntervalMs = toMillis(value));
- setLong(prop, IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS,
- value -> stateAuditIntervalMs = 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);
+ maxFpcUpdateIntervalMs);
}
private static void setBoolean(Properties props, String propName, Consumer<Boolean> setter) {
@@ -1302,8 +1318,7 @@ public class IntegrityMonitor {
}
}
- private static String checkNonNull(Properties props, String propName)
- throws IntegrityMonitorPropertiesException {
+ private static String checkNonNull(Properties props, String propName) throws IntegrityMonitorPropertiesException {
String propValue = props.getProperty(propName);
if (propValue == null) {
@@ -1315,8 +1330,8 @@ public class IntegrityMonitor {
return propValue.trim();
}
- private static void setInt(Properties props, String propName, Consumer<Integer> setter) {
- String propValue = props.getProperty(propName);
+ private static void setInt(Properties props, IntConsumer setter) {
+ String propValue = props.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD);
if (StringUtils.isBlank(propValue)) {
return;
}
@@ -1324,11 +1339,11 @@ public class IntegrityMonitor {
try {
setter.accept(Integer.parseInt(propValue.trim()));
} catch (NumberFormatException e) {
- logger.warn(IGNORE_INVALID_PROPERTY_STRING, propName, e);
+ logger.warn(IGNORE_INVALID_PROPERTY_STRING, IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, e);
}
}
- private static void setLong(Properties props, String propName, Consumer<Long> setter) {
+ private static void setLong(Properties props, String propName, LongConsumer setter) {
String propValue = props.getProperty(propName);
if (StringUtils.isBlank(propValue)) {
return;
@@ -1409,7 +1424,7 @@ public class IntegrityMonitor {
missedCycles += 1;
if (missedCycles >= failedCounterThreshold && !alarmExists) {
logger.debug("Forward progress not detected for resource {}. Setting state to disable failed.",
- resourceName);
+ resourceName);
if (!(stateManager.getOpState()).equals(StateManagement.DISABLED)) {
// Note: The refreshStateAudit will make redundant
// calls
@@ -1425,8 +1440,7 @@ public class IntegrityMonitor {
lastFpCounter = fpCounter;
missedCycles = 0;
// set op state to enabled
- logger.debug("Forward progress detected for resource {}. Setting state to enable not failed.",
- resourceName);
+ 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();
@@ -1457,13 +1471,13 @@ public class IntegrityMonitor {
return;
}
if (!stateManager.getStandbyStatus().equals(StateManagement.NULL_VALUE)
- && stateManager.getStandbyStatus() != null
- && !stateManager.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)) {
+ && stateManager.getStandbyStatus() != null
+ && !stateManager.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)) {
logger.debug("IntegrityMonitor.stateAudit(): NOT PROVIDING_SERVICE. returning");
return;
}
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
long timeSinceLastStateAudit = date.getTime() - lastStateAuditTime.getTime();
if (timeSinceLastStateAudit < stateAuditIntervalMs) {
logger.debug("IntegrityMonitor.stateAudit(): Not time to run. returning");
@@ -1482,14 +1496,14 @@ public class IntegrityMonitor {
*/
public void executeStateAudit() {
logger.debug("IntegrityMonitor.executeStateAudit(): entry");
- Date date = MonitorTime.getInstance().getDate();
+ 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 the this is my ForwardProgressEntity, continue
+ // If this is my ForwardProgressEntity, continue
if (fpe.getResourceName().equals(IntegrityMonitor.resourceName)) {
continue;
}
@@ -1498,21 +1512,21 @@ public class IntegrityMonitor {
long diffMs = date.getTime() - fpe.getLastUpdated().getTime();
if (logger.isDebugEnabled()) {
logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, diffMs = {}", fpe.getResourceName(),
- diffMs);
+ diffMs);
}
// Threshold for a stale entry
long staleMs = maxFpcUpdateIntervalMs;
if (logger.isDebugEnabled()) {
logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, staleMs = {}", fpe.getResourceName(),
- staleMs);
+ staleMs);
}
if (diffMs > staleMs) {
// ForwardProgress is stale. Disable it
// Start a transaction
logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, FPC is stale. Disabling it",
- fpe.getResourceName());
+ fpe.getResourceName());
EntityTransaction et = em.getTransaction();
et.begin();
StateManagementEntity sme = disableEntity(et, fpe);
@@ -1520,15 +1534,16 @@ public class IntegrityMonitor {
if (sme != null && !sme.getOpState().equals(StateManagement.DISABLED)) {
disableFailed(sme);
}
- } // end if(diffMs > staleMs)
- } // end for(ForwardProgressEntity fpe : fpList)
+ }
+ }
logger.debug("IntegrityMonitor.executeStateAudit(): exit");
}
/**
* Disables the entity.
+ *
* @param entrans entity transaction
- * @param fpe entity of interest
+ * @param fpe entity of interest
* @return the corresponding state management entity
*/
private StateManagementEntity disableEntity(EntityTransaction entrans, ForwardProgressEntity fpe) {
@@ -1536,28 +1551,26 @@ public class IntegrityMonitor {
try {
// query if StateManagement entry exists for fpe resource
- Query query =
- em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource");
+ TypedQuery<StateManagementEntity> query =
+ em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource",
+ StateManagementEntity.class);
query.setParameter(LC_RESOURCE_STRING, fpe.getResourceName());
- @SuppressWarnings("rawtypes")
- List smList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ List<StateManagementEntity> smList =
+ query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!smList.isEmpty()) {
// exists
- sme = (StateManagementEntity) smList.get(0);
+ 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());
+ 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";
+ + ": resource not found in state management entity database table";
logger.error("{}", msg);
}
synchronized (imFlushLock) {
@@ -1566,7 +1579,7 @@ public class IntegrityMonitor {
} catch (Exception e) {
// log an error
logger.error("IntegrityMonitor.executeStateAudit(): {}: StateManagementEntity DB read failed with "
- + "exception: ", fpe.getResourceName(), e);
+ + "exception: ", fpe.getResourceName(), e);
synchronized (imFlushLock) {
if (entrans.isActive()) {
entrans.rollback();
@@ -1584,19 +1597,18 @@ public class IntegrityMonitor {
stateManager.disableFailed(dep);
}
} catch (Exception e) {
- String msg = STATE_CHECK_STRING + dep
- + "; " + e.getMessage();
+ String msg = STATE_CHECK_STRING + dep + "; " + e.getMessage();
logger.error("{}", msg, e);
}
}
private void disableEntity(String dep) {
try {
- // create instance of StateMangement class for dependent
- StateManagement depStateManager = new StateManagement(emf, dep);
+ // 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);
+ + "state to disable failed.", dep);
depStateManager.disableFailed();
}
} catch (Exception e) {
@@ -1607,12 +1619,13 @@ public class IntegrityMonitor {
/**
* 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());
+ sme.getResourceName());
}
try {
stateManager.disableFailed(sme.getResourceName());
@@ -1692,7 +1705,7 @@ public class IntegrityMonitor {
long currTime = MonitorTime.getInstance().getMillis();
logger.debug("checkDependentHealth currTime - lastDependencyCheckTime = {}",
- currTime - lastDependencyCheckTime);
+ currTime - lastDependencyCheckTime);
if ((currTime - lastDependencyCheckTime) > checkDependencyIntervalMs) {
// execute dependency check and update this resource's state
@@ -1702,13 +1715,13 @@ public class IntegrityMonitor {
}
/*
- * 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 synch due to database
- * corruption (manual or otherwise) or because a node became isolated.
+ * 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.
+ * 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");
@@ -1728,7 +1741,7 @@ public class IntegrityMonitor {
logger.debug("executeRefreshStateAudit(): entry");
synchronized (refreshStateAuditLock) {
logger.debug("refreshStateAudit: entry");
- Date now = MonitorTime.getInstance().getDate();
+ var now = MonitorTime.getInstance().getDate();
long nowMs = now.getTime();
long lastTimeMs = refreshStateAuditLastRunDate.getTime();
logger.debug("refreshStateAudit: ms since last run = {}", nowMs - lastTimeMs);
@@ -1814,10 +1827,8 @@ public class IntegrityMonitor {
* @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
- * @throws AllSeemsWellException if an error occurs
*/
- public void allSeemsWell(String key, Boolean asw, String msg)
- throws AllSeemsWellException {
+ public void allSeemsWell(String key, Boolean asw, String msg) {
logger.debug("allSeemsWell entry: key = {}, asw = {}, msg = {}", key, asw, msg);
if (StringUtils.isEmpty(key)) {
@@ -1841,7 +1852,7 @@ public class IntegrityMonitor {
allNotWellMap = new HashMap<>();
}
- if (asw) {
+ if (Boolean.TRUE.equals(asw)) {
logger.info("allSeemsWell: ALL SEEMS WELL: key = {}, msg = {}", key, msg);
allSeemsWellMap.put(key, msg);
allNotWellMap.remove(key);
@@ -1864,7 +1875,7 @@ public class IntegrityMonitor {
}
/**
- * Converts the given value to milliseconds using the current {@link #propertyUnits}.
+ * 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
@@ -1873,19 +1884,10 @@ public class IntegrityMonitor {
return (value < 0 ? -1 : value * 1000L);
}
- public Map<String, String> getAllSeemsWellMap() {
- return allSeemsWellMap;
- }
-
- public Map<String, String> getAllNotWellMap() {
- return allNotWellMap;
- }
-
// these methods may be overridden by junit tests
/**
- * Indicates that the {@link FpManager#run()} method has started. This method
- * simply returns.
+ * Indicates that the {FpManager#run()} method has started. This method simply returns.
*
* @throws InterruptedException can be interrupted
*/
@@ -1910,16 +1912,4 @@ public class IntegrityMonitor {
protected String getPersistenceUnit() {
return PERSISTENCE_UNIT;
}
-
- /*
- * The remaining methods are used by JUnit tests.
- */
-
- public static boolean isUnitTesting() {
- return isUnitTesting;
- }
-
- public static void setUnitTesting(boolean isUnitTesting) {
- IntegrityMonitor.isUnitTesting = isUnitTesting;
- }
}
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
index 252fd27b..6af7a557 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,12 +21,16 @@
package org.onap.policy.common.im;
-public class IntegrityMonitorProperties {
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
- public static final String DB_DRIVER = "javax.persistence.jdbc.driver";
- public static final String DB_URL = "javax.persistence.jdbc.url";
- public static final String DB_USER = "javax.persistence.jdbc.user";
- public static final String DB_PWD = "javax.persistence.jdbc.password"; //NOSONAR
+@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;
@@ -54,8 +59,4 @@ public class IntegrityMonitorProperties {
// AllSeemsWell types
public static final Boolean ALLNOTWELL = Boolean.FALSE;
public static final Boolean ALLSEEMSWELL = Boolean.TRUE;
-
- private IntegrityMonitorProperties() {
- // Private constructor to prevent subclassing
- }
}
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
index e489a8c1..61afb682 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,31 +20,20 @@
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();
-
- /**
- * Constructor.
- */
- private MonitorTime() {
- super();
- }
-
- /**
- * Get instance.
- *
- * @return the CurrentTime singleton
- */
- public static CurrentTime getInstance() {
- return instance;
- }
}
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
index eee3a9ef..5fc111e0 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017, 2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.im;
+import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
@@ -43,6 +44,7 @@ import org.slf4j.LoggerFactory;
* StateManagement class.
*
*/
+@Getter
public class StateChangeNotifier {
private static final Logger logger = LoggerFactory.getLogger(StateChangeNotifier.class);
// The observable class
@@ -71,12 +73,4 @@ public class StateChangeNotifier {
logger.debug("handleStateChange, message: {}", this.message);
}
}
-
- public StateManagement getStateManagement() {
- return stateManagement;
- }
-
- public String getMessage() {
- return 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
index 73724b30..d1bc9cc1 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,12 +21,14 @@
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);
@@ -41,10 +43,6 @@ public class StateElement {
String endingStandbyStatus = null;
String exception = null;
- public StateElement() {
- // Empty constructor
- }
-
/**
* Display the state element.
*/
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
index 7a018ef9..eace6037 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,16 +21,16 @@
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 javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.FlushModeType;
-import javax.persistence.LockModeType;
-import javax.persistence.TypedQuery;
import org.onap.policy.common.im.exceptions.EntityRetrievalException;
import org.onap.policy.common.im.jpa.StateManagementEntity;
import org.onap.policy.common.utils.jpa.EntityMgrCloser;
@@ -147,7 +148,7 @@ public class StateManagement {
* 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)
+ private void setState(String methodName, String resourceName, ExFunction<StateManagementEntity, String> updateState)
throws StateManagementException {
synchronized (SYNCLOCK) {
@@ -155,13 +156,13 @@ public class StateManagement {
resourceName);
logger.debug("StateManagement: {}() operation started, resourceName = {}", methodName, resourceName);
- final EntityManager em = emf.createEntityManager();
+ final var em = emf.createEntityManager();
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
+ try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
logger.debug(FIND_MESSAGE, resourceName);
- final StateManagementEntity sm = findStateManagementEntity(em, resourceName);
+ final var sm = findStateManagementEntity(em, resourceName);
String changed = updateState.update(sm);
em.persist(sm);
@@ -174,7 +175,6 @@ public class StateManagement {
logger.debug("StateManagement: {}() operation completed, resourceName = {}",
methodName, resourceName);
} catch (final Exception ex) {
- logger.error("StateManagement.{}() caught unexpected exception: ", methodName, ex);
throw new StateManagementException("StateManagement." + methodName + "() Exception: " + ex);
}
}
@@ -198,7 +198,7 @@ public class StateManagement {
throws StateManagementException {
setState(actionName, resourceName, sm -> {
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
+ final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
sm.getAvailStatus(), sm.getStandbyStatus(), actionName);
sm.setAdminState(stateElement.getEndingAdminState());
@@ -293,7 +293,7 @@ public class StateManagement {
AtomicReference<String> newStatus = new AtomicReference<>();
setState(PROMOTE_ACTION, resourceName, sm -> {
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
+ final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
sm.getAvailStatus(), sm.getStandbyStatus(), PROMOTE_ACTION);
sm.setAdminState(stateElement.getEndingAdminState());
@@ -358,8 +358,8 @@ public class StateManagement {
logger.debug("StateManagement(6/1/16): {} for resourceName {}", methodName, resourceName);
- final EntityManager em = emf.createEntityManager();
- try (final EntityMgrCloser emc = new EntityMgrCloser(em)) {
+ 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);
@@ -370,7 +370,7 @@ public class StateManagement {
query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!resourceList.isEmpty()) {
// exist
- final StateManagementEntity stateManagementEntity = resourceList.get(0);
+ final var stateManagementEntity = resourceList.get(0);
// refresh the object from DB in case cached data was returned
em.refresh(stateManagementEntity);
function.accept(stateManagementEntity);
@@ -378,7 +378,7 @@ public class StateManagement {
notFound.run();
}
} catch (final Exception ex) {
- logger.error("StateManagement: {} exception: {}", methodName, ex.toString(), ex);
+ logger.error("StateManagement: {} exception: {}", methodName, ex.getMessage(), ex);
}
}
@@ -459,14 +459,14 @@ public class StateManagement {
query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!resourceList.isEmpty()) {
// exist
- final StateManagementEntity stateManagementEntity = resourceList.get(0);
+ 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 StateManagementEntity stateManagementEntity = new StateManagementEntity();
+ final var stateManagementEntity = new StateManagementEntity();
stateManagementEntity.setResourceName(otherResourceName);
stateManagementEntity.setAdminState(UNLOCKED);
stateManagementEntity.setOpState(ENABLED);
@@ -475,9 +475,7 @@ public class StateManagement {
return stateManagementEntity;
}
} catch (final Exception ex) {
- final String message = "findStateManagementEntity exception";
- logger.error("{}: {}", message, ex.toString(), ex);
- throw new EntityRetrievalException(message, ex);
+ throw new EntityRetrievalException("findStateManagementEntity exception", ex);
}
}
@@ -491,9 +489,9 @@ public class StateManagement {
/*
* Start transaction
*/
- final EntityManager em = emf.createEntityManager();
+ final var em = emf.createEntityManager();
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
+ 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
@@ -515,7 +513,7 @@ public class StateManagement {
}
@FunctionalInterface
- private static interface ExFunction<T,R> {
+ private static interface ExFunction<T, R> {
public R update(T object) throws IntegrityMonitorException;
}
@@ -533,7 +531,7 @@ public class StateManagement {
@Override
public void commit() {
synchronized (FLUSHLOCK) {
- if (getTransation().isActive()) {
+ if (getTransaction().isActive()) {
super.commit();
}
}
@@ -542,7 +540,7 @@ public class StateManagement {
@Override
public void rollback() {
synchronized (FLUSHLOCK) {
- if (getTransation().isActive()) {
+ if (getTransaction().isActive()) {
super.rollback();
}
}
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
index 3542aa2c..2ebef874 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.im;
+import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -37,6 +38,8 @@ 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,";
@@ -165,7 +168,7 @@ public class StateTransition {
}
- StateElement stateElement = new StateElement();
+ var stateElement = new StateElement();
// dependency,failed is stored as dependency.failed in StateTable
String availStatus2 = availStatus;
@@ -177,7 +180,7 @@ public class StateTransition {
String value = STATE_TABLE.get(key);
if (value != null) {
- String[] parts = value.split(",", 5);
+ String[] parts = COMMA_PAT.split(value, 5);
stateElement.setEndingAdminState(parts[0].trim());
stateElement.setEndingOpState(parts[1].trim());
stateElement.setEndingAvailStatus(parts[2].trim().replace(".", ","));
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
index bd7ed7b5..8cbdaa7d 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,7 +22,6 @@ 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;
@@ -31,7 +30,6 @@ 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;
@@ -54,7 +52,7 @@ public class ComponentAdmin implements ComponentAdminMBean {
/**
* Constructor.
- *
+ *
* @param name the MBean name
* @param integrityMonitor the integrity monitor
* @param stateManager the state manager
@@ -81,7 +79,7 @@ public class ComponentAdmin implements ComponentAdminMBean {
/**
* Registers with the MBean server.
- *
+ *
* @throws ComponentAdminException a JMX exception
*/
public synchronized void register() throws ComponentAdminException {
@@ -89,13 +87,13 @@ public class ComponentAdmin implements ComponentAdminMBean {
try {
logger.debug("Registering {} MBean", name);
- MBeanServer mbeanServer = findMBeanServer();
+ var mbeanServer = findMBeanServer();
if (mbeanServer == null) {
return;
}
- ObjectName objectName = new ObjectName(name);
+ var objectName = new ObjectName(name);
if (mbeanServer.isRegistered(objectName)) {
logger.debug("Unregistering a previously registered {} MBean", name);
@@ -114,7 +112,7 @@ public class ComponentAdmin implements ComponentAdminMBean {
/**
* Checks if this MBean is registered with the MBeanServer.
- *
+ *
* @return true if this MBean is registered with the MBeanServer.
*/
public boolean isRegistered() {
@@ -123,7 +121,7 @@ public class ComponentAdmin implements ComponentAdminMBean {
/**
* Unregisters with the MBean server.
- *
+ *
* @throws ComponentAdminException a JMX exception
*/
public synchronized void unregister() throws ComponentAdminException {
@@ -151,7 +149,7 @@ public class ComponentAdmin implements ComponentAdminMBean {
/**
* Finds the MBeanServer.
- *
+ *
* @return the MBeanServer, or null if it is not found
*/
public static MBeanServer findMBeanServer() {
@@ -172,7 +170,7 @@ public class ComponentAdmin implements ComponentAdminMBean {
/**
* Creates the MBeanServer (intended for unit testing only).
- *
+ *
* @return the MBeanServer
*/
public static MBeanServer createMBeanServer() {
@@ -181,7 +179,7 @@ public class ComponentAdmin implements ComponentAdminMBean {
/**
* Get the MBean object name for the specified feature name.
- *
+ *
* @param componentName component name
* @return the object name
* @throws MalformedObjectNameException a JMX exception
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
new file mode 100644
index 00000000..5213baef
--- /dev/null
+++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java
@@ -0,0 +1,71 @@
+/*-
+ * ============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
index f0ea2c00..7c9698b3 100644
--- 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
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,39 +21,35 @@
package org.onap.policy.common.im.jpa;
-import java.io.Serializable;
-import java.util.Date;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.NamedQueries;
-import javax.persistence.NamedQuery;
-import javax.persistence.PrePersist;
-import javax.persistence.PreUpdate;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
-/*
- * The Entity class to persist a policy object ForwardProgress
- */
-import org.onap.policy.common.im.MonitorTime;
+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")
-@NamedQueries({@NamedQuery(name = " ForwardProgressEntity.findAll", query = "SELECT e FROM ForwardProgressEntity e "),
- @NamedQuery(name = "ForwardProgressEntity.deleteAll", query = "DELETE FROM ForwardProgressEntity WHERE 1=1")})
-// @SequenceGenerator(name="seqForwardProgress", initialValue=1, allocationSize=1)
-
-public class ForwardProgressEntity implements Serializable {
+@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.SEQUENCE, generator="seqForwardProgress")
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "forwardProgressId")
+ @Setter(AccessLevel.NONE)
private long forwardProgressId;
@Column(name = "resourceName", nullable = false, length = 100, unique = true)
@@ -61,84 +58,13 @@ public class ForwardProgressEntity implements Serializable {
@Column(name = "fpc_count", nullable = false)
private long fpcCount;
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_date", updatable = false)
- private Date createdDate;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "last_updated")
- private Date lastUpdated;
-
- public ForwardProgressEntity() {
- // default constructor
- }
-
/**
* PrePersist callback method.
*/
@PrePersist
+ @Override
public void prePersist() {
- Date date = MonitorTime.getInstance().getDate();
- this.createdDate = date;
- this.lastUpdated = date;
this.fpcCount = 0;
- }
-
- @PreUpdate
- public void preUpdate() {
- this.lastUpdated = MonitorTime.getInstance().getDate();
- }
-
- /**
- * Get the forward progress Id.
- *
- * @return the Id
- */
- public long getForwardProgressId() {
- return forwardProgressId;
- }
-
- public String getResourceName() {
- return this.resourceName;
- }
-
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
-
- /**
- * Get the fpcCount.
- *
- * @return the fpcCount
- */
- public long getFpcCount() {
- return fpcCount;
- }
-
- /**
- * Set the fpcCount.
- *
- * @param fpcCount the fpcCount to set
- */
- public void setFpcCount(long fpcCount) {
- this.fpcCount = fpcCount;
- }
-
- /**
- * Get the lastUpdated.
- *
- * @return the lastUpdated
- */
- public Date getLastUpdated() {
- return lastUpdated;
- }
-
- /**
- * Set the lastUpdated.
- *
- * @param lastUpdated the lastUpdated to set
- */
- public void setLastUpdated(Date lastUpdated) {
- this.lastUpdated = lastUpdated;
+ 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
index 1822578b..e70a000b 100644
--- 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
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,36 +21,41 @@
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 javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.NamedQueries;
-import javax.persistence.NamedQuery;
-import javax.persistence.PrePersist;
-import javax.persistence.PreUpdate;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
import org.onap.policy.common.im.MonitorTime;
@Entity
@Table(name = "ImTestEntity")
-@NamedQueries({@NamedQuery(name = " ImTestEntity.findAll", query = "SELECT e FROM ImTestEntity e "),
- @NamedQuery(name = "ImTestEntity.deleteAll", query = "DELETE FROM ImTestEntity WHERE 1=1")})
-// @SequenceGenerator(name="seqImTest", initialValue=1, allocationSize=1)
-
+@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.SEQUENCE, generator="seqImTest")
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ImTestId")
+ @Setter(AccessLevel.NONE)
private long imTestId;
@Column(name = "created_by", nullable = false, length = 255)
@@ -66,16 +72,12 @@ public class ImTestEntity implements Serializable {
@Column(name = "modified_date", nullable = false)
private Date modifiedDate;
- public ImTestEntity() {
- // default constructor
- }
-
/**
* PrePersist callback method.
*/
@PrePersist
public void prePersist() {
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
this.createdDate = date;
this.modifiedDate = date;
}
@@ -84,76 +86,4 @@ public class ImTestEntity implements Serializable {
public void preUpdate() {
this.modifiedDate = MonitorTime.getInstance().getDate();
}
-
- /**
- * Get 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;
- }
}
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
index 42e141aa..a771ba09 100644
--- 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
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,42 +21,38 @@
package org.onap.policy.common.im.jpa;
-import java.io.Serializable;
-import java.util.Date;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.NamedQueries;
-import javax.persistence.NamedQuery;
-import javax.persistence.PrePersist;
-import javax.persistence.PreUpdate;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
-import org.onap.policy.common.im.MonitorTime;
+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.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")
-@NamedQueries({
- @NamedQuery(name = " ResourceRegistrationEntity.findAll",
- query = "SELECT e FROM ResourceRegistrationEntity e "),
- @NamedQuery(name = "ResourceRegistrationEntity.deleteAll",
- query = "DELETE FROM ResourceRegistrationEntity WHERE 1=1")})
-// @SequenceGenerator(name="seqResourceRegistration", initialValue=1, allocationSize=1)
-
-public class ResourceRegistrationEntity implements Serializable {
+@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.SEQUENCE, generator="seqResourceRegistration")
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ResourceRegistrationId")
+ @Setter(AccessLevel.NONE)
private long resourceRegistrationId;
@Column(name = "resourceName", nullable = false, length = 100, unique = true)
@@ -69,99 +66,4 @@ public class ResourceRegistrationEntity implements Serializable {
@Column(name = "nodeType", nullable = true, length = 50)
private String nodeType;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_date", updatable = false)
- private Date createdDate;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "last_updated")
- private Date lastUpdated;
-
- public ResourceRegistrationEntity() {
- // default constructor
- }
-
- /**
- * PrePersist callback method.
- */
- @PrePersist
- public void prePersist() {
- Date date = MonitorTime.getInstance().getDate();
- this.createdDate = date;
- this.lastUpdated = date;
- }
-
- @PreUpdate
- public void preUpdate() {
- this.lastUpdated = MonitorTime.getInstance().getDate();
- }
-
- /**
- * Get the resource registration Id.
- *
- * @return the Id
- */
- public long getResourceRegistrationId() {
- return resourceRegistrationId;
- }
-
- public String getResourceName() {
- return this.resourceName;
- }
-
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
-
- public String getResourceUrl() {
- return this.resourceUrl;
- }
-
- public void setResourceUrl(String resourceUrl) {
- this.resourceUrl = resourceUrl;
- }
-
- public String getSite() {
- return this.site;
- }
-
- public void setSite(String site) {
- this.site = site;
- }
-
- public String getNodeType() {
- return this.nodeType;
- }
-
- public void setNodeType(String nodeType) {
- this.nodeType = nodeType;
- }
-
- /**
- * Get the createdDate.
- *
- * @return the createdDate
- */
- public Date getCreatedDate() {
- return createdDate;
- }
-
- /**
- * Get the lastUpdated.
- *
- * @return the lastUpdated
- */
- public Date getLastUpdated() {
- return lastUpdated;
- }
-
- /**
- * Set the lastUpdated.
- *
- * @param lastUpdated the lastUpdated to set
- */
- public void setLastUpdated(Date lastUpdated) {
- this.lastUpdated = lastUpdated;
- }
}
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
index 494931d2..b03ec71b 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,38 +21,37 @@
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 javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.NamedQuery;
-import javax.persistence.PrePersist;
-import javax.persistence.PreUpdate;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
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")
-// @SequenceGenerator(name="seqSM", initialValue=1, allocationSize=1)
-
@Getter
@Setter
-
+@NoArgsConstructor
public class StateManagementEntity implements Serializable {
+ @Serial
private static final long serialVersionUID = 1L;
@Id
- // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqSM")
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@Getter(AccessLevel.NONE)
@@ -82,10 +82,6 @@ public class StateManagementEntity implements Serializable {
@Column(name = "modifiedDate", nullable = false)
private Date modifiedDate;
- public StateManagementEntity() {
- // default constructor
- }
-
@PrePersist
public void prePersist() {
this.createdDate = MonitorTime.getInstance().getDate();
@@ -104,7 +100,7 @@ public class StateManagementEntity implements Serializable {
* @return a new StateManagementEntity
*/
public static StateManagementEntity clone(StateManagementEntity sm) {
- StateManagementEntity newStateManagementEntity = new StateManagementEntity();
+ var newStateManagementEntity = new StateManagementEntity();
newStateManagementEntity.setResourceName(sm.getResourceName());
newStateManagementEntity.setAdminState(sm.getResourceName());
newStateManagementEntity.setOpState(sm.getOpState());
diff --git a/integrity-monitor/src/main/resources/META-INF/persistence.xml b/integrity-monitor/src/main/resources/META-INF/persistence.xml
index 7aff9219..beff1432 100644
--- a/integrity-monitor/src/main/resources/META-INF/persistence.xml
+++ b/integrity-monitor/src/main/resources/META-INF/persistence.xml
@@ -4,6 +4,7 @@
Integrity Monitor
================================================================================
Copyright (C) 2017, 2019 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.
@@ -19,24 +20,24 @@
============LICENSE_END=========================================================
-->
-<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="schemaPU" transaction-type="RESOURCE_LOCAL">
- <!-- Limited use for generating the DB and schema files for imtest DB - uses eclipselink -->
- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+ <!-- 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="javax.persistence.schema-generation.database.action" value="drop-and-create" />
+ <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.eclipse.persistence.jpa.PersistenceProvider</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>
diff --git a/integrity-monitor/src/main/resources/logback.xml b/integrity-monitor/src/main/resources/logback.xml
deleted file mode 100644
index 1d498631..00000000
--- a/integrity-monitor/src/main/resources/logback.xml
+++ /dev/null
@@ -1,261 +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=========================================================
- -->
-
-<configuration
- scan="true"
- scanPeriod="3 seconds"
- debug="true">
- <!--<jmxConfigurator /> -->
- <!-- directory path for all other type logs -->
- <property
- name="logDir"
- value="${POLICY_LOGS}" />
-
- <!-- directory path for debugging type logs -->
- <property
- name="debugDir"
- value="${POLICY_LOGS}" />
-
- <!-- 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-monitor"></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.rolling.RollingFileAppender">
- <file>${logDirectory}/${auditLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <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.rolling.RollingFileAppender">
- <file>${logDirectory}/${metricsLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
- %msg%n"</pattern> -->
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
-
- <appender
- name="asyncEELFMetrics"
- class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFMetrics" />
- </appender>
-
- <appender
- name="EELFError"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${errorLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>ERROR</level>
- </filter>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <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.rolling.RollingFileAppender">
- <file>${debugLogDirectory}/${debugLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>INFO</level>
- </filter>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
- <appender
- name="asyncEELFDebug"
- class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFDebug" />
- <includeCallerData>true</includeCallerData>
- </appender>
-
-
- <!-- ============================================================================ -->
- <!-- EELF loggers -->
- <!-- ============================================================================ -->
-
- <logger
- name="com.att.eelf.audit"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFAudit" />
- </logger>
-
- <logger
- name="com.att.eelf.metrics"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFMetrics" />
- </logger>
-
- <logger
- name="com.att.eelf.error"
- level="error"
- additivity="false">
- <appender-ref ref="asyncEELFError" />
- </logger>
-
- <logger
- name="com.att.eelf.debug"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFDebug" />
- </logger>
-
-
- <!-- <root level="INFO"> -->
- <root level="INFO">
- <appender-ref ref="asyncEELFDebug" />
- <appender-ref ref="asyncEELFError" />
- </root>
-
-</configuration>
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
index 79cfe549..b5c15904 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Modificaitons 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.
@@ -20,7 +21,7 @@
package org.onap.policy.common.im;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -33,9 +34,9 @@ import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.powermock.reflect.Whitebox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.test.util.ReflectionTestUtils;
public class AllSeemsWellTest extends IntegrityMonitorTestBase {
private static final String ALL_SEEMS_WELL_MSG = "'AllSeemsWellTest - ALLSEEMSWELL'";
@@ -93,7 +94,7 @@ public class AllSeemsWellTest extends IntegrityMonitorTestBase {
}
};
- Whitebox.setInternalState(IntegrityMonitor.class, IM_INSTANCE_FIELD, im);
+ ReflectionTestUtils.setField(IntegrityMonitor.class, IM_INSTANCE_FIELD, im);
}
@After
@@ -177,16 +178,19 @@ public class AllSeemsWellTest extends IntegrityMonitorTestBase {
}
// Check for null parameters
- assertThatThrownBy(() -> im.allSeemsWell(null, IntegrityMonitorProperties.ALLSEEMSWELL, ALL_SEEMS_WELL_MSG));
+ assertThatIllegalArgumentException().isThrownBy(
+ () -> im.allSeemsWell(null, IntegrityMonitorProperties.ALLSEEMSWELL, ALL_SEEMS_WELL_MSG));
- assertThatThrownBy(() -> im.allSeemsWell("", IntegrityMonitorProperties.ALLSEEMSWELL, ALL_SEEMS_WELL_MSG));
+ assertThatIllegalArgumentException().isThrownBy(
+ () -> im.allSeemsWell("", IntegrityMonitorProperties.ALLSEEMSWELL, ALL_SEEMS_WELL_MSG));
- assertThatThrownBy(() -> im.allSeemsWell(this.getClass().getName(), null, ALL_SEEMS_WELL_MSG));
+ assertThatIllegalArgumentException().isThrownBy(
+ () -> im.allSeemsWell(this.getClass().getName(), null, ALL_SEEMS_WELL_MSG));
- assertThatThrownBy(() -> im.allSeemsWell(this.getClass().getName(), IntegrityMonitorProperties.ALLSEEMSWELL,
- null));
+ assertThatIllegalArgumentException().isThrownBy(
+ () -> im.allSeemsWell(this.getClass().getName(), IntegrityMonitorProperties.ALLSEEMSWELL, null));
- assertThatThrownBy(
+ assertThatIllegalArgumentException().isThrownBy(
() -> im.allSeemsWell(this.getClass().getName(), IntegrityMonitorProperties.ALLSEEMSWELL, ""));
logger.debug("\n\ntestAllSeemsWell: Exit\n\n");
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
index 1e194c3b..adb19f54 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Modificaitons 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.
@@ -24,14 +25,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.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 javax.persistence.EntityTransaction;
-import javax.persistence.Query;
-import javax.persistence.TemporalType;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -40,9 +41,9 @@ import org.junit.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.powermock.reflect.Whitebox;
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
@@ -60,10 +61,17 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
private static final String SITE_B_PAP2 = "siteB_pap2";
private static final String ENABLE_NO_DEPENDENCY_MSG =
- "\n\nsm.enableNoDependency()\nAdminState = {}\nOpState() = {}\n"
- + "AvailStatus = {}\nStandbyStatus = {}\n";
+ """
- private static Logger logger = LoggerFactory.getLogger(IntegrityMonitorTest.class);
+
+ 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.
@@ -192,7 +200,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
waitCycles(DEPENDENCY_CHECK_CYCLES);
final IntegrityMonitor im2 = im;
- assertThatThrownBy(im2::evaluateSanity);
+ assertThatThrownBy(im2::evaluateSanity).isInstanceOf(IntegrityMonitorException.class);
// undo dependency groups and jmx test properties settings
myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "");
@@ -218,8 +226,15 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
im = makeMonitor(resourceName, myProp);
logger.debug(
- "\n\ntestSanityJmx state after creating new im\n"
- + "AdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
+ """
+
+
+ testSanityJmx state after creating new im
+ AdminState = {}
+ OpState() = {}
+ AvailStatus = {}
+ StandbyStatus = {}
+ """,
im.getStateManager().getAdminState(), im.getStateManager().getOpState(),
im.getStateManager().getAvailStatus(), im.getStateManager().getStandbyStatus());
@@ -244,8 +259,15 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
im = makeMonitor(resourceName, myProp);
sm = im.getStateManager();
logger.debug(
- "\n\ntestSanityJmx restart with AdminState=locked"
- + "\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
+ """
+
+
+ testSanityJmx restart with AdminState=locked
+ AdminState = {}
+ OpState() = {}
+ AvailStatus = {}
+ StandbyStatus = {}
+ """,
sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
assertEquals(StateManagement.LOCKED, sm.getAdminState());
@@ -262,8 +284,15 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
im = makeMonitor(resourceName, myProp);
sm = im.getStateManager();
logger.debug(
- "\n\ntestSanityJmx restart with AdminState=unlocked\n"
- + "AdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
+ """
+
+
+ testSanityJmx restart with AdminState=unlocked
+ AdminState = {}
+ OpState() = {}
+ AvailStatus = {}
+ StandbyStatus = {}
+ """,
sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
assertEquals(StateManagement.UNLOCKED, sm.getAdminState());
@@ -313,7 +342,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
assertEquals(StateManagement.LOCKED, sm.getAdminState());
// test startTransaction. It should fail since it is locked
- assertThatThrownBy(im::startTransaction);
+ assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
sm.unlock();
logger.debug("\n\nsm.unlock()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
@@ -374,7 +403,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
assertEquals(StateManagement.HOT_STANDBY, sm.getStandbyStatus());
// test startTransaction. It should fail since it is standby
- assertThatThrownBy(im::startTransaction);
+ assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
sm.promote();
@@ -400,7 +429,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
// Test startTransaction. Should fail since standby status is cold
// standby
- assertThatThrownBy(im::startTransaction);
+ assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
sm.enableNoDependency();
@@ -410,7 +439,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
assertEquals(StateManagement.FAILED, sm.getAvailStatus());
// Test startTransaction. Should fail since standby status is cold
// standby
- assertThatThrownBy(im::startTransaction);
+ assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
sm.disableDependency();
sm.enableNotFailed();
@@ -423,7 +452,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
assertEquals(StateManagement.DEPENDENCY, sm.getAvailStatus());
// Test startTransaction. Should fail since standby status is cold
// standby
- assertThatThrownBy(im::startTransaction);
+ assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
sm.enableNoDependency();
logger.debug(
@@ -432,7 +461,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
assertEquals(StateManagement.ENABLED, sm.getOpState());
// test startTransaction. It should fail since standby status is hot
// standby
- assertThatThrownBy(im::startTransaction);
+ assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
logger.debug("\n\ntestIM: Exit\n\n");
}
@@ -490,7 +519,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
// to do it.
logger.debug("\n\nIntegrityMonitor.testSanityState: calling im.dependencyCheck()\n\n");
im.dependencyCheck();
- assertThatThrownBy(im::evaluateSanity);
+ assertThatThrownBy(im::evaluateSanity).isInstanceOf(IntegrityMonitorException.class);
logger.debug("\n\ntestSanityState: Exit\n\n");
}
@@ -539,9 +568,13 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
em.refresh(sme);
logger.debug(
- "??? -- Retrieve StateManagementEntity from database --\nsme.getResourceName() = {}\n"
- + "sme.getAdminState() = {}\nsme.getOpState() = {}\nsme.getAvailStatus() = {}\n"
- + "sme.getStandbyStatus() = {}",
+ """
+ ??? -- Retrieve StateManagementEntity from database --
+ sme.getResourceName() = {}
+ sme.getAdminState() = {}
+ sme.getOpState() = {}
+ sme.getAvailStatus() = {}
+ sme.getStandbyStatus() = {}""",
sme.getResourceName(), sme.getAdminState(), sme.getOpState(), sme.getAvailStatus(),
sme.getStandbyStatus());
@@ -577,9 +610,13 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
sme1 = (StateManagementEntity) resourceList1.get(0);
em.refresh(sme1);
logger.debug(
- "??? -- Retrieve StateManagementEntity from database --\nsme1.getResourceName() = {}\n"
- + "sme1.getAdminState() = {}\nsme1.getOpState() = {}\nsme1.getAvailStatus() = {}\n"
- + "sme1.getStandbyStatus() = {}",
+ """
+ ??? -- Retrieve StateManagementEntity from database --
+ sme1.getResourceName() = {}
+ sme1.getAdminState() = {}
+ sme1.getOpState() = {}
+ sme1.getAvailStatus() = {}
+ sme1.getStandbyStatus() = {}""",
sme1.getResourceName(), sme1.getAdminState(), sme1.getOpState(), sme1.getAvailStatus(),
sme1.getStandbyStatus());
@@ -648,7 +685,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
*/
waitCycles(DEPENDENCY_CHECK_CYCLES);
- assertThatThrownBy(im::evaluateSanity);
+ assertThatThrownBy(im::evaluateSanity).isInstanceOf(IntegrityMonitorException.class);
logger.debug("\n\ntestStateCheck: Exit\n\n");
}
@@ -804,8 +841,14 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
StateManagementEntity tmpSme = (StateManagementEntity) mySme;
em.refresh(tmpSme);
logger.debug(
- "\n ResourceName: {}\n AdminState: {}\n OpState: {}"
- + "\n AvailStatus: {}\n StandbyStatus: {}",
+ """
+
+ ResourceName: {}
+ AdminState: {}
+ OpState: {}
+ AvailStatus: {}
+ StandbyStatus: {}\
+ """,
tmpSme.getResourceName(), tmpSme.getAdminState(), tmpSme.getOpState(), tmpSme.getAvailStatus(),
tmpSme.getStandbyStatus());
}
@@ -827,8 +870,14 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
StateManagementEntity tmpSme = (StateManagementEntity) mySme;
em.refresh(tmpSme);
logger.debug(
- "\n ResourceName: {}" + "\n AdminState: {}" + "\n OpState: {}"
- + "\n AvailStatus: {}" + "\n StandbyStatus: {}",
+ """
+
+ ResourceName: {}
+ AdminState: {}
+ OpState: {}
+ AvailStatus: {}
+ StandbyStatus: {}\
+ """,
tmpSme.getResourceName(), tmpSme.getAdminState(), tmpSme.getOpState(), tmpSme.getAvailStatus(),
tmpSme.getStandbyStatus());
}
@@ -867,8 +916,14 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
em.refresh(tmpSme);
logger.debug(
- "\n (restart4) ResourceName: {}" + "\n AdminState: {}" + "\n OpState: {}"
- + "\n AvailStatus: {}" + "\n StandbyStatus: {}",
+ """
+
+ (restart4) ResourceName: {}
+ AdminState: {}
+ OpState: {}
+ AvailStatus: {}
+ StandbyStatus: {}\
+ """,
tmpSme.getResourceName(), tmpSme.getAdminState(), tmpSme.getOpState(), tmpSme.getAvailStatus(),
tmpSme.getStandbyStatus());
}
@@ -906,7 +961,7 @@ public class IntegrityMonitorTest extends IntegrityMonitorTestBase {
}
};
- Whitebox.setInternalState(IntegrityMonitor.class, IM_INSTANCE_FIELD, im);
+ ReflectionTestUtils.setField(IntegrityMonitor.class, IM_INSTANCE_FIELD, im);
// wait for the monitor thread to start
waitCycles(1);
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
index 1bb7cd96..1433c20d 100644
--- 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
@@ -3,6 +3,7 @@
* Integrity Audit
* ================================================================================
* Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Modificaitons 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.
@@ -22,21 +23,21 @@ package org.onap.policy.common.im;
import static org.junit.Assert.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 javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
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.powermock.reflect.Whitebox;
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
@@ -152,7 +153,7 @@ public class IntegrityMonitorTestBase {
IntegrityMonitor.setUnitTesting(true);
testTime = new TestTime();
- Whitebox.setInternalState(MonitorTime.class, TIME_INSTANCE_FIELD, testTime);
+ ReflectionTestUtils.setField(MonitorTime.class, TIME_INSTANCE_FIELD, testTime);
properties = new Properties();
properties.put(IntegrityMonitorProperties.DB_DRIVER, DB_DRIVER);
@@ -185,7 +186,7 @@ public class IntegrityMonitorTestBase {
systemProps.put(JMX_PORT_PROP, savedJmxPort);
}
- Whitebox.setInternalState(MonitorTime.class, TIME_INSTANCE_FIELD, savedTime);
+ ReflectionTestUtils.setField(MonitorTime.class, TIME_INSTANCE_FIELD, savedTime);
IntegrityMonitor.setUnitTesting(false);
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
index 3e482ddf..34ff25a7 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -22,10 +23,8 @@ package org.onap.policy.common.im;
import static org.junit.Assert.assertEquals;
+import jakarta.persistence.Query;
import java.util.List;
-
-import javax.persistence.Query;
-
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -37,7 +36,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StateManagementEntityTest extends IntegrityMonitorTestBase {
- private static Logger logger = LoggerFactory.getLogger(StateManagementEntityTest.class);
+ private static final Logger logger = LoggerFactory.getLogger(StateManagementEntityTest.class);
/**
* Set up for the test class.
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
index dccef6ae..443bcdd3 100644
--- 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
@@ -2,7 +2,9 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020 Bell Canada. 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.
@@ -28,13 +30,12 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.PersistenceException;
-import javax.persistence.QueryTimeoutException;
-import javax.persistence.TypedQuery;
-
+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.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -57,7 +58,7 @@ public class StateManagementTest extends IntegrityMonitorTestBase {
private static final String UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE = "unlocked,enabled,null,providingservice";
private static final String TEST_RESOURCE_NAME = "test_resource1";
- private static Logger logger = LoggerFactory.getLogger(StateManagementTest.class);
+ private static final Logger logger = LoggerFactory.getLogger(StateManagementTest.class);
//
@BeforeClass
@@ -84,143 +85,12 @@ public class StateManagementTest extends IntegrityMonitorTestBase {
@Test
public void test() throws Exception {
logger.info("\n\nlogger.infor StateManagementTest: Entering\n\n");
- String resourceName = TEST_RESOURCE_NAME;
// These parameters are in a properties file
try {
- final StateManagement sm = new StateManagement(emf, resourceName);
-
- 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");
- assertThatThrownBy(() -> {
- sm.disableFailed();
- sm.lock();
-
- sm.promote();
- });
- 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);
- 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");
- resourceName = "test_resource2";
- final StateManagement sm2 = new StateManagement(emf, resourceName);
- 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));
-
- // D3 If demote() is called while standbyStatus is null and
- // adminState is locked or opState is disabled,
- // the state shall transition to coldstandby
- logger.info("\n??? demote() test case D3");
- resourceName = "test_resource3";
- final StateManagement sm3 = new StateManagement(emf, resourceName);
- 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");
- resourceName = "test_resource4";
- final StateManagement sm4 = new StateManagement(emf, resourceName);
- 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);
- assertEquals(UNLOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(sm));
-
+ 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;
@@ -229,6 +99,136 @@ public class StateManagementTest extends IntegrityMonitorTestBase {
logger.info("\n\nStateManagementTest: Exit\n\n");
}
+ private void test_1(final StateManagement sm) throws StateManagementException, 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 StateManagementException, 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(expected = StateManagementException.class)
@SuppressWarnings("unchecked")
public void test_StateManagementInitialization_ThrowException_ifEntityManagerCreateQuerythrowsAnyException()
@@ -245,7 +245,7 @@ public class StateManagementTest extends IntegrityMonitorTestBase {
@Test(expected = StateManagementException.class)
@SuppressWarnings("unchecked")
- public void test_StateManagementInitialization_ThrowStateManagementException_ifEntityManagerthrowsAnyException()
+ public void test_StateManagementInitialization_ThrowStateManagementException_ifEntityManagerThrowsAnyException()
throws Exception {
final EntityManager mockedEm = getMockedEntityManager();
final EntityManagerFactory mockedEmf = getMockedEntityManagerFactory(mockedEm);
@@ -288,16 +288,9 @@ public class StateManagementTest extends IntegrityMonitorTestBase {
return null;
}
- final StringBuilder b = new StringBuilder();
-
- b.append(sm.getAdminState());
- b.append(',');
- b.append(sm.getOpState());
- b.append(',');
- b.append(sm.getAvailStatus());
- b.append(',');
- b.append(sm.getStandbyStatus());
-
- return b.toString();
+ 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
index 6d11b30b..7cd7f4c2 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,8 +23,6 @@ package org.onap.policy.common.im;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/*
* All JUnits are designed to run in the local development environment
@@ -49,2091 +47,3499 @@ public class StateTransitionTest {
private static final String ENABLE_NOT_FAILED = "enableNotFailed";
private static final String ENABLED = "enabled";
private static final String FAILED = "failed";
- private static Logger logger = LoggerFactory.getLogger(StateTransitionTest.class);
@Test
- public void test() throws StateTransitionException {
- logger.info("\n\nlogger.infor StateTransitionTest: Entering\n\n");
- logger.info("??? create a new StateTransition");
- StateTransition st = new StateTransition();
+ public void testBad() throws StateTransitionException {
+ // bad test case
+ assertEquals("coldstandby,locked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, "lock"));
- StateElement se = null;
+ }
- // bad test case
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, "lock");
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test1() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", "lock"));
+
+ }
+
+ @Test
+ public void test2() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test3() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, ENABLED, "null", "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test4() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test5() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, "null", "null", DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test6() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", "null", ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test7() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", PROMOTE));
+
+ }
+
+ @Test
+ public void test8() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test9() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test10() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test11() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test12() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test13() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test14() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test15() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test16() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test17() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test18() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test19() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test20() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test21() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test22() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test23() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test24() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test25() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test26() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test27() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test28() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test29() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test30() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test31() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, PROMOTE));
+
+ }
+
+ @Test
+ public void test32() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test33() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test34() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test35() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, ENABLED, FAILED, "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test36() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test37() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, FAILED, "null", DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test38() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, "null", ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test39() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", PROMOTE));
+
+ }
+
+ @Test
+ public void test40() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test41() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test42() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test43() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test44() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test45() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test46() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test47() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test48() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test49() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test50() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test51() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test52() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test53() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test54() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test55() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test56() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test57() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test58() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test59() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test60() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test61() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test62() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test63() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, PROMOTE));
+
+ }
+
+ @Test
+ public void test64() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test65() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test66() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test67() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test68() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test69() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test70() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test71() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", PROMOTE));
+
+ }
+
+ @Test
+ public void test72() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test73() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test74() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test75() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test76() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test77() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test78() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test79() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test80() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test81() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test82() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test83() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test84() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test85() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test86() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test87() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test88() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test89() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test90() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test91() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test92() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test93() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test94() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test95() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE));
+
+ }
+
+ @Test
+ public void test96() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test97() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test98() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test99() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test100() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test101() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test102() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test103() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", PROMOTE));
+
+ }
+
+ @Test
+ public void test104() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test105() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test106() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test107() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test108() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test109() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test110() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test111() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test112() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test113() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test114() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test115() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test116() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test117() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test118() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test119() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test120() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test121() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test122() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test123() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test124() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test125() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test126() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test127() throws StateTransitionException {
+ assertEquals("providingservice,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE));
+
+ }
+
+ @Test
+ public void test128() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test129() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test130() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test131() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, "null", "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test132() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, DISABLED, "null", "null", ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test133() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, "null", "null", DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test134() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", "null", ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test135() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, "null", "null", PROMOTE));
+
+ }
+
+ @Test
+ public void test136() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test137() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test138() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test139() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test140() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test141() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test142() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test143() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test144() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test145() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test146() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test147() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test148() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test149() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test150() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test151() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test152() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test153() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test154() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test155() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test156() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test157() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test158() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test159() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, PROMOTE));
+
+ }
+
+ @Test
+ public void test160() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,",
+ makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test161() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, FAILED, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test162() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, FAILED, "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test163() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, FAILED, "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test164() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, DISABLED, FAILED, "null", ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test165() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, "null", DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test166() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, "null", ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test167() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, FAILED, "null", PROMOTE));
+
+ }
+
+ @Test
+ public void test168() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, FAILED, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test169() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test170() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test171() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test172() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test173() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test174() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test175() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test176() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test177() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test178() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test179() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test180() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test181() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test182() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test183() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test184() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test185() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test186() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test187() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test188() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test189() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test190() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test191() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, PROMOTE));
+
+ }
+
+ @Test
+ public void test192() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test193() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test194() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,", makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test195() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test196() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED));
+
+ }
- logger.info("??? StateTransition testcase 1");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", "null", "lock");
- assertEquals("null,locked,enabled,null,", makeString(se));
+ @Test
+ public void test197() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 2");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", "null", UNLOCK);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 3");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", "null", DISABLE_FAILED);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test198() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 4");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", "null", ENABLE_NOT_FAILED);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 5");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", "null", DISABLE_DEPENDENCY);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test199() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", PROMOTE));
- logger.info("??? StateTransition testcase 6");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 7");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", "null", PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test200() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", DEMOTE));
- logger.info("??? StateTransition testcase 8");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", "null", DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 9");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test201() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 10");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 11");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test202() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 12");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 13");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test203() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 14");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 15");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test204() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 16");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 17");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test205() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 18");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", HOTSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 19");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test206() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 20");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 21");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test207() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 22");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 23");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", HOTSTANDBY, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test208() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 24");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 25");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test209() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 26");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, UNLOCK);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 27");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test210() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 28");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 29");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test211() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 30");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 31");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test212() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 32");
- se = st.getEndingState(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 33");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, "null", DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test213() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 34");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, "null", UNLOCK);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 35");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, "null", DISABLE_FAILED);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test214() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 36");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, "null", ENABLE_NOT_FAILED);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 37");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, "null", DISABLE_DEPENDENCY);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test215() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 38");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 39");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, "null", PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test216() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 40");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, "null", DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 41");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test217() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 42");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 43");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test218() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK));
- logger.info("??? StateTransition testcase 44");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 45");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test219() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 46");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 47");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test220() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 48");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 49");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test221() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 50");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 51");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test222() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 52");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 53");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test223() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE));
- logger.info("??? StateTransition testcase 54");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 55");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test224() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 56");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 57");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test225() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE));
- logger.info("??? StateTransition testcase 58");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, UNLOCK);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 59");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test226() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", UNLOCK));
- logger.info("??? StateTransition testcase 60");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 61");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test227() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED));
- logger.info("??? StateTransition testcase 62");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 63");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test228() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 64");
- se = st.getEndingState(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 65");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, "null", DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test229() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 66");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, "null", UNLOCK);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 67");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, "null", DISABLE_FAILED);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test230() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 68");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 69");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test231() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", PROMOTE));
- logger.info("??? StateTransition testcase 70");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 71");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, "null", PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test232() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE));
- logger.info("??? StateTransition testcase 72");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, "null", DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 73");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test233() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 74");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 75");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test234() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test235() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test236() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test237() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 76");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 77");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test238() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 78");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 79");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test239() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 80");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 81");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test240() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 82");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 83");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test241() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 84");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 85");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("hotstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test242() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 86");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
+
+ @Test
+ public void test243() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test244() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test245() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test246() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test247() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test248() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test249() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test250() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test251() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test252() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test253() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test254() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test255() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE));
+
+ }
+
+ @Test
+ public void test256() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test257() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test258() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test259() throws StateTransitionException {
+ assertEquals("null,locked,disabled,failed,", makeString(LOCKED, ENABLED, "null", "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test260() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test261() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, "null", "null", DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test262() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test263() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, "null", "null", PROMOTE));
+
+ }
+
+ @Test
+ public void test264() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test265() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test266() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, "null", COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test267() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test268() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test269() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test270() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test271() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, "null", COLDSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test272() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test273() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test274() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, "null", HOTSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test275() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test276() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test277() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test278() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test279() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, "null", HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test280() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test281() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test282() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test283() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test284() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test285() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test286() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test287() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, PROMOTE));
+
+ }
+
+ @Test
+ public void test288() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test289() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test290() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", UNLOCK));
+
+ }
+
+ @Test
+ public void test291() throws StateTransitionException {
+ assertEquals("null,locked,disabled,failed,", makeString(LOCKED, ENABLED, FAILED, "null", DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test292() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test293() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, FAILED, "null", DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test294() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test295() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, FAILED, "null", PROMOTE));
+
+ }
+
+ @Test
+ public void test296() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", DEMOTE));
+
+ }
+
+ @Test
+ public void test297() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test298() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test299() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test300() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test301() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test302() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test303() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test304() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test305() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test306() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, UNLOCK));
+
+ }
+
+ @Test
+ public void test307() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test308() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
+
+ }
+
+ @Test
+ public void test309() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test310() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
+
+ }
+
+ @Test
+ public void test311() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, PROMOTE));
+
+ }
+
+ @Test
+ public void test312() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE));
+
+ }
+
+ @Test
+ public void test313() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
+
+ }
+
+ @Test
+ public void test314() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, UNLOCK));
+
+ }
+
+ @Test
+ public void test315() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
+
+ }
+
+ @Test
+ public void test316() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 87");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 88");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test317() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 89");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 90");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test318() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 91");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 92");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test319() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, PROMOTE));
- logger.info("??? StateTransition testcase 93");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 94");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test320() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 95");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 96");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test321() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", DEMOTE));
- logger.info("??? StateTransition testcase 97");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 98");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", UNLOCK);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test322() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", UNLOCK));
- logger.info("??? StateTransition testcase 99");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 100");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test323() throws StateTransitionException {
+ assertEquals("null,locked,disabled,failed,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", DISABLE_FAILED));
- logger.info("??? StateTransition testcase 101");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 102");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test324() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 103");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 104");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test325() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 105");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 106");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test326() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 107");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 108");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test327() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, DEPENDENCY, "null", PROMOTE));
- logger.info("??? StateTransition testcase 109");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 110");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test328() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", DEMOTE));
- logger.info("??? StateTransition testcase 111");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 112");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test329() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 113");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 114");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test330() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 115");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 116");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test331() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 117");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 118");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test332() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 119");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 120");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test333() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 121");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 122");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test334() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 123");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 124");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- ENABLE_NOT_FAILED);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
-
- logger.info("??? StateTransition testcase 125");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
-
- logger.info("??? StateTransition testcase 126");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- ENABLE_NO_DEPENDENCY);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test335() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 127");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE);
- assertEquals("providingservice,unlocked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 128");
- se = st.getEndingState(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test336() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 129");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", "null", DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 130");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", "null", UNLOCK);
- assertEquals("null,unlocked,disabled,null,", makeString(se));
+ @Test
+ public void test337() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 131");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", "null", DISABLE_FAILED);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 132");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", "null", ENABLE_NOT_FAILED);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test338() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 133");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", "null", DISABLE_DEPENDENCY);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 134");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test339() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 135");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", "null", PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 136");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", "null", DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ @Test
+ public void test340() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 137");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 138");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", COLDSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ @Test
+ public void test341() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 139");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 140");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test342() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 141");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 142");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test343() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 143");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 144");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ @Test
+ public void test344() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 145");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 146");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", HOTSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ @Test
+ public void test345() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 147");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 148");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test346() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK));
- logger.info("??? StateTransition testcase 149");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 150");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test347() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 151");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 152");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ @Test
+ public void test348() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 153");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 154");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ @Test
+ public void test349() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 155");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 156");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test350() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 157");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 158");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test351() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE));
- logger.info("??? StateTransition testcase 159");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 160");
- se = st.getEndingState(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ @Test
+ public void test352() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 161");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, "null", DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 162");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, "null", UNLOCK);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test353() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE));
- logger.info("??? StateTransition testcase 163");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, "null", DISABLE_FAILED);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 164");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, "null", ENABLE_NOT_FAILED);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test354() throws StateTransitionException {
+ assertEquals("null,unlocked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", UNLOCK));
- logger.info("??? StateTransition testcase 165");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, "null", DISABLE_DEPENDENCY);
- assertEquals("null,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 166");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test355() throws StateTransitionException {
+ assertEquals("null,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED));
- logger.info("??? StateTransition testcase 167");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, "null", PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 168");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, "null", DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test356() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 169");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 170");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test357() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 171");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 172");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test358() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 173");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 174");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test359() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", PROMOTE));
- logger.info("??? StateTransition testcase 175");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 176");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test360() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE));
- logger.info("??? StateTransition testcase 177");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 178");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test361() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 179");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 180");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test362() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 181");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 182");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test363() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 183");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 184");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test364() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 185");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 186");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test365() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 187");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 188");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test366() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 189");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 190");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test367() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 191");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 192");
- se = st.getEndingState(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ @Test
+ public void test368() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 193");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, "null", DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 194");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, "null", UNLOCK);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test369() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 195");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, "null", DISABLE_FAILED);
- assertEquals("null,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 196");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test370() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 197");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 198");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test371() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 199");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, "null", PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 200");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, "null", DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test372() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 201");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 202");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test373() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 203");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 204");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test374() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 205");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 206");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test375() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 207");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 208");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test376() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 209");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 210");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test377() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 211");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 212");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test378() throws StateTransitionException {
+ assertEquals("hotstandby,unlocked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK));
- logger.info("??? StateTransition testcase 213");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 214");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test379() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 215");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 216");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test380() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 217");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 218");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test381() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 219");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 220");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test382() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 221");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 222");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test383() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE));
- logger.info("??? StateTransition testcase 223");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 224");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test384() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 225");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 226");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", UNLOCK);
- assertEquals("null,unlocked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test385() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", "null", DEMOTE));
- logger.info("??? StateTransition testcase 227");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED);
- assertEquals("null,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 228");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ @Test
+ public void test386() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,null,", makeString(LOCKED, DISABLED, "null", "null", UNLOCK));
- logger.info("??? StateTransition testcase 229");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY);
- assertEquals("null,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 230");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 231");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException", makeString(se));
-
- logger.info("??? StateTransition testcase 232");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 233");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 234");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 235");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 236");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
-
- logger.info("??? StateTransition testcase 237");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 238");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY,
- ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 239");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException", makeString(se));
-
- logger.info("??? StateTransition testcase 240");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 241");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 242");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 243");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 244");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
-
- logger.info("??? StateTransition testcase 245");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 246");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 247");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException", makeString(se));
-
- logger.info("??? StateTransition testcase 248");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 249");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 250");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 251");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- DISABLE_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 252");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- ENABLE_NOT_FAILED);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
-
- logger.info("??? StateTransition testcase 253");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- DISABLE_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 254");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 255");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException", makeString(se));
-
- logger.info("??? StateTransition testcase 256");
- se = st.getEndingState(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 257");
- se = st.getEndingState(LOCKED, ENABLED, "null", "null", DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
-
- logger.info("??? StateTransition testcase 258");
- se = st.getEndingState(LOCKED, ENABLED, "null", "null", UNLOCK);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
-
- logger.info("??? StateTransition testcase 259");
- se = st.getEndingState(LOCKED, ENABLED, "null", "null", DISABLE_FAILED);
- assertEquals("null,locked,disabled,failed,", makeString(se));
-
- logger.info("??? StateTransition testcase 260");
- se = st.getEndingState(LOCKED, ENABLED, "null", "null", ENABLE_NOT_FAILED);
- assertEquals("null,locked,enabled,null,", makeString(se));
-
- logger.info("??? StateTransition testcase 261");
- se = st.getEndingState(LOCKED, ENABLED, "null", "null", DISABLE_DEPENDENCY);
- assertEquals("null,locked,disabled,dependency,", makeString(se));
-
- logger.info("??? StateTransition testcase 262");
- se = st.getEndingState(LOCKED, ENABLED, "null", "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ @Test
+ public void test387() throws StateTransitionException {
+ assertEquals("null,locked,disabled,failed,", makeString(LOCKED, DISABLED, "null", "null", DISABLE_FAILED));
- logger.info("??? StateTransition testcase 263");
- se = st.getEndingState(LOCKED, ENABLED, "null", "null", PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 264");
- se = st.getEndingState(LOCKED, ENABLED, "null", "null", DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test388() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(LOCKED, DISABLED, "null", "null", ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 265");
- se = st.getEndingState(LOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 266");
- se = st.getEndingState(LOCKED, ENABLED, "null", COLDSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test389() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, "null", "null", DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 267");
- se = st.getEndingState(LOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 268");
- se = st.getEndingState(LOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test390() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(LOCKED, DISABLED, "null", "null", ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 269");
- se = st.getEndingState(LOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 270");
- se = st.getEndingState(LOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test391() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,StandbyStatusException",
+ makeString(LOCKED, DISABLED, "null", "null", PROMOTE));
- logger.info("??? StateTransition testcase 271");
- se = st.getEndingState(LOCKED, ENABLED, "null", COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 272");
- se = st.getEndingState(LOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test392() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", "null", DEMOTE));
- logger.info("??? StateTransition testcase 273");
- se = st.getEndingState(LOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 274");
- se = st.getEndingState(LOCKED, ENABLED, "null", HOTSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test393() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 275");
- se = st.getEndingState(LOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 276");
- se = st.getEndingState(LOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test394() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,", makeString(LOCKED, DISABLED, "null", COLDSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 277");
- se = st.getEndingState(LOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 278");
- se = st.getEndingState(LOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test395() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 279");
- se = st.getEndingState(LOCKED, ENABLED, "null", HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 280");
- se = st.getEndingState(LOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test396() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 281");
- se = st.getEndingState(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 282");
- se = st.getEndingState(LOCKED, ENABLED, "null", PROVIDINGSERVICE, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test397() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 283");
- se = st.getEndingState(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 284");
- se = st.getEndingState(LOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test398() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 285");
- se = st.getEndingState(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 286");
- se = st.getEndingState(LOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test399() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,StandbyStatusException",
+ makeString(LOCKED, DISABLED, "null", COLDSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 287");
- se = st.getEndingState(LOCKED, ENABLED, "null", PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 288");
- se = st.getEndingState(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test400() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 289");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, "null", DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 290");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, "null", UNLOCK);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test401() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 291");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, "null", DISABLE_FAILED);
- assertEquals("null,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 292");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, "null", ENABLE_NOT_FAILED);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ @Test
+ public void test402() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,", makeString(LOCKED, DISABLED, "null", HOTSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 293");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, "null", DISABLE_DEPENDENCY);
- assertEquals("null,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 294");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ @Test
+ public void test403() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 295");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, "null", PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 296");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, "null", DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test404() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 297");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 298");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, COLDSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test405() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 299");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 300");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test406() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 301");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 302");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test407() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,StandbyStatusException",
+ makeString(LOCKED, DISABLED, "null", HOTSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 303");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 304");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test408() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 305");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 306");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, HOTSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test409() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,",
+ makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 307");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 308");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test410() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,null,",
+ makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, UNLOCK));
- logger.info("??? StateTransition testcase 309");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 310");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test411() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 311");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 312");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test412() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 313");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 314");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test413() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 315");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 316");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test414() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 317");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 318");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test415() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,StandbyStatusException",
+ makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, PROMOTE));
- logger.info("??? StateTransition testcase 319");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 320");
- se = st.getEndingState(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test416() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,null,",
+ makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 321");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, "null", DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 322");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, "null", UNLOCK);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test417() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, "null", DEMOTE));
- logger.info("??? StateTransition testcase 323");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, "null", DISABLE_FAILED);
- assertEquals("null,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 324");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ @Test
+ public void test418() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, "null", UNLOCK));
- logger.info("??? StateTransition testcase 325");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY);
- assertEquals("null,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 326");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ @Test
+ public void test419() throws StateTransitionException {
+ assertEquals("null,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, "null", DISABLE_FAILED));
- logger.info("??? StateTransition testcase 327");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, "null", PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 328");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, "null", DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test420() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,", makeString(LOCKED, DISABLED, FAILED, "null", ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 329");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 330");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test421() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, FAILED, "null", DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 331");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 332");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test422() throws StateTransitionException {
+ assertEquals("null,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, "null", ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 333");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 334");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test423() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException",
+ makeString(LOCKED, DISABLED, FAILED, "null", PROMOTE));
- logger.info("??? StateTransition testcase 335");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 336");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test424() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, "null", DEMOTE));
- logger.info("??? StateTransition testcase 337");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 338");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test425() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 339");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 340");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test426() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 341");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 342");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test427() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 343");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 344");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test428() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 345");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 346");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test429() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 347");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 348");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test430() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 349");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 350");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test431() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException",
+ makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 351");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 352");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test432() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 353");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 354");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", UNLOCK);
- assertEquals("null,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test433() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 355");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED);
- assertEquals("null,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 356");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ @Test
+ public void test434() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 357");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY);
- assertEquals("null,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 358");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ @Test
+ public void test435() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 359");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 360");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test436() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 361");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 362");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test437() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 363");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 364");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test438() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 365");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 366");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test439() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException",
+ makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 367");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 368");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test440() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 369");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 370");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test441() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 371");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 372");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test442() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, UNLOCK));
- logger.info("??? StateTransition testcase 373");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 374");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test443() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 375");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ }
- logger.info("??? StateTransition testcase 376");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test444() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 377");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 378");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK);
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(se));
+ @Test
+ public void test445() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 379");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 380");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ @Test
+ public void test446() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 381");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
-
- logger.info("??? StateTransition testcase 382");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 383");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException", makeString(se));
+ @Test
+ public void test447() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException",
+ makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, PROMOTE));
- logger.info("??? StateTransition testcase 384");
- se = st.getEndingState(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 385");
- se = st.getEndingState(LOCKED, DISABLED, "null", "null", DEMOTE);
- assertEquals("coldstandby,locked,disabled,null,", makeString(se));
+ @Test
+ public void test448() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 386");
- se = st.getEndingState(LOCKED, DISABLED, "null", "null", UNLOCK);
- assertEquals("null,unlocked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 387");
- se = st.getEndingState(LOCKED, DISABLED, "null", "null", DISABLE_FAILED);
- assertEquals("null,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test449() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, "null", DEMOTE));
- logger.info("??? StateTransition testcase 388");
- se = st.getEndingState(LOCKED, DISABLED, "null", "null", ENABLE_NOT_FAILED);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 389");
- se = st.getEndingState(LOCKED, DISABLED, "null", "null", DISABLE_DEPENDENCY);
- assertEquals("null,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test450() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,", makeString(LOCKED, DISABLED, DEPENDENCY, "null", UNLOCK));
- logger.info("??? StateTransition testcase 390");
- se = st.getEndingState(LOCKED, DISABLED, "null", "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 391");
- se = st.getEndingState(LOCKED, DISABLED, "null", "null", PROMOTE);
- assertEquals("coldstandby,locked,disabled,null,StandbyStatusException", makeString(se));
+ @Test
+ public void test451() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, "null", DISABLE_FAILED));
- logger.info("??? StateTransition testcase 392");
- se = st.getEndingState(LOCKED, DISABLED, "null", "null", DEMOTE);
- assertEquals("coldstandby,locked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 393");
- se = st.getEndingState(LOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,null,", makeString(se));
+ @Test
+ public void test452() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 394");
- se = st.getEndingState(LOCKED, DISABLED, "null", COLDSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 395");
- se = st.getEndingState(LOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test453() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 396");
- se = st.getEndingState(LOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 397");
- se = st.getEndingState(LOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test454() throws StateTransitionException {
+ assertEquals("null,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 398");
- se = st.getEndingState(LOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 399");
- se = st.getEndingState(LOCKED, DISABLED, "null", COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,disabled,null,StandbyStatusException", makeString(se));
+ @Test
+ public void test455() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException",
+ makeString(LOCKED, DISABLED, DEPENDENCY, "null", PROMOTE));
- logger.info("??? StateTransition testcase 400");
- se = st.getEndingState(LOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 401");
- se = st.getEndingState(LOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,null,", makeString(se));
+ @Test
+ public void test456() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, "null", DEMOTE));
- logger.info("??? StateTransition testcase 402");
- se = st.getEndingState(LOCKED, DISABLED, "null", HOTSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 403");
- se = st.getEndingState(LOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test457() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 404");
- se = st.getEndingState(LOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 405");
- se = st.getEndingState(LOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test458() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 406");
- se = st.getEndingState(LOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 407");
- se = st.getEndingState(LOCKED, DISABLED, "null", HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,disabled,null,StandbyStatusException", makeString(se));
+ @Test
+ public void test459() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 408");
- se = st.getEndingState(LOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 409");
- se = st.getEndingState(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,disabled,null,", makeString(se));
+ @Test
+ public void test460() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 410");
- se = st.getEndingState(LOCKED, DISABLED, "null", PROVIDINGSERVICE, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 411");
- se = st.getEndingState(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test461() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 412");
- se = st.getEndingState(LOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 413");
- se = st.getEndingState(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test462() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 414");
- se = st.getEndingState(LOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 415");
- se = st.getEndingState(LOCKED, DISABLED, "null", PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,locked,disabled,null,StandbyStatusException", makeString(se));
+ @Test
+ public void test463() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException",
+ makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 416");
- se = st.getEndingState(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,disabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 417");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, "null", DEMOTE);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test464() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 418");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, "null", UNLOCK);
- assertEquals("null,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 419");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, "null", DISABLE_FAILED);
- assertEquals("null,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test465() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 420");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, "null", ENABLE_NOT_FAILED);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 421");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, "null", DISABLE_DEPENDENCY);
- assertEquals("null,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test466() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 422");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 423");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, "null", PROMOTE);
- assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException", makeString(se));
+ @Test
+ public void test467() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 424");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, "null", DEMOTE);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 425");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test468() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 426");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, COLDSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 427");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test469() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 428");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 429");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test470() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 430");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 431");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException", makeString(se));
+ @Test
+ public void test471() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException",
+ makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 432");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 433");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test472() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 434");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, HOTSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 435");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test473() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 436");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 437");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test474() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK));
- logger.info("??? StateTransition testcase 438");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 439");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException", makeString(se));
+ @Test
+ public void test475() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 440");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 441");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test476() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 442");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 443");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ @Test
+ public void test477() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 444");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 445");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test478() throws StateTransitionException {
+ assertEquals("coldstandby,locked,enabled,null,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 446");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 447");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException", makeString(se));
+ @Test
+ public void test479() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException",
+ makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE));
- logger.info("??? StateTransition testcase 448");
- se = st.getEndingState(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 449");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, "null", DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test480() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 450");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, "null", UNLOCK);
- assertEquals("null,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 451");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, "null", DISABLE_FAILED);
- assertEquals("null,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test481() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE));
- logger.info("??? StateTransition testcase 452");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED);
- assertEquals("null,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 453");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY);
- assertEquals("null,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test482() throws StateTransitionException {
+ assertEquals("null,unlocked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", UNLOCK));
- logger.info("??? StateTransition testcase 454");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 455");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, "null", PROMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException", makeString(se));
+ @Test
+ public void test483() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED));
- logger.info("??? StateTransition testcase 456");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, "null", DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 457");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test484() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 458");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 459");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test485() throws StateTransitionException {
+ assertEquals("null,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 460");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 461");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test486() throws StateTransitionException {
+ assertEquals("null,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 462");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 463");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException", makeString(se));
+ @Test
+ public void test487() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", PROMOTE));
- logger.info("??? StateTransition testcase 464");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 465");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test488() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE));
- logger.info("??? StateTransition testcase 466");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 467");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test489() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 468");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 469");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test490() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 470");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 471");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException", makeString(se));
+ @Test
+ public void test491() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 472");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 473");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test492() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 474");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 475");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test493() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 476");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 477");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ @Test
+ public void test494() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 478");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,enabled,null,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 479");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException", makeString(se));
+ @Test
+ public void test495() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 480");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 481");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test496() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 482");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", UNLOCK);
- assertEquals("null,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 483");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED);
- assertEquals("null,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test497() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 484");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED);
- assertEquals("null,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 485");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY);
- assertEquals("null,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test498() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK));
- logger.info("??? StateTransition testcase 486");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY);
- assertEquals("null,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 487");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", PROMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException", makeString(se));
+ @Test
+ public void test499() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 488");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 489");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test500() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 490");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 491");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test501() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 492");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 493");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test502() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 494");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 495");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException", makeString(se));
+ @Test
+ public void test503() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE));
- logger.info("??? StateTransition testcase 496");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 497");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test504() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
- logger.info("??? StateTransition testcase 498");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 499");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test505() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
- logger.info("??? StateTransition testcase 500");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 501");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test506() throws StateTransitionException {
+ assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK));
- logger.info("??? StateTransition testcase 502");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 503");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException", makeString(se));
+ @Test
+ public void test507() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
- logger.info("??? StateTransition testcase 504");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 505");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test508() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
- logger.info("??? StateTransition testcase 506");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK);
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 507");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test509() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
- logger.info("??? StateTransition testcase 508");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- ENABLE_NOT_FAILED);
- assertEquals("coldstandby,locked,disabled,dependency,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 509");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- DISABLE_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ @Test
+ public void test510() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
- logger.info("??? StateTransition testcase 510");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE,
- ENABLE_NO_DEPENDENCY);
- assertEquals("coldstandby,locked,disabled,failed,", makeString(se));
+ }
- logger.info("??? StateTransition testcase 511");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException", makeString(se));
+ @Test
+ public void test511() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE));
- logger.info("??? StateTransition testcase 512");
- se = st.getEndingState(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE);
- assertEquals("coldstandby,locked,disabled,dependency,failed,", makeString(se));
+ }
- logger.info("\n\nStateTransitionTest: Exit\n\n");
+ @Test
+ public void test512() throws StateTransitionException {
+ assertEquals("coldstandby,locked,disabled,dependency,failed,",
+ makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
}
/**
- * Converts a state element to a comma-separated string.
- *
- * @param se element to be converted
- * @return a string representing the element
+ * Converts a transition to a string.
*/
- private String makeString(StateElement se) {
+ 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;
}
diff --git a/policy-endpoints/pom.xml b/policy-endpoints/pom.xml
index d70399cd..c6dd4b6e 100644
--- a/policy-endpoints/pom.xml
+++ b/policy-endpoints/pom.xml
@@ -1,8 +1,9 @@
<!--
============LICENSE_START=======================================================
- Copyright (C) 2018 Ericsson. All rights reserved.
- Modifications Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2019 Nordix Foundation.
+ Copyright (C) 2022 Ericsson. All rights reserved.
+ Modifications Copyright (C) 2018-2022 AT&T Intellectual Property. All rights reserved.
+ Modifications Copyright (C) 2019-2024 Nordix Foundation.
+ Modifications Copyright (C) 2022 Bell Canada. 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.
@@ -19,54 +20,65 @@
SPDX-License-Identifier: Apache-2.0
============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">
-
+<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>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
<artifactId>policy-endpoints</artifactId>
-
<name>policy-endpoints</name>
<description>Endpoints</description>
<properties>
<cambria.version>1.2.1-oss</cambria.version>
- <http.client.version>4.5.5</http.client.version>
- <http.core.version>4.4.4</http.core.version>
</properties>
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.glassfish.jersey</groupId>
+ <artifactId>jersey-bom</artifactId>
+ <version>${version.jersey}</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
<dependencies>
<dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>capabilities</artifactId>
<version>${project.version}</version>
</dependency>
-
<dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>gson</artifactId>
<version>${project.version}</version>
</dependency>
-
<dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>utils</artifactId>
<version>${project.version}</version>
</dependency>
-
<dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>common-parameters</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>com.att.nsa</groupId>
<artifactId>cambriaClient</artifactId>
@@ -77,178 +89,101 @@
</exclusion>
</exclusions>
</dependency>
-
<dependency>
- <groupId>org.onap.dmaap.messagerouter.dmaapclient</groupId>
- <artifactId>dmaapClient</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- <exclusion>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- </exclusion>
- </exclusions>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
-
<dependency>
- <groupId>org.onap.aaf.authz</groupId>
- <artifactId>aaf-cadi-aaf</artifactId>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
</dependency>
-
<dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-server</artifactId>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
</dependency>
-
<dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-servlet</artifactId>
+ <groupId>com.fasterxml.jackson.module</groupId>
+ <artifactId>jackson-module-jakarta-xmlbind-annotations</artifactId>
</dependency>
-
<dependency>
- <groupId>org.glassfish.jersey.core</groupId>
- <artifactId>jersey-server</artifactId>
+ <groupId>com.fasterxml.jackson.dataformat</groupId>
+ <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
-
<dependency>
- <groupId>org.glassfish.jersey.containers</groupId>
- <artifactId>jersey-container-servlet-core</artifactId>
+ <groupId>org.glassfish.jaxb</groupId>
+ <artifactId>jaxb-runtime</artifactId>
</dependency>
-
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
- <artifactId>jersey-container-jetty-http</artifactId>
+ <artifactId>jersey-container-servlet</artifactId>
</dependency>
-
<dependency>
- <groupId>org.glassfish.jersey.core</groupId>
- <artifactId>jersey-client</artifactId>
+ <groupId>org.glassfish.jersey.media</groupId>
+ <artifactId>jersey-media-json-jackson</artifactId>
+ <version>${version.jersey}</version>
+ <scope>compile</scope>
</dependency>
-
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
- <artifactId>jersey-common</artifactId>
+ <artifactId>jersey-server</artifactId>
+ <version>${version.jersey}</version>
</dependency>
-
<dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
+ <groupId>org.glassfish.jersey.inject</groupId>
+ <artifactId>jersey-hk2</artifactId>
+ <version>${version.jersey}</version>
</dependency>
-
<dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
</dependency>
-
<dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
+ <groupId>org.apache.httpcomponents.core5</groupId>
+ <artifactId>httpcore5</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpcore</artifactId>
+ <groupId>jakarta.activation</groupId>
+ <artifactId>jakarta.activation-api</artifactId>
</dependency>
-
<dependency>
- <groupId>io.swagger</groupId>
- <artifactId>swagger-jersey2-jaxrs</artifactId>
+ <groupId>jakarta.inject</groupId>
+ <artifactId>jakarta.inject-api</artifactId>
</dependency>
-
<dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-collections4</artifactId>
- <version>4.1</version>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-servlet</artifactId>
</dependency>
-
<dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-security</artifactId>
</dependency>
-
<dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>utils-test</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
+ <groupId>org.apache.kafka</groupId>
+ <artifactId>kafka-clients</artifactId>
</dependency>
-
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-collections4</artifactId>
</dependency>
-
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito2</artifactId>
- <scope>test</scope>
+ <groupId>io.swagger.core.v3</groupId>
+ <artifactId>swagger-annotations</artifactId>
</dependency>
-
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
+ <groupId>io.opentelemetry.instrumentation</groupId>
+ <artifactId>opentelemetry-kafka-clients-2.6</artifactId>
</dependency>
-
<dependency>
- <groupId>org.glassfish.jersey.inject</groupId>
- <artifactId>jersey-hk2</artifactId>
+ <groupId>io.opentelemetry</groupId>
+ <artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>
-
<dependency>
- <groupId>com.openpojo</groupId>
- <artifactId>openpojo</artifactId>
+ <groupId>io.opentelemetry</groupId>
+ <artifactId>opentelemetry-sdk-extension-autoconfigure</artifactId>
</dependency>
-
<dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <scope>provided</scope>
+ <groupId>com.sun.xml.bind</groupId>
+ <artifactId>jaxb-impl</artifactId>
</dependency>
-
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>onap-java-style</id>
- <goals>
- <goal>check</goal>
- </goals>
- <phase>process-sources</phase>
- <configuration>
- <!-- Use Google Java Style Guide:
- https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml
- with minor changes -->
- <configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
- <!-- <sourceDirectory> is needed so that checkstyle ignores the generated sources directory -->
- <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
- <includeResources>true</includeResources>
- <includeTestSourceDirectory>true</includeTestSourceDirectory>
- <includeTestResources>true</includeTestResources>
- <excludes>
- </excludes>
- <consoleOutput>true</consoleOutput>
- <failsOnViolation>true</failsOnViolation>
- <violationSeverity>warning</violationSeverity>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.onap.oparent</groupId>
- <artifactId>checkstyle</artifactId>
- <version>${oparent.version}</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
- </plugin>
- </plugins>
- </build>
</project>
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/Topic.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/Topic.java
index 96c00c77..d09e7353 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/Topic.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/Topic.java
@@ -2,8 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (C) 2022,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.
@@ -22,7 +23,6 @@
package org.onap.policy.common.endpoints.event.comm;
import java.util.List;
-
import org.onap.policy.common.capabilities.Lockable;
import org.onap.policy.common.capabilities.Startable;
@@ -41,9 +41,9 @@ public interface Topic extends TopicRegisterable, Startable, Lockable {
*/
UEB,
/**
- * DMAAP Communication Infrastructure.
+ * KAFKA Communication Infrastructure.
*/
- DMAAP,
+ KAFKA,
/**
* NOOP for internal use only.
*/
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpoint.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpoint.java
index bb707523..8cae5bd1 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpoint.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpoint.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2022,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.
@@ -24,8 +25,8 @@ import java.util.List;
import java.util.Properties;
import org.onap.policy.common.capabilities.Lockable;
import org.onap.policy.common.capabilities.Startable;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSink;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSource;
+import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicSink;
+import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicSource;
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink;
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSource;
import org.onap.policy.common.endpoints.event.comm.bus.UebTopicSink;
@@ -34,7 +35,7 @@ import org.onap.policy.common.endpoints.parameters.TopicParameterGroup;
import org.onap.policy.common.endpoints.parameters.TopicParameters;
/**
- * Abstraction to managed the system's Networked Topic Endpoints, sources of all events input into
+ * Abstraction to manage the system's Networked Topic Endpoints, sources of all events input into
* the System.
*/
public interface TopicEndpoint extends Startable, Lockable {
@@ -140,24 +141,20 @@ public interface TopicEndpoint extends Startable, Lockable {
UebTopicSource getUebTopicSource(String topicName);
/**
- * Get the DMAAP Topic Source for the given topic name.
- *
- * @param topicName the topic name
+ * Get the Noop Source for the given topic name.
*
- * @return the DMAAP Topic Source
- * @throws IllegalStateException if the entity is in an invalid state, for example multiple
- * TopicReaders for a topic name and communication infrastructure
- * @throws IllegalArgumentException if invalid parameters are present
+ * @param topicName the topic name.
+ * @return the Noop Source.
*/
- DmaapTopicSource getDmaapTopicSource(String topicName);
+ NoopTopicSource getNoopTopicSource(String topicName);
/**
- * Get the Noop Source for the given topic name.
+ * Get the Kafka Source for the given topic name.
*
* @param topicName the topic name.
- * @return the Noop Source.
+ * @return the Kafka Source.
*/
- NoopTopicSource getNoopTopicSource(String topicName);
+ KafkaTopicSource getKafkaTopicSource(String topicName);
/**
* Get the Topic Sinks for the given topic name.
@@ -225,7 +222,7 @@ public interface TopicEndpoint extends Startable, Lockable {
NoopTopicSink getNoopTopicSink(String topicName);
/**
- * Get the DMAAP Topic Source for the given topic name.
+ * Get the KAFKA Topic Source for the given topic name.
*
* @param topicName the topic name
*
@@ -234,7 +231,7 @@ public interface TopicEndpoint extends Startable, Lockable {
* TopicReaders for a topic name and communication infrastructure
* @throws IllegalArgumentException if invalid parameters are present
*/
- DmaapTopicSink getDmaapTopicSink(String topicName);
+ KafkaTopicSink getKafkaTopicSink(String topicName);
/**
* Gets only the UEB Topic Sources.
@@ -244,11 +241,11 @@ public interface TopicEndpoint extends Startable, Lockable {
List<UebTopicSource> getUebTopicSources();
/**
- * Gets only the DMAAP Topic Sources.
+ * Gets only the KAFKA Topic Sources.
*
- * @return the DMAAP Topic Source List
+ * @return the KAFKA Topic Source List
*/
- List<DmaapTopicSource> getDmaapTopicSources();
+ List<KafkaTopicSource> getKafkaTopicSources();
/**
* Gets only the NOOP Topic Sources.
@@ -265,11 +262,11 @@ public interface TopicEndpoint extends Startable, Lockable {
List<UebTopicSink> getUebTopicSinks();
/**
- * Gets only the DMAAP Topic Sinks.
+ * Gets only the KAFKA Topic Sinks.
*
- * @return the DMAAP Topic Sink List
+ * @return the KAFKA Topic Sinks List
*/
- List<DmaapTopicSink> getDmaapTopicSinks();
+ List<KafkaTopicSink> getKafkaTopicSinks();
/**
* Gets only the NOOP Topic Sinks.
@@ -277,4 +274,5 @@ public interface TopicEndpoint extends Startable, Lockable {
* @return the NOOP Topic Sinks List
*/
List<NoopTopicSink> getNoopTopicSinks();
+
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointManager.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointManager.java
index c390afc6..fb18a307 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointManager.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointManager.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,8 +20,11 @@
package org.onap.policy.common.endpoints.event.comm;
+import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TopicEndpointManager {
/**
@@ -29,9 +32,4 @@ public class TopicEndpointManager {
*/
@Getter
private static TopicEndpoint manager = new TopicEndpointProxy();
-
-
- private TopicEndpointManager() {
- // do nothing
- }
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java
index 9aabad52..4ec8eb54 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2022-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.
@@ -20,15 +21,16 @@
package org.onap.policy.common.endpoints.event.comm;
-import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.Properties;
+import lombok.Getter;
import org.onap.policy.common.capabilities.Startable;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicFactories;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSink;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSource;
+import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicFactories;
+import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicSink;
+import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicSource;
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories;
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink;
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSource;
@@ -45,6 +47,7 @@ import org.slf4j.LoggerFactory;
* This implementation of the Topic Endpoint Manager, proxies operations to the appropriate
* implementation(s).
*/
+@Getter
class TopicEndpointProxy implements TopicEndpoint {
/**
* Logger.
@@ -71,9 +74,9 @@ class TopicEndpointProxy implements TopicEndpoint {
@Override
public List<Topic> addTopics(TopicParameterGroup params) {
List<TopicParameters> sinks =
- (params.getTopicSinks() != null ? params.getTopicSinks() : Collections.emptyList());
+ (params.getTopicSinks() != null ? params.getTopicSinks() : Collections.emptyList());
List<TopicParameters> sources =
- (params.getTopicSources() != null ? params.getTopicSources() : Collections.emptyList());
+ (params.getTopicSources() != null ? params.getTopicSources() : Collections.emptyList());
List<Topic> topics = new ArrayList<>(sinks.size() + sources.size());
topics.addAll(addTopicSources(sources));
@@ -90,15 +93,15 @@ class TopicEndpointProxy implements TopicEndpoint {
case UEB:
sources.add(UebTopicFactories.getSourceFactory().build(param));
break;
- case DMAAP:
- sources.add(DmaapTopicFactories.getSourceFactory().build(param));
+ case KAFKA:
+ sources.add(KafkaTopicFactories.getSourceFactory().build(param));
break;
case NOOP:
sources.add(NoopTopicFactories.getSourceFactory().build(param));
break;
default:
logger.debug("Unknown source type {} for topic: {}", param.getTopicCommInfrastructure(),
- param.getTopic());
+ param.getTopic());
break;
}
}
@@ -112,13 +115,13 @@ class TopicEndpointProxy implements TopicEndpoint {
public List<TopicSource> addTopicSources(Properties properties) {
// 1. Create UEB Sources
- // 2. Create DMAAP Sources
+ // 2. Create KAFKA Sources
// 3. Create NOOP Sources
List<TopicSource> sources = new ArrayList<>();
sources.addAll(UebTopicFactories.getSourceFactory().build(properties));
- sources.addAll(DmaapTopicFactories.getSourceFactory().build(properties));
+ sources.addAll(KafkaTopicFactories.getSourceFactory().build(properties));
sources.addAll(NoopTopicFactories.getSourceFactory().build(properties));
lockSources(sources);
@@ -141,15 +144,15 @@ class TopicEndpointProxy implements TopicEndpoint {
case UEB:
sinks.add(UebTopicFactories.getSinkFactory().build(param));
break;
- case DMAAP:
- sinks.add(DmaapTopicFactories.getSinkFactory().build(param));
+ case KAFKA:
+ sinks.add(KafkaTopicFactories.getSinkFactory().build(param));
break;
case NOOP:
sinks.add(NoopTopicFactories.getSinkFactory().build(param));
break;
default:
logger.debug("Unknown sink type {} for topic: {}", param.getTopicCommInfrastructure(),
- param.getTopic());
+ param.getTopic());
break;
}
}
@@ -162,13 +165,13 @@ class TopicEndpointProxy implements TopicEndpoint {
@Override
public List<TopicSink> addTopicSinks(Properties properties) {
// 1. Create UEB Sinks
- // 2. Create DMAAP Sinks
+ // 2. Create KAFKA Sinks
// 3. Create NOOP Sinks
final List<TopicSink> sinks = new ArrayList<>();
sinks.addAll(UebTopicFactories.getSinkFactory().build(properties));
- sinks.addAll(DmaapTopicFactories.getSinkFactory().build(properties));
+ sinks.addAll(KafkaTopicFactories.getSinkFactory().build(properties));
sinks.addAll(NoopTopicFactories.getSinkFactory().build(properties));
lockSinks(sinks);
@@ -188,7 +191,7 @@ class TopicEndpointProxy implements TopicEndpoint {
final List<TopicSource> sources = new ArrayList<>();
sources.addAll(UebTopicFactories.getSourceFactory().inventory());
- sources.addAll(DmaapTopicFactories.getSourceFactory().inventory());
+ sources.addAll(KafkaTopicFactories.getSourceFactory().inventory());
sources.addAll(NoopTopicFactories.getSourceFactory().inventory());
return sources;
@@ -202,34 +205,27 @@ class TopicEndpointProxy implements TopicEndpoint {
}
final List<TopicSource> sources = new ArrayList<>();
- for (final String topic : topicNames) {
+
+ topicNames.forEach(topic -> {
try {
- final TopicSource uebSource = this.getUebTopicSource(topic);
- if (uebSource != null) {
- sources.add(uebSource);
- }
+ sources.add(Objects.requireNonNull(this.getUebTopicSource(topic)));
} catch (final Exception e) {
logger.debug("No UEB source for topic: {}", topic, e);
}
try {
- final TopicSource dmaapSource = this.getDmaapTopicSource(topic);
- if (dmaapSource != null) {
- sources.add(dmaapSource);
- }
+ sources.add(Objects.requireNonNull(this.getKafkaTopicSource(topic)));
} catch (final Exception e) {
- logger.debug("No DMAAP source for topic: {}", topic, e);
+ logger.debug("No KAFKA source for topic: {}", topic, e);
}
try {
- final TopicSource noopSource = this.getNoopTopicSource(topic);
- if (noopSource != null) {
- sources.add(noopSource);
- }
+ sources.add(Objects.requireNonNull(this.getNoopTopicSource(topic)));
} catch (final Exception e) {
logger.debug("No NOOP source for topic: {}", topic, e);
}
- }
+ });
+
return sources;
}
@@ -239,7 +235,7 @@ class TopicEndpointProxy implements TopicEndpoint {
final List<TopicSink> sinks = new ArrayList<>();
sinks.addAll(UebTopicFactories.getSinkFactory().inventory());
- sinks.addAll(DmaapTopicFactories.getSinkFactory().inventory());
+ sinks.addAll(KafkaTopicFactories.getSinkFactory().inventory());
sinks.addAll(NoopTopicFactories.getSinkFactory().inventory());
return sinks;
@@ -255,28 +251,19 @@ class TopicEndpointProxy implements TopicEndpoint {
final List<TopicSink> sinks = new ArrayList<>();
for (final String topic : topicNames) {
try {
- final TopicSink uebSink = this.getUebTopicSink(topic);
- if (uebSink != null) {
- sinks.add(uebSink);
- }
+ sinks.add(Objects.requireNonNull(this.getUebTopicSink(topic)));
} catch (final Exception e) {
logger.debug("No UEB sink for topic: {}", topic, e);
}
try {
- final TopicSink dmaapSink = this.getDmaapTopicSink(topic);
- if (dmaapSink != null) {
- sinks.add(dmaapSink);
- }
+ sinks.add(Objects.requireNonNull(this.getKafkaTopicSink(topic)));
} catch (final Exception e) {
- logger.debug("No DMAAP sink for topic: {}", topic, e);
+ logger.debug("No KAFKA sink for topic: {}", topic, e);
}
try {
- final TopicSink noopSink = this.getNoopTopicSink(topic);
- if (noopSink != null) {
- sinks.add(noopSink);
- }
+ sinks.add(Objects.requireNonNull(this.getNoopTopicSink(topic)));
} catch (final Exception e) {
logger.debug("No NOOP sink for topic: {}", topic, e);
}
@@ -287,7 +274,7 @@ class TopicEndpointProxy implements TopicEndpoint {
@Override
public List<TopicSink> getTopicSinks(String topicName) {
if (topicName == null) {
- throw parmException(null);
+ throw paramException(null);
}
final List<TopicSink> sinks = new ArrayList<>();
@@ -299,7 +286,7 @@ class TopicEndpointProxy implements TopicEndpoint {
}
try {
- sinks.add(this.getDmaapTopicSink(topicName));
+ sinks.add(this.getKafkaTopicSink(topicName));
} catch (final Exception e) {
logNoSink(topicName, e);
}
@@ -313,42 +300,36 @@ class TopicEndpointProxy implements TopicEndpoint {
return sinks;
}
- @JsonIgnore
@GsonJsonIgnore
@Override
public List<UebTopicSource> getUebTopicSources() {
return UebTopicFactories.getSourceFactory().inventory();
}
- @JsonIgnore
@GsonJsonIgnore
@Override
- public List<DmaapTopicSource> getDmaapTopicSources() {
- return DmaapTopicFactories.getSourceFactory().inventory();
+ public List<KafkaTopicSource> getKafkaTopicSources() {
+ return KafkaTopicFactories.getSourceFactory().inventory();
}
- @JsonIgnore
@GsonJsonIgnore
@Override
public List<NoopTopicSource> getNoopTopicSources() {
return NoopTopicFactories.getSourceFactory().inventory();
}
- @JsonIgnore
@GsonJsonIgnore
@Override
public List<UebTopicSink> getUebTopicSinks() {
return UebTopicFactories.getSinkFactory().inventory();
}
- @JsonIgnore
- @GsonJsonIgnore
@Override
- public List<DmaapTopicSink> getDmaapTopicSinks() {
- return DmaapTopicFactories.getSinkFactory().inventory();
+ @GsonJsonIgnore
+ public List<KafkaTopicSink> getKafkaTopicSinks() {
+ return KafkaTopicFactories.getSinkFactory().inventory();
}
- @JsonIgnore
@GsonJsonIgnore
@Override
public List<NoopTopicSink> getNoopTopicSinks() {
@@ -372,7 +353,7 @@ class TopicEndpointProxy implements TopicEndpoint {
final List<Startable> endpoints = this.getEndpoints();
- boolean success = true;
+ var success = true;
for (final Startable endpoint : endpoints) {
try {
success = endpoint.start() && success;
@@ -398,7 +379,7 @@ class TopicEndpointProxy implements TopicEndpoint {
final List<Startable> endpoints = this.getEndpoints();
- boolean success = true;
+ var success = true;
for (final Startable endpoint : endpoints) {
try {
success = endpoint.stop() && success;
@@ -416,7 +397,6 @@ class TopicEndpointProxy implements TopicEndpoint {
*
* @return list of managed endpoints
*/
- @JsonIgnore
@GsonJsonIgnore
protected List<Startable> getEndpoints() {
final List<Startable> endpoints = new ArrayList<>();
@@ -434,8 +414,8 @@ class TopicEndpointProxy implements TopicEndpoint {
UebTopicFactories.getSourceFactory().destroy();
UebTopicFactories.getSinkFactory().destroy();
- DmaapTopicFactories.getSourceFactory().destroy();
- DmaapTopicFactories.getSinkFactory().destroy();
+ KafkaTopicFactories.getSourceFactory().destroy();
+ KafkaTopicFactories.getSinkFactory().destroy();
NoopTopicFactories.getSinkFactory().destroy();
NoopTopicFactories.getSourceFactory().destroy();
@@ -443,27 +423,22 @@ class TopicEndpointProxy implements TopicEndpoint {
}
@Override
- public boolean isAlive() {
- return this.alive;
- }
-
- @Override
public boolean lock() {
+ boolean shouldLock;
synchronized (this) {
- if (this.locked) {
- return true;
- }
-
+ shouldLock = !this.locked;
this.locked = true;
}
- for (final TopicSource source : this.getTopicSources()) {
- source.lock();
- }
+ if (shouldLock) {
+ for (final TopicSource source : this.getTopicSources()) {
+ source.lock();
+ }
- for (final TopicSink sink : this.getTopicSinks()) {
- sink.lock();
+ for (final TopicSink sink : this.getTopicSinks()) {
+ sink.lock();
+ }
}
return true;
@@ -471,73 +446,61 @@ class TopicEndpointProxy implements TopicEndpoint {
@Override
public boolean unlock() {
- synchronized (this) {
- if (!this.locked) {
- return true;
- }
+ boolean shouldUnlock;
+ synchronized (this) {
+ shouldUnlock = this.locked;
this.locked = false;
}
- for (final TopicSource source : this.getTopicSources()) {
- source.unlock();
- }
+ if (shouldUnlock) {
+ for (final TopicSource source : this.getTopicSources()) {
+ source.unlock();
+ }
- for (final TopicSink sink : this.getTopicSinks()) {
- sink.unlock();
+ for (final TopicSink sink : this.getTopicSinks()) {
+ sink.unlock();
+ }
}
return true;
}
@Override
- public boolean isLocked() {
- return this.locked;
- }
-
- @Override
public TopicSource getTopicSource(Topic.CommInfrastructure commType, String topicName) {
if (commType == null) {
- throw parmException(topicName);
+ throw paramException(topicName);
}
if (topicName == null) {
- throw parmException(null);
+ throw paramException(null);
}
- switch (commType) {
- case UEB:
- return this.getUebTopicSource(topicName);
- case DMAAP:
- return this.getDmaapTopicSource(topicName);
- case NOOP:
- return this.getNoopTopicSource(topicName);
- default:
- throw new UnsupportedOperationException("Unsupported " + commType.name());
- }
+ return switch (commType) {
+ case UEB -> this.getUebTopicSource(topicName);
+ case KAFKA -> this.getKafkaTopicSource(topicName);
+ case NOOP -> this.getNoopTopicSource(topicName);
+ default -> throw new UnsupportedOperationException("Unsupported " + commType.name());
+ };
}
@Override
public TopicSink getTopicSink(Topic.CommInfrastructure commType, String topicName) {
if (commType == null) {
- throw parmException(topicName);
+ throw paramException(topicName);
}
if (topicName == null) {
- throw parmException(null);
+ throw paramException(null);
}
- switch (commType) {
- case UEB:
- return this.getUebTopicSink(topicName);
- case DMAAP:
- return this.getDmaapTopicSink(topicName);
- case NOOP:
- return this.getNoopTopicSink(topicName);
- default:
- throw new UnsupportedOperationException("Unsupported " + commType.name());
- }
+ return switch (commType) {
+ case UEB -> this.getUebTopicSink(topicName);
+ case KAFKA -> this.getKafkaTopicSink(topicName);
+ case NOOP -> this.getNoopTopicSink(topicName);
+ default -> throw new UnsupportedOperationException("Unsupported " + commType.name());
+ };
}
@Override
@@ -551,8 +514,8 @@ class TopicEndpointProxy implements TopicEndpoint {
}
@Override
- public DmaapTopicSource getDmaapTopicSource(String topicName) {
- return DmaapTopicFactories.getSourceFactory().get(topicName);
+ public KafkaTopicSource getKafkaTopicSource(String topicName) {
+ return KafkaTopicFactories.getSourceFactory().get(topicName);
}
@Override
@@ -561,8 +524,8 @@ class TopicEndpointProxy implements TopicEndpoint {
}
@Override
- public DmaapTopicSink getDmaapTopicSink(String topicName) {
- return DmaapTopicFactories.getSinkFactory().get(topicName);
+ public KafkaTopicSink getKafkaTopicSink(String topicName) {
+ return KafkaTopicFactories.getSinkFactory().get(topicName);
}
@Override
@@ -570,7 +533,7 @@ class TopicEndpointProxy implements TopicEndpoint {
return NoopTopicFactories.getSinkFactory().get(topicName);
}
- private IllegalArgumentException parmException(String topicName) {
+ private IllegalArgumentException paramException(String topicName) {
return new IllegalArgumentException(
"Invalid parameter: a communication infrastructure required to fetch " + topicName);
}
@@ -579,4 +542,4 @@ class TopicEndpointProxy implements TopicEndpoint {
logger.debug("No sink for topic: {}", topicName, ex);
}
-} \ No newline at end of file
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicSink.java
index f36dfa31..b67756e5 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicSink.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicSink.java
@@ -3,6 +3,7 @@
* policy-endpoints
* ================================================================================
* Copyright (C) 2017-2018 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.
@@ -32,9 +33,9 @@ public interface TopicSink extends Topic {
*
* @return true if the send operation succeeded, false otherwise
* @throws IllegalArgumentException an invalid message has been provided
- * @throws IllegalStateException the entity is in an state that prevents
+ * @throws IllegalStateException the entity is in a state that prevents
* it from sending messages, for example, locked or stopped.
*/
- public boolean send(String message);
+ boolean send(String message);
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSink.java
index e77beea1..4073f5a7 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSink.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSink.java
@@ -3,6 +3,7 @@
* policy-endpoints
* ================================================================================
* 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.
@@ -23,7 +24,7 @@ package org.onap.policy.common.endpoints.event.comm.bus;
import org.onap.policy.common.endpoints.event.comm.TopicSink;
/**
- * Topic Sink over Bus Infrastructure (DMAAP/UEB).
+ * Topic Sink over Bus Infrastructure (KAFKA/UEB).
*/
public interface BusTopicSink extends ApiKeyEnabled, TopicSink {
@@ -32,12 +33,12 @@ public interface BusTopicSink extends ApiKeyEnabled, TopicSink {
*
* @param partitionKey the partition key
*/
- public void setPartitionKey(String partitionKey);
+ void setPartitionKey(String partitionKey);
/**
* Return the partition key in used by the system to publish messages.
*
* @return the partition key
*/
- public String getPartitionKey();
+ String getPartitionKey();
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSource.java
index cd9bc015..f1af8a21 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSource.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicSource.java
@@ -3,6 +3,7 @@
* policy-endpoints
* ================================================================================
* 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.
@@ -23,7 +24,7 @@ package org.onap.policy.common.endpoints.event.comm.bus;
import org.onap.policy.common.endpoints.event.comm.TopicSource;
/**
- * Generic Topic Source for UEB/DMAAP Communication Infrastructure.
+ * Generic Topic Source for UEB/KAFKA Communication Infrastructure.
*
*/
public interface BusTopicSource extends ApiKeyEnabled, TopicSource {
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactory.java
deleted file mode 100644
index 4409e827..00000000
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactory.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * policy-endpoints
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
- * ================================================================================
- * 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.endpoints.event.comm.bus;
-
-import java.util.List;
-import java.util.Properties;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
-
-/**
- * DMAAP Topic Sink Factory.
- */
-public interface DmaapTopicSinkFactory {
-
- /**
- * <pre>
- * Instantiate a new DMAAP Topic Sink, with following params.
- * servers list of servers
- * topic topic name
- * apiKey API Key
- * apiSecret API Secret
- * userName AAF user name
- * password AAF password
- * partitionKey Consumer Group
- * environment DME2 environment
- * aftEnvironment DME2 AFT environment
- * partner DME2 Partner
- * latitude DME2 latitude
- * longitude DME2 longitude
- * additionalProps additional properties to pass to DME2
- * managed is this sink endpoint managed?
- * </pre>
- * @param busTopicParams parameter object
- * @return DmaapTopicSink object
- * @throws IllegalArgumentException if invalid parameters are present
- */
- DmaapTopicSink build(BusTopicParams busTopicParams);
-
- /**
- * Creates an DMAAP Topic Sink based on properties files.
- *
- * @param properties Properties containing initialization values
- * @return an DMAAP Topic Sink
- * @throws IllegalArgumentException if invalid parameters are present
- */
- List<DmaapTopicSink> build(Properties properties);
-
- /**
- * Instantiates a new DMAAP Topic Sink.
- *
- * @param servers list of servers
- * @param topic topic name
- * @return an DMAAP Topic Sink
- * @throws IllegalArgumentException if invalid parameters are present
- */
- DmaapTopicSink build(List<String> servers, String topic);
-
- /**
- * Destroys an DMAAP Topic Sink based on a topic.
- *
- * @param topic topic name
- * @throws IllegalArgumentException if invalid parameters are present
- */
- void destroy(String topic);
-
- /**
- * Destroys all DMAAP Topic Sinks.
- */
- void destroy();
-
- /**
- * Gets an DMAAP Topic Sink based on topic name.
- *
- * @param topic the topic name
- * @return an DMAAP Topic Sink with topic name
- * @throws IllegalArgumentException if an invalid topic is provided
- * @throws IllegalStateException if the DMAAP Topic Reader is an incorrect state
- */
- DmaapTopicSink get(String topic);
-
- /**
- * Provides a snapshot of the DMAAP Topic Sinks.
- *
- * @return a list of the DMAAP Topic Sinks
- */
- List<DmaapTopicSink> inventory();
-}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSourceFactory.java
deleted file mode 100644
index d7f4695e..00000000
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSourceFactory.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * 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.endpoints.event.comm.bus;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Properties;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.SingleThreadedDmaapTopicSource;
-import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
-import org.onap.policy.common.endpoints.utils.DmaapPropertyUtils;
-import org.onap.policy.common.endpoints.utils.PropertyUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Factory of DMAAP Source Topics indexed by topic name.
- */
-
-class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory {
- private static final String MISSING_TOPIC = "A topic must be provided";
-
- /**
- * Logger.
- */
- private static Logger logger = LoggerFactory.getLogger(IndexedDmaapTopicSourceFactory.class);
-
- /**
- * DMaaP Topic Name Index.
- */
- protected HashMap<String, DmaapTopicSource> dmaapTopicSources = new HashMap<>();
-
- @Override
- public DmaapTopicSource build(BusTopicParams busTopicParams) {
-
- if (busTopicParams.getTopic() == null || busTopicParams.getTopic().isEmpty()) {
- throw new IllegalArgumentException(MISSING_TOPIC);
- }
-
- synchronized (this) {
- if (dmaapTopicSources.containsKey(busTopicParams.getTopic())) {
- return dmaapTopicSources.get(busTopicParams.getTopic());
- }
-
- DmaapTopicSource dmaapTopicSource = makeSource(busTopicParams);
-
- if (busTopicParams.isManaged()) {
- dmaapTopicSources.put(busTopicParams.getTopic(), dmaapTopicSource);
- }
- return dmaapTopicSource;
- }
- }
-
- @Override
- public List<DmaapTopicSource> build(Properties properties) {
-
- String readTopics = properties.getProperty(PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS);
- if (StringUtils.isBlank(readTopics)) {
- logger.info("{}: no topic for DMaaP Source", this);
- return new ArrayList<>();
- }
-
- List<DmaapTopicSource> dmaapTopicSourceLst = new ArrayList<>();
- synchronized (this) {
- for (String topic : readTopics.split("\\s*,\\s*")) {
- addTopic(dmaapTopicSourceLst, properties, topic);
- }
- }
- return dmaapTopicSourceLst;
- }
-
- @Override
- public DmaapTopicSource build(List<String> servers, String topic, String apiKey, String apiSecret) {
- return this.build(BusTopicParams.builder()
- .servers(servers)
- .topic(topic)
- .apiKey(apiKey)
- .apiSecret(apiSecret)
- .fetchTimeout(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH)
- .fetchLimit(PolicyEndPointProperties.DEFAULT_LIMIT_FETCH)
- .managed(true)
- .useHttps(false)
- .allowSelfSignedCerts(false)
- .build());
- }
-
- @Override
- public DmaapTopicSource build(List<String> servers, String topic) {
- return this.build(servers, topic, null, null);
- }
-
- private void addTopic(List<DmaapTopicSource> dmaapTopicSourceLst, Properties properties, String topic) {
- if (this.dmaapTopicSources.containsKey(topic)) {
- dmaapTopicSourceLst.add(this.dmaapTopicSources.get(topic));
- return;
- }
-
- String topicPrefix = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic;
-
- PropertyUtils props = new PropertyUtils(properties, topicPrefix,
- (name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
-
- String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
- if (StringUtils.isBlank(servers)) {
- logger.error("{}: no DMaaP servers or DME2 ServiceName provided", this);
- return;
- }
-
- DmaapTopicSource uebTopicSource = this.build(DmaapPropertyUtils.makeBuilder(props, topic, servers)
- .consumerGroup(props.getString(
- PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, null))
- .consumerInstance(props.getString(
- PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX, null))
- .fetchTimeout(props.getInteger(
- PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX,
- PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH))
- .fetchLimit(props.getInteger(PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX,
- PolicyEndPointProperties.DEFAULT_LIMIT_FETCH))
- .build());
-
- dmaapTopicSourceLst.add(uebTopicSource);
- }
-
- /**
- * Makes a new source.
- *
- * @param busTopicParams parameters to use to configure the source
- * @return a new source
- */
- protected DmaapTopicSource makeSource(BusTopicParams busTopicParams) {
- return new SingleThreadedDmaapTopicSource(busTopicParams);
- }
-
- @Override
- public void destroy(String topic) {
-
- if (topic == null || topic.isEmpty()) {
- throw new IllegalArgumentException(MISSING_TOPIC);
- }
-
- DmaapTopicSource uebTopicSource;
-
- synchronized (this) {
- if (!dmaapTopicSources.containsKey(topic)) {
- return;
- }
-
- uebTopicSource = dmaapTopicSources.remove(topic);
- }
-
- uebTopicSource.shutdown();
- }
-
- @Override
- public void destroy() {
- List<DmaapTopicSource> readers = this.inventory();
- for (DmaapTopicSource reader : readers) {
- reader.shutdown();
- }
-
- synchronized (this) {
- this.dmaapTopicSources.clear();
- }
- }
-
- @Override
- public DmaapTopicSource get(String topic) {
-
- if (topic == null || topic.isEmpty()) {
- throw new IllegalArgumentException(MISSING_TOPIC);
- }
-
- synchronized (this) {
- if (dmaapTopicSources.containsKey(topic)) {
- return dmaapTopicSources.get(topic);
- } else {
- throw new IllegalStateException("DmaapTopiceSource for " + topic + " not found");
- }
- }
- }
-
- @Override
- public synchronized List<DmaapTopicSource> inventory() {
- return new ArrayList<>(this.dmaapTopicSources.values());
- }
-
- @Override
- public String toString() {
- return "IndexedDmaapTopicSourceFactory []";
- }
-
-}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSinkFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSinkFactory.java
index 6f0753b3..f913926e 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSinkFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSinkFactory.java
@@ -1,8 +1,6 @@
/*
* ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2022-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.
@@ -20,118 +18,114 @@
package org.onap.policy.common.endpoints.event.comm.bus;
+import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.InlineDmaapTopicSink;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.InlineKafkaTopicSink;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
-import org.onap.policy.common.endpoints.utils.DmaapPropertyUtils;
+import org.onap.policy.common.endpoints.utils.KafkaPropertyUtils;
import org.onap.policy.common.endpoints.utils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Factory of DMAAP Reader Topics indexed by topic name.
+ * Factory of KAFKA Reader Topics indexed by topic name.
*/
-class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory {
-
+class IndexedKafkaTopicSinkFactory implements KafkaTopicSinkFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
private static final String MISSING_TOPIC = "A topic must be provided";
/**
* Logger.
*/
- private static Logger logger = LoggerFactory.getLogger(IndexedDmaapTopicSinkFactory.class);
+ private static final Logger logger = LoggerFactory.getLogger(IndexedKafkaTopicSinkFactory.class);
/**
- * DMAAP Topic Name Index.
+ * KAFKA Topic Name Index.
*/
- protected HashMap<String, DmaapTopicSink> dmaapTopicWriters = new HashMap<>();
+ protected HashMap<String, KafkaTopicSink> kafkaTopicSinks = new HashMap<>();
@Override
- public DmaapTopicSink build(BusTopicParams busTopicParams) {
+ public KafkaTopicSink build(BusTopicParams busTopicParams) {
+
+ if (busTopicParams.getServers() == null || busTopicParams.getServers().isEmpty()) {
+ throw new IllegalArgumentException("KAFKA Server(s) must be provided");
+ }
if (StringUtils.isBlank(busTopicParams.getTopic())) {
throw new IllegalArgumentException(MISSING_TOPIC);
}
synchronized (this) {
- if (dmaapTopicWriters.containsKey(busTopicParams.getTopic())) {
- return dmaapTopicWriters.get(busTopicParams.getTopic());
+ if (kafkaTopicSinks.containsKey(busTopicParams.getTopic())) {
+ return kafkaTopicSinks.get(busTopicParams.getTopic());
}
- DmaapTopicSink dmaapTopicSink = makeSink(busTopicParams);
-
+ KafkaTopicSink kafkaTopicWriter = makeSink(busTopicParams);
if (busTopicParams.isManaged()) {
- dmaapTopicWriters.put(busTopicParams.getTopic(), dmaapTopicSink);
+ kafkaTopicSinks.put(busTopicParams.getTopic(), kafkaTopicWriter);
}
- return dmaapTopicSink;
+
+ return kafkaTopicWriter;
}
}
+
@Override
- public DmaapTopicSink build(List<String> servers, String topic) {
+ public KafkaTopicSink build(List<String> servers, String topic) {
return this.build(BusTopicParams.builder()
.servers(servers)
.topic(topic)
.managed(true)
.useHttps(false)
- .allowSelfSignedCerts(false)
.build());
}
+
@Override
- public List<DmaapTopicSink> build(Properties properties) {
+ public List<KafkaTopicSink> build(Properties properties) {
- String writeTopics = properties.getProperty(PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS);
+ String writeTopics = properties.getProperty(PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS);
if (StringUtils.isBlank(writeTopics)) {
- logger.info("{}: no topic for DMaaP Sink", this);
+ logger.info("{}: no topic for KAFKA Sink", this);
return new ArrayList<>();
}
- List<DmaapTopicSink> newDmaapTopicSinks = new ArrayList<>();
+ List<KafkaTopicSink> newKafkaTopicSinks = new ArrayList<>();
synchronized (this) {
- for (String topic : writeTopics.split("\\s*,\\s*")) {
- addTopic(newDmaapTopicSinks, properties, topic);
+ for (String topic : COMMA_SPACE_PAT.split(writeTopics)) {
+ addTopic(newKafkaTopicSinks, topic.toLowerCase(), properties);
}
- return newDmaapTopicSinks;
+ return newKafkaTopicSinks;
}
}
- private void addTopic(List<DmaapTopicSink> newDmaapTopicSinks, Properties properties, String topic) {
- if (this.dmaapTopicWriters.containsKey(topic)) {
- newDmaapTopicSinks.add(this.dmaapTopicWriters.get(topic));
+ private void addTopic(List<KafkaTopicSink> newKafkaTopicSinks, String topic, Properties properties) {
+ if (this.kafkaTopicSinks.containsKey(topic)) {
+ newKafkaTopicSinks.add(this.kafkaTopicSinks.get(topic));
return;
}
- String topicPrefix = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic;
+ String topicPrefix = PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS + "." + topic;
- PropertyUtils props = new PropertyUtils(properties, topicPrefix,
- (name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
+ var props = new PropertyUtils(properties, topicPrefix,
+ (name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic sink {} ",
+ this, name, value, topic));
String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
if (StringUtils.isBlank(servers)) {
- logger.error("{}: no DMaaP servers or DME2 ServiceName provided", this);
+ logger.error("{}: no KAFKA servers configured for sink {}", this, topic);
return;
}
- DmaapTopicSink dmaapTopicSink = this.build(DmaapPropertyUtils.makeBuilder(props, topic, servers)
+ KafkaTopicSink kafkaTopicWriter = this.build(KafkaPropertyUtils.makeBuilder(props, topic, servers)
.partitionId(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, null))
.build());
-
- newDmaapTopicSinks.add(dmaapTopicSink);
- }
-
- /**
- * Makes a new sink.
- *
- * @param busTopicParams parameters to use to configure the sink
- * @return a new sink
- */
- protected DmaapTopicSink makeSink(BusTopicParams busTopicParams) {
- return new InlineDmaapTopicSink(busTopicParams);
+ newKafkaTopicSinks.add(kafkaTopicWriter);
}
@Override
@@ -141,54 +135,65 @@ class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory {
throw new IllegalArgumentException(MISSING_TOPIC);
}
- DmaapTopicSink dmaapTopicWriter;
+ KafkaTopicSink kafkaTopicWriter;
synchronized (this) {
- if (!dmaapTopicWriters.containsKey(topic)) {
+ if (!kafkaTopicSinks.containsKey(topic)) {
return;
}
- dmaapTopicWriter = dmaapTopicWriters.remove(topic);
+ kafkaTopicWriter = kafkaTopicSinks.remove(topic);
}
- dmaapTopicWriter.shutdown();
+ kafkaTopicWriter.shutdown();
}
@Override
public void destroy() {
- List<DmaapTopicSink> writers = this.inventory();
- for (DmaapTopicSink writer : writers) {
+ List<KafkaTopicSink> writers = this.inventory();
+ for (KafkaTopicSink writer : writers) {
writer.shutdown();
}
synchronized (this) {
- this.dmaapTopicWriters.clear();
+ this.kafkaTopicSinks.clear();
}
}
@Override
- public DmaapTopicSink get(String topic) {
+ public KafkaTopicSink get(String topic) {
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentException(MISSING_TOPIC);
}
synchronized (this) {
- if (dmaapTopicWriters.containsKey(topic)) {
- return dmaapTopicWriters.get(topic);
+ if (kafkaTopicSinks.containsKey(topic)) {
+ return kafkaTopicSinks.get(topic);
} else {
- throw new IllegalStateException("DmaapTopicSink for " + topic + " not found");
+ throw new IllegalStateException("KafkaTopicSink for " + topic + " not found");
}
}
}
@Override
- public synchronized List<DmaapTopicSink> inventory() {
- return new ArrayList<>(this.dmaapTopicWriters.values());
+ public synchronized List<KafkaTopicSink> inventory() {
+ return new ArrayList<>(this.kafkaTopicSinks.values());
}
+ /**
+ * Makes a new sink.
+ *
+ * @param busTopicParams parameters to use to configure the sink
+ * @return a new sink
+ */
+ protected KafkaTopicSink makeSink(BusTopicParams busTopicParams) {
+ return new InlineKafkaTopicSink(busTopicParams);
+ }
+
+
@Override
public String toString() {
- return "IndexedDmaapTopicSinkFactory []";
+ return "IndexedKafkaTopicSinkFactory " + kafkaTopicSinks.keySet();
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSourceFactory.java
new file mode 100644
index 00000000..151d8f69
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSourceFactory.java
@@ -0,0 +1,204 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2022-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.endpoints.event.comm.bus;
+
+import com.google.re2j.Pattern;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Properties;
+import org.apache.commons.lang3.StringUtils;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.SingleThreadedKafkaTopicSource;
+import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
+import org.onap.policy.common.endpoints.utils.KafkaPropertyUtils;
+import org.onap.policy.common.endpoints.utils.PropertyUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Factory of KAFKA Source Topics indexed by topic name.
+ */
+class IndexedKafkaTopicSourceFactory implements KafkaTopicSourceFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
+ private static final String MISSING_TOPIC = "A topic must be provided";
+
+ /**
+ * Logger.
+ */
+ private static final Logger logger = LoggerFactory.getLogger(IndexedKafkaTopicSourceFactory.class);
+
+ /**
+ * KAFKA Topic Name Index.
+ */
+ protected HashMap<String, KafkaTopicSource> kafkaTopicSources = new HashMap<>();
+
+ @Override
+ public KafkaTopicSource build(BusTopicParams busTopicParams) {
+ if (busTopicParams.getServers() == null || busTopicParams.getServers().isEmpty()) {
+ throw new IllegalArgumentException("KAFKA Server(s) must be provided");
+ }
+
+ if (busTopicParams.getTopic() == null || busTopicParams.getTopic().isEmpty()) {
+ throw new IllegalArgumentException(MISSING_TOPIC);
+ }
+
+ synchronized (this) {
+ if (kafkaTopicSources.containsKey(busTopicParams.getTopic())) {
+ return kafkaTopicSources.get(busTopicParams.getTopic());
+ }
+
+ var kafkaTopicSource = makeSource(busTopicParams);
+
+ kafkaTopicSources.put(busTopicParams.getTopic(), kafkaTopicSource);
+
+ return kafkaTopicSource;
+ }
+ }
+
+ @Override
+ public List<KafkaTopicSource> build(Properties properties) {
+
+ String readTopics = properties.getProperty(PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS);
+ if (StringUtils.isBlank(readTopics)) {
+ logger.info("{}: no topic for KAFKA Source", this);
+ return new ArrayList<>();
+ }
+
+ List<KafkaTopicSource> newKafkaTopicSources = new ArrayList<>();
+ synchronized (this) {
+ for (String topic : COMMA_SPACE_PAT.split(readTopics)) {
+ addTopic(newKafkaTopicSources, topic.toLowerCase(), properties);
+ }
+ }
+ return newKafkaTopicSources;
+ }
+
+ @Override
+ public KafkaTopicSource build(List<String> servers, String topic) {
+ return this.build(BusTopicParams.builder()
+ .servers(servers)
+ .topic(topic)
+ .managed(true)
+ .fetchTimeout(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH)
+ .fetchLimit(PolicyEndPointProperties.DEFAULT_LIMIT_FETCH)
+ .useHttps(false).build());
+ }
+
+ private void addTopic(List<KafkaTopicSource> newKafkaTopicSources, String topic, Properties properties) {
+ if (this.kafkaTopicSources.containsKey(topic)) {
+ newKafkaTopicSources.add(this.kafkaTopicSources.get(topic));
+ return;
+ }
+
+ String topicPrefix = PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS + "." + topic;
+
+ var props = new PropertyUtils(properties, topicPrefix,
+ (name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic source {} ",
+ this, name, value, topic));
+
+ String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
+ if (StringUtils.isBlank(servers)) {
+ logger.error("{}: no KAFKA servers configured for source {}", this, topic);
+ return;
+ }
+
+ var kafkaTopicSource = this.build(KafkaPropertyUtils.makeBuilder(props, topic, servers)
+ .consumerGroup(props.getString(
+ PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, null))
+ .consumerInstance(props.getString(
+ PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX, null))
+ .fetchTimeout(props.getInteger(
+ PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX,
+ PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH))
+ .fetchLimit(props.getInteger(PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX,
+ PolicyEndPointProperties.DEFAULT_LIMIT_FETCH))
+ .build());
+
+ newKafkaTopicSources.add(kafkaTopicSource);
+ }
+
+ /**
+ * Makes a new source.
+ *
+ * @param busTopicParams parameters to use to configure the source
+ * @return a new source
+ */
+ protected KafkaTopicSource makeSource(BusTopicParams busTopicParams) {
+ return new SingleThreadedKafkaTopicSource(busTopicParams);
+ }
+
+ @Override
+ public void destroy(String topic) {
+
+ if (topic == null || topic.isEmpty()) {
+ throw new IllegalArgumentException(MISSING_TOPIC);
+ }
+
+ KafkaTopicSource kafkaTopicSource;
+
+ synchronized (this) {
+ if (!kafkaTopicSources.containsKey(topic)) {
+ return;
+ }
+
+ kafkaTopicSource = kafkaTopicSources.remove(topic);
+ }
+
+ kafkaTopicSource.shutdown();
+ }
+
+ @Override
+ public void destroy() {
+ List<KafkaTopicSource> readers = this.inventory();
+ for (KafkaTopicSource reader : readers) {
+ reader.shutdown();
+ }
+
+ synchronized (this) {
+ this.kafkaTopicSources.clear();
+ }
+ }
+
+ @Override
+ public KafkaTopicSource get(String topic) {
+
+ if (topic == null || topic.isEmpty()) {
+ throw new IllegalArgumentException(MISSING_TOPIC);
+ }
+
+ synchronized (this) {
+ if (kafkaTopicSources.containsKey(topic)) {
+ return kafkaTopicSources.get(topic);
+ } else {
+ throw new IllegalStateException("KafkaTopiceSource for " + topic + " not found");
+ }
+ }
+ }
+
+ @Override
+ public synchronized List<KafkaTopicSource> inventory() {
+ return new ArrayList<>(this.kafkaTopicSources.values());
+ }
+
+ @Override
+ public String toString() {
+ return "IndexedKafkaTopicSourceFactory " + kafkaTopicSources.keySet();
+ }
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSinkFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSinkFactory.java
index 150a02c0..b04fc078 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSinkFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSinkFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus;
+import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -37,6 +38,7 @@ import org.slf4j.LoggerFactory;
* Factory of UEB Reader Topics indexed by topic name.
*/
class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
private static final String MISSING_TOPIC = "A topic must be provided";
/**
@@ -99,7 +101,7 @@ class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
List<UebTopicSink> newUebTopicSinks = new ArrayList<>();
synchronized (this) {
- for (String topic : writeTopics.split("\\s*,\\s*")) {
+ for (String topic : COMMA_SPACE_PAT.split(writeTopics)) {
addTopic(newUebTopicSinks, topic, properties);
}
return newUebTopicSinks;
@@ -114,7 +116,7 @@ class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
String topicPrefix = PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic;
- PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+ var props = new PropertyUtils(properties, topicPrefix,
(name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
@@ -194,9 +196,7 @@ class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("IndexedUebTopicSinkFactory []");
- return builder.toString();
+ return "IndexedUebTopicSinkFactory " + uebTopicSinks.keySet();
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSourceFactory.java
index 5bdc8ab6..09500978 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSourceFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSourceFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus;
+import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -37,6 +38,7 @@ import org.slf4j.LoggerFactory;
* Factory of UEB Source Topics indexed by topic name.
*/
class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
private static final String MISSING_TOPIC = "A topic must be provided";
/**
@@ -64,7 +66,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
return uebTopicSources.get(busTopicParams.getTopic());
}
- UebTopicSource uebTopicSource = makeSource(busTopicParams);
+ var uebTopicSource = makeSource(busTopicParams);
if (busTopicParams.isManaged()) {
uebTopicSources.put(busTopicParams.getTopic(), uebTopicSource);
@@ -85,7 +87,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
List<UebTopicSource> newUebTopicSources = new ArrayList<>();
synchronized (this) {
- for (String topic : readTopics.split("\\s*,\\s*")) {
+ for (String topic : COMMA_SPACE_PAT.split(readTopics)) {
addTopic(newUebTopicSources, topic, properties);
}
}
@@ -120,7 +122,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
String topicPrefix = PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic;
- PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+ var props = new PropertyUtils(properties, topicPrefix,
(name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
@@ -129,7 +131,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
return;
}
- UebTopicSource uebTopicSource = this.build(UebPropertyUtils.makeBuilder(props, topic, servers)
+ var uebTopicSource = this.build(UebPropertyUtils.makeBuilder(props, topic, servers)
.consumerGroup(props.getString(
PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, null))
.consumerInstance(props.getString(
@@ -209,8 +211,6 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("IndexedUebTopicSourceFactory []");
- return builder.toString();
+ return "IndexedUebTopicSourceFactory " + uebTopicSources.keySet();
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactories.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicFactories.java
index d5a46f8f..60db3857 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactories.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicFactories.java
@@ -1,8 +1,6 @@
/*
* ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2022 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,24 +18,22 @@
package org.onap.policy.common.endpoints.event.comm.bus;
+import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
-public class DmaapTopicFactories {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class KafkaTopicFactories {
/**
* Factory for instantiation and management of sinks.
*/
@Getter
- private static final DmaapTopicSinkFactory sinkFactory = new IndexedDmaapTopicSinkFactory();
+ private static final KafkaTopicSinkFactory sinkFactory = new IndexedKafkaTopicSinkFactory();
/**
* Factory for instantiation and management of sources.
*/
@Getter
- private static final DmaapTopicSourceFactory sourceFactory = new IndexedDmaapTopicSourceFactory();
-
-
- private DmaapTopicFactories() {
- // do nothing
- }
+ private static final KafkaTopicSourceFactory sourceFactory = new IndexedKafkaTopicSourceFactory();
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSink.java
index 805ed108..960a02c5 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSink.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSink.java
@@ -1,8 +1,6 @@
-/*-
+/*
* ============LICENSE_START=======================================================
- * policy-endpoints
- * ================================================================================
- * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2022 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +18,9 @@
package org.onap.policy.common.endpoints.event.comm.bus;
-public interface DmaapTopicSink extends BusTopicSink {
+/**
+ * Topic Writer over KAFKA Infrastructure.
+ */
+public interface KafkaTopicSink extends BusTopicSink {
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkFactory.java
index 7b1f185b..fa5e56f9 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkFactory.java
@@ -1,9 +1,6 @@
/*
* ============LICENSE_START=======================================================
- * policy-endpoints
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (C) 2022 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,54 +23,41 @@ import java.util.Properties;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
/**
- * DMAAP Topic Source Factory.
+ * KAFKA Topic Sink Factory.
*/
-public interface DmaapTopicSourceFactory {
-
- /**
- * Creates an DMAAP Topic Source based on properties files.
- *
- * @param properties Properties containing initialization values
- *
- * @return an DMAAP Topic Source
- * @throws IllegalArgumentException if invalid parameters are present
- */
- List<DmaapTopicSource> build(Properties properties);
+public interface KafkaTopicSinkFactory {
/**
- * Instantiates a new DMAAP Topic Source.
+ * Instantiates a new KAFKA Topic Writer.
*
* @param busTopicParams parameters object
- * @return a DMAAP Topic Source
+ * @return an KAFKA Topic Sink
*/
- DmaapTopicSource build(BusTopicParams busTopicParams);
+ KafkaTopicSink build(BusTopicParams busTopicParams);
/**
- * Instantiates a new DMAAP Topic Source.
+ * Creates an KAFKA Topic Writer based on properties files.
*
- * @param servers list of servers
- * @param topic topic name
- * @param apiKey API Key
- * @param apiSecret API Secret
+ * @param properties Properties containing initialization values
*
- * @return an DMAAP Topic Source
+ * @return an KAFKA Topic Writer
* @throws IllegalArgumentException if invalid parameters are present
*/
- DmaapTopicSource build(List<String> servers, String topic, String apiKey, String apiSecret);
+ List<KafkaTopicSink> build(Properties properties);
/**
- * Instantiates a new DMAAP Topic Source.
+ * Instantiates a new KAFKA Topic Writer.
*
* @param servers list of servers
* @param topic topic name
*
- * @return an DMAAP Topic Source
+ * @return an KAFKA Topic Writer
* @throws IllegalArgumentException if invalid parameters are present
*/
- DmaapTopicSource build(List<String> servers, String topic);
+ KafkaTopicSink build(List<String> servers, String topic);
/**
- * Destroys an DMAAP Topic Source based on a topic.
+ * Destroys an KAFKA Topic Writer based on a topic.
*
* @param topic topic name
* @throws IllegalArgumentException if invalid parameters are present
@@ -81,24 +65,25 @@ public interface DmaapTopicSourceFactory {
void destroy(String topic);
/**
- * Destroys all DMAAP Topic Sources.
+ * Destroys all KAFKA Topic Writers.
*/
void destroy();
/**
- * Gets an DMAAP Topic Source based on topic name.
+ * gets an KAFKA Topic Writer based on topic name.
*
* @param topic the topic name
- * @return an DMAAP Topic Source with topic name
+ *
+ * @return an KAFKA Topic Writer with topic name
* @throws IllegalArgumentException if an invalid topic is provided
- * @throws IllegalStateException if the DMAAP Topic Source is an incorrect state
+ * @throws IllegalStateException if the KAFKA Topic Reader is an incorrect state
*/
- DmaapTopicSource get(String topic);
+ KafkaTopicSink get(String topic);
/**
- * Provides a snapshot of the DMAAP Topic Sources.
+ * Provides a snapshot of the KAFKA Topic Writers.
*
- * @return a list of the DMAAP Topic Sources
+ * @return a list of the KAFKA Topic Writers
*/
- List<DmaapTopicSource> inventory();
+ List<KafkaTopicSink> inventory();
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSource.java
index 9893fa15..03efd083 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSource.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSource.java
@@ -1,8 +1,6 @@
-/*-
+/*
* ============LICENSE_START=======================================================
- * policy-endpoints
- * ================================================================================
- * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2022 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +18,9 @@
package org.onap.policy.common.endpoints.event.comm.bus;
-public interface DmaapTopicSource extends BusTopicSource {
+/**
+ * Kafka Topic Source.
+ */
+public interface KafkaTopicSource extends BusTopicSource {
-}
+} \ No newline at end of file
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceFactory.java
new file mode 100644
index 00000000..e5642daa
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceFactory.java
@@ -0,0 +1,88 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2022-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.endpoints.event.comm.bus;
+
+import java.util.List;
+import java.util.Properties;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
+
+/**
+ * Kafka Topic Source Factory.
+ */
+public interface KafkaTopicSourceFactory {
+
+ /**
+ * Creates a Kafka Topic Source based on properties files.
+ *
+ * @param properties Properties containing initialization values
+ *
+ * @return a Kafka Topic Source
+ * @throws IllegalArgumentException if invalid parameters are present
+ */
+ List<KafkaTopicSource> build(Properties properties);
+
+ /**
+ * Instantiates a new Kafka Topic Source.
+ *
+ * @param busTopicParams parameters object
+ * @return a Kafka Topic Source
+ */
+ KafkaTopicSource build(BusTopicParams busTopicParams);
+
+ /**
+ * Instantiates a new Kafka Topic Source.
+ *
+ * @param servers list of servers
+ * @param topic topic name
+ *
+ * @return a Kafka Topic Source
+ * @throws IllegalArgumentException if invalid parameters are present
+ */
+ KafkaTopicSource build(List<String> servers, String topic);
+
+ /**
+ * Destroys a Kafka Topic Source based on a topic.
+ *
+ * @param topic topic name
+ * @throws IllegalArgumentException if invalid parameters are present
+ */
+ void destroy(String topic);
+
+ /**
+ * Destroys all Kafka Topic Sources.
+ */
+ void destroy();
+
+ /**
+ * Gets a Kafka Topic Source based on topic name.
+ *
+ * @param topic the topic name
+ * @return a Kafka Topic Source with topic name
+ * @throws IllegalArgumentException if an invalid topic is provided
+ * @throws IllegalStateException if the Kafka Topic Source is an incorrect state
+ */
+ KafkaTopicSource get(String topic);
+
+ /**
+ * Provides a snapshot of the Kafka Topic Sources.
+ *
+ * @return a list of the Kafka Topic Sources
+ */
+ List<KafkaTopicSource> inventory();
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java
index 73c61651..73ff6ed6 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java
@@ -2,8 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2020 Bell Canada. 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.
@@ -41,7 +42,7 @@ public abstract class NoopTopicEndpoint extends TopicBase {
/**
* Constructs the object.
*/
- public NoopTopicEndpoint(List<String> servers, String topic) {
+ protected NoopTopicEndpoint(List<String> servers, String topic) {
super(servers, topic);
}
@@ -94,16 +95,13 @@ public abstract class NoopTopicEndpoint extends TopicBase {
logger.info("{}: starting", this);
synchronized (this) {
+ if (!this.alive) {
+ if (locked) {
+ throw new IllegalStateException(this + " is locked.");
+ }
- if (this.alive) {
- return true;
+ this.alive = true;
}
-
- if (locked) {
- throw new IllegalStateException(this + " is locked.");
- }
-
- this.alive = true;
}
return true;
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactories.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactories.java
index aa85e714..c3e7e0a4 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactories.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactories.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,8 +20,11 @@
package org.onap.policy.common.endpoints.event.comm.bus;
+import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class NoopTopicFactories {
/**
@@ -35,9 +38,4 @@ public class NoopTopicFactories {
*/
@Getter
private static final NoopTopicSourceFactory sourceFactory = new NoopTopicSourceFactory();
-
-
- private NoopTopicFactories() {
- // do nothing
- }
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactory.java
index 98b6ed6f..dfe7c2c4 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus;
+import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -32,6 +33,7 @@ import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
* Noop Topic Factory.
*/
public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends TopicBaseHashedFactory<T> {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
/**
* Get Topics Property Name.
@@ -50,7 +52,7 @@ public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends Topi
return new ArrayList<>();
}
- return Arrays.asList(topics.split("\\s*,\\s*"));
+ return Arrays.asList(COMMA_SPACE_PAT.split(topics));
}
/**
@@ -66,7 +68,7 @@ public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends Topi
servers = CommInfrastructure.NOOP.toString();
}
- return new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
+ return new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
}
/**
@@ -74,11 +76,11 @@ public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends Topi
*/
@Override
protected boolean isManaged(String topicName, Properties properties) {
- String managedString =
+ var managedString =
properties.getProperty(getTopicsPropertyName()
+ "." + topicName + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX);
- boolean managed = true;
+ var managed = true;
if (managedString != null && !managedString.isEmpty()) {
managed = Boolean.parseBoolean(managedString);
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/TopicBaseHashedFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/TopicBaseHashedFactory.java
index f53c5ea8..c785ef04 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/TopicBaseHashedFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/TopicBaseHashedFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -126,7 +126,7 @@ public abstract class TopicBaseHashedFactory<T extends Topic> implements TopicBa
return this.endpoints.get(topic);
}
- T endpoint = build(servers, topic);
+ var endpoint = build(servers, topic);
if (managed) {
this.endpoints.put(topic, endpoint);
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicFactories.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicFactories.java
index d02758be..721f2135 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicFactories.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicFactories.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,8 +20,11 @@
package org.onap.policy.common.endpoints.event.comm.bus;
+import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UebTopicFactories {
/**
@@ -35,9 +38,4 @@ public class UebTopicFactories {
*/
@Getter
private static final UebTopicSourceFactory sourceFactory = new IndexedUebTopicSourceFactory();
-
-
- private UebTopicFactories() {
- // do nothing
- }
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java
index 0f31bf7d..3c57d1ba 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java
@@ -2,8 +2,10 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2020,2023 Bell Canada. All rights reserved.
+ * Modifications Copyright (C) 2022-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.
@@ -24,19 +26,33 @@ package org.onap.policy.common.endpoints.event.comm.bus.internal;
import com.att.nsa.cambria.client.CambriaClientBuilders;
import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder;
import com.att.nsa.cambria.client.CambriaConsumer;
+import io.opentelemetry.api.trace.Span;
+import io.opentelemetry.api.trace.SpanContext;
+import io.opentelemetry.api.trace.TraceFlags;
+import io.opentelemetry.api.trace.TraceState;
+import io.opentelemetry.context.Context;
+import io.opentelemetry.instrumentation.kafkaclients.v2_6.TracingConsumerInterceptor;
import java.io.IOException;
import java.net.MalformedURLException;
+import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
+import java.time.Duration;
import java.util.ArrayList;
-import java.util.Map;
+import java.util.Collections;
+import java.util.List;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.dmaap.mr.client.MRClientFactory;
-import org.onap.dmaap.mr.client.impl.MRConsumerImpl;
-import org.onap.dmaap.mr.client.response.MRConsumerResponse;
-import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
+import lombok.Data;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.header.Headers;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,84 +76,109 @@ public interface BusConsumer {
public void close();
/**
- * BusConsumer that supports server-side filtering.
+ * Consumer that handles fetch() failures by sleeping.
*/
- public interface FilterableBusConsumer extends BusConsumer {
+ abstract class FetchingBusConsumer implements BusConsumer {
+ private static final Logger logger = LoggerFactory.getLogger(FetchingBusConsumer.class);
/**
- * Sets the server-side filter.
- *
- * @param filter new filter value, or {@code null}
- * @throws IllegalArgumentException if the consumer cannot be built with the new filter
+ * Fetch timeout.
*/
- public void setFilter(String filter);
- }
-
- /**
- * Cambria based consumer.
- */
- public static class CambriaConsumerWrapper implements FilterableBusConsumer {
+ protected int fetchTimeout;
/**
- * logger.
+ * Time to sleep on a fetch failure.
*/
- private static Logger logger = LoggerFactory.getLogger(CambriaConsumerWrapper.class);
+ @Getter
+ private final int sleepTime;
/**
- * Used to build the consumer.
+ * Counted down when {@link #close()} is invoked.
*/
- private final ConsumerBuilder builder;
+ private final CountDownLatch closeCondition = new CountDownLatch(1);
+
/**
- * Locked while updating {@link #consumer} and {@link #newConsumer}.
+ * Constructs the object.
+ *
+ * @param busTopicParams parameters for the bus topic
*/
- private final Object consLocker = new Object();
+ protected FetchingBusConsumer(BusTopicParams busTopicParams) {
+ this.fetchTimeout = busTopicParams.getFetchTimeout();
+
+ if (this.fetchTimeout <= 0) {
+ this.sleepTime = PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH;
+ } else {
+ // don't sleep too long, even if fetch timeout is large
+ this.sleepTime = Math.min(this.fetchTimeout, PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH);
+ }
+ }
/**
- * Cambria client.
+ * Causes the thread to sleep; invoked after fetch() fails. If the consumer is closed,
+ * or the thread is interrupted, then this will return immediately.
*/
- private CambriaConsumer consumer;
+ protected void sleepAfterFetchFailure() {
+ try {
+ logger.info("{}: backoff for {}ms", this, sleepTime);
+ if (this.closeCondition.await(this.sleepTime, TimeUnit.MILLISECONDS)) {
+ logger.info("{}: closed while handling fetch error", this);
+ }
+
+ } catch (InterruptedException e) {
+ logger.warn("{}: interrupted while handling fetch error", this, e);
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ @Override
+ public void close() {
+ this.closeCondition.countDown();
+ }
+ }
+
+ /**
+ * Cambria based consumer.
+ */
+ public static class CambriaConsumerWrapper extends FetchingBusConsumer {
/**
- * Cambria client to use for next fetch.
+ * logger.
*/
- private CambriaConsumer newConsumer = null;
+ private static Logger logger = LoggerFactory.getLogger(CambriaConsumerWrapper.class);
/**
- * fetch timeout.
+ * Used to build the consumer.
*/
- protected int fetchTimeout;
+ private final ConsumerBuilder builder;
/**
- * close condition.
+ * Cambria client.
*/
- protected CountDownLatch closeCondition = new CountDownLatch(1);
+ private final CambriaConsumer consumer;
/**
* Cambria Consumer Wrapper.
* BusTopicParam object contains the following parameters
- * servers messaging bus hosts.
- * topic topic
- * apiKey API Key
- * apiSecret API Secret
- * consumerGroup Consumer Group
- * consumerInstance Consumer Instance
- * fetchTimeout Fetch Timeout
- * fetchLimit Fetch Limit
+ * servers - messaging bus hosts.
+ * topic - topic for messages
+ * apiKey - API Key
+ * apiSecret - API Secret
+ * consumerGroup - Consumer Group
+ * consumerInstance - Consumer Instance
+ * fetchTimeout - Fetch Timeout
+ * fetchLimit - Fetch Limit
*
* @param busTopicParams - The parameters for the bus topic
- * @throws GeneralSecurityException - Security exception
- * @throws MalformedURLException - Malformed URL exception
*/
public CambriaConsumerWrapper(BusTopicParams busTopicParams) {
-
- this.fetchTimeout = busTopicParams.getFetchTimeout();
+ super(busTopicParams);
this.builder = new CambriaClientBuilders.ConsumerBuilder();
builder.knownAs(busTopicParams.getConsumerGroup(), busTopicParams.getConsumerInstance())
- .usingHosts(busTopicParams.getServers()).onTopic(busTopicParams.getTopic())
- .waitAtServer(fetchTimeout).receivingAtMost(busTopicParams.getFetchLimit());
+ .usingHosts(busTopicParams.getServers()).onTopic(busTopicParams.getTopic())
+ .waitAtServer(fetchTimeout).receivingAtMost(busTopicParams.getFetchLimit());
// Set read timeout to fetch timeout + 30 seconds (TBD: this should be configurable)
builder.withSocketTimeout(fetchTimeout + 30000);
@@ -168,77 +209,18 @@ public interface BusConsumer {
@Override
public Iterable<String> fetch() throws IOException {
try {
- return getCurrentConsumer().fetch();
+ return this.consumer.fetch();
} catch (final IOException e) { //NOSONAR
- logger.error("{}: cannot fetch because of {} - backoff for {} ms.", this, e.getMessage(),
- this.fetchTimeout);
+ logger.error("{}: cannot fetch because of {}", this, e.getMessage());
sleepAfterFetchFailure();
throw e;
}
}
- private void sleepAfterFetchFailure() {
- try {
- this.closeCondition.await(this.fetchTimeout, TimeUnit.MILLISECONDS); //NOSONAR
-
- } catch (InterruptedException e) {
- logger.warn("{}: interrupted while handling fetch error", this, e);
- Thread.currentThread().interrupt();
- }
- }
-
@Override
public void close() {
- this.closeCondition.countDown();
- getCurrentConsumer().close();
- }
-
- private CambriaConsumer getCurrentConsumer() {
- CambriaConsumer old = null;
- CambriaConsumer ret;
-
- synchronized (consLocker) {
- if (this.newConsumer != null) {
- // replace old consumer with new consumer
- old = this.consumer;
- this.consumer = this.newConsumer;
- this.newConsumer = null;
- }
-
- ret = this.consumer;
- }
-
- if (old != null) {
- old.close();
- }
-
- return ret;
- }
-
- @Override
- public void setFilter(String filter) {
- logger.info("{}: setting DMAAP server-side filter: {}", this, filter);
- builder.withServerSideFilter(filter);
-
- try {
- CambriaConsumer previous;
- synchronized (consLocker) {
- previous = this.newConsumer;
- this.newConsumer = builder.build();
- }
-
- if (previous != null) {
- // there was already a new consumer - close it
- previous.close();
- }
-
- } catch (MalformedURLException | GeneralSecurityException e) {
- /*
- * Since an exception occurred, "consumer" still has its old value, thus it should
- * not be closed at this point.
- */
- throw new IllegalArgumentException(e);
- }
+ super.close();
+ this.consumer.close();
}
@Override
@@ -248,307 +230,144 @@ public interface BusConsumer {
}
/**
- * MR based consumer.
+ * Kafka based consumer.
*/
- public abstract class DmaapConsumerWrapper implements BusConsumer {
+ class KafkaConsumerWrapper extends FetchingBusConsumer {
/**
* logger.
*/
- private static Logger logger = LoggerFactory.getLogger(DmaapConsumerWrapper.class);
-
- /**
- * Name of the "protocol" property.
- */
- protected static final String PROTOCOL_PROP = "Protocol";
+ private static final Logger logger = LoggerFactory.getLogger(KafkaConsumerWrapper.class);
- /**
- * fetch timeout.
- */
- protected int fetchTimeout;
+ private static final String KEY_DESERIALIZER = "org.apache.kafka.common.serialization.StringDeserializer";
/**
- * close condition.
+ * Kafka consumer.
*/
- protected CountDownLatch closeCondition = new CountDownLatch(1);
+ protected KafkaConsumer<String, String> consumer;
+ protected Properties kafkaProps;
- /**
- * MR Consumer.
- */
- protected MRConsumerImpl consumer;
+ protected boolean allowTracing;
/**
- * MR Consumer Wrapper.
+ * Kafka Consumer Wrapper.
+ * BusTopicParam - object contains the following parameters
+ * servers - messaging bus hosts.
+ * topic - topic
*
- * <p>servers messaging bus hosts
- * topic topic
- * apiKey API Key
- * apiSecret API Secret
- * username AAF Login
- * password AAF Password
- * consumerGroup Consumer Group
- * consumerInstance Consumer Instance
- * fetchTimeout Fetch Timeout
- * fetchLimit Fetch Limit
- *
- * @param busTopicParams contains above listed attributes
- * @throws MalformedURLException URL should be valid
+ * @param busTopicParams - The parameters for the bus topic
*/
- public DmaapConsumerWrapper(BusTopicParams busTopicParams) throws MalformedURLException {
-
- this.fetchTimeout = busTopicParams.getFetchTimeout();
+ public KafkaConsumerWrapper(BusTopicParams busTopicParams) {
+ super(busTopicParams);
if (busTopicParams.isTopicInvalid()) {
- throw new IllegalArgumentException("No topic for DMaaP");
+ throw new IllegalArgumentException("No topic for Kafka");
}
- this.consumer = new MRConsumerImpl(busTopicParams.getServers(), busTopicParams.getTopic(),
- busTopicParams.getConsumerGroup(), busTopicParams.getConsumerInstance(),
- busTopicParams.getFetchTimeout(), busTopicParams.getFetchLimit(), null,
- busTopicParams.getApiKey(), busTopicParams.getApiSecret());
-
- this.consumer.setUsername(busTopicParams.getUserName());
- this.consumer.setPassword(busTopicParams.getPassword());
- }
-
- @Override
- public Iterable<String> fetch() throws IOException {
- final MRConsumerResponse response = this.consumer.fetchWithReturnConsumerResponse();
- if (response == null) {
- logger.warn("{}: DMaaP NULL response received", this);
+ //Setup Properties for consumer
+ kafkaProps = new Properties();
+ kafkaProps.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
+ busTopicParams.getServers().get(0));
- sleepAfterFetchFailure();
- return new ArrayList<>();
- } else {
- logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(),
- response.getResponseMessage());
-
- if (!"200".equals(response.getResponseCode())) {
-
- logger.error("DMaaP consumer received: {} : {}", response.getResponseCode(),
- response.getResponseMessage());
-
- sleepAfterFetchFailure();
-
- /* fall through */
- }
+ if (busTopicParams.isAdditionalPropsValid()) {
+ kafkaProps.putAll(busTopicParams.getAdditionalProps());
}
- if (response.getActualMessages() == null) {
- return new ArrayList<>();
- } else {
- return response.getActualMessages();
+ if (kafkaProps.get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG) == null) {
+ kafkaProps.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, KEY_DESERIALIZER);
}
- }
-
- private void sleepAfterFetchFailure() {
- try {
- this.closeCondition.await(this.fetchTimeout, TimeUnit.MILLISECONDS); //NOSONAR
-
- } catch (InterruptedException e) {
- logger.warn("{}: interrupted while handling fetch error", this, e);
- Thread.currentThread().interrupt();
+ if (kafkaProps.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG) == null) {
+ kafkaProps.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KEY_DESERIALIZER);
}
- }
-
- @Override
- public void close() {
- this.closeCondition.countDown();
- this.consumer.close();
- }
-
- @Override
- public String toString() {
- return "DmaapConsumerWrapper [" + "consumer.getAuthDate()=" + consumer.getAuthDate()
- + ", consumer.getAuthKey()=" + consumer.getAuthKey() + ", consumer.getHost()=" + consumer.getHost()
- + ", consumer.getProtocolFlag()=" + consumer.getProtocolFlag() + ", consumer.getUsername()="
- + consumer.getUsername() + "]";
- }
- }
-
- /**
- * MR based consumer.
- */
- public static class DmaapAafConsumerWrapper extends DmaapConsumerWrapper {
-
- private static Logger logger = LoggerFactory.getLogger(DmaapAafConsumerWrapper.class);
-
- private final Properties props;
-
- /**
- * BusTopicParams contain the following parameters.
- * MR Consumer Wrapper.
- *
- * <p>servers messaging bus hosts
- * topic topic
- * apiKey API Key
- * apiSecret API Secret
- * aafLogin AAF Login
- * aafPassword AAF Password
- * consumerGroup Consumer Group
- * consumerInstance Consumer Instance
- * fetchTimeout Fetch Timeout
- * fetchLimit Fetch Limit
- *
- * @param busTopicParams contains above listed params
- * @throws MalformedURLException URL should be valid
- */
- public DmaapAafConsumerWrapper(BusTopicParams busTopicParams) throws MalformedURLException {
-
- super(busTopicParams);
-
- // super constructor sets servers = {""} if empty to avoid errors when using DME2
- if (busTopicParams.isServersInvalid()) {
- throw new IllegalArgumentException("Must provide at least one host for HTTP AAF");
+ if (kafkaProps.get(ConsumerConfig.GROUP_ID_CONFIG) == null) {
+ kafkaProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, busTopicParams.getConsumerGroup());
}
-
- this.consumer.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
-
- props = new Properties();
-
- if (busTopicParams.isUseHttps()) {
- props.setProperty(PROTOCOL_PROP, "https");
- this.consumer.setHost(busTopicParams.getServers().get(0) + ":3905");
-
- } else {
- props.setProperty(PROTOCOL_PROP, "http");
- this.consumer.setHost(busTopicParams.getServers().get(0) + ":3904");
+ if (busTopicParams.isAllowTracing()) {
+ this.allowTracing = true;
+ kafkaProps.setProperty(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG,
+ TracingConsumerInterceptor.class.getName());
}
- this.consumer.setProps(props);
- logger.info("{}: CREATION", this);
+ consumer = new KafkaConsumer<>(kafkaProps);
+ //Subscribe to the topic
+ consumer.subscribe(List.of(busTopicParams.getTopic()));
}
@Override
- public String toString() {
- final MRConsumerImpl consumer = this.consumer;
-
- return "DmaapConsumerWrapper [" + "consumer.getAuthDate()=" + consumer.getAuthDate()
- + ", consumer.getAuthKey()=" + consumer.getAuthKey() + ", consumer.getHost()=" + consumer.getHost()
- + ", consumer.getProtocolFlag()=" + consumer.getProtocolFlag() + ", consumer.getUsername()="
- + consumer.getUsername() + "]";
- }
- }
-
- public static class DmaapDmeConsumerWrapper extends DmaapConsumerWrapper {
-
- private static Logger logger = LoggerFactory.getLogger(DmaapDmeConsumerWrapper.class);
-
- private final Properties props;
-
- /**
- * Constructor.
- *
- * @param busTopicParams topic paramters
- *
- * @throws MalformedURLException must provide a valid URL
- */
- public DmaapDmeConsumerWrapper(BusTopicParams busTopicParams) throws MalformedURLException {
-
-
- super(busTopicParams);
-
-
- final String dme2RouteOffer = (busTopicParams.isAdditionalPropsValid()
- ? busTopicParams.getAdditionalProps().get(
- PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY)
- : null);
-
- if (busTopicParams.isEnvironmentInvalid()) {
- throw parmException(busTopicParams.getTopic(),
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX);
- }
- if (busTopicParams.isAftEnvironmentInvalid()) {
- throw parmException(busTopicParams.getTopic(),
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX);
- }
- if (busTopicParams.isLatitudeInvalid()) {
- throw parmException(busTopicParams.getTopic(),
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX);
- }
- if (busTopicParams.isLongitudeInvalid()) {
- throw parmException(busTopicParams.getTopic(),
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX);
+ public Iterable<String> fetch() {
+ ConsumerRecords<String, String> records = this.consumer.poll(Duration.ofMillis(fetchTimeout));
+ if (records == null || records.count() <= 0) {
+ return Collections.emptyList();
}
+ List<String> messages = new ArrayList<>(records.count());
+ try {
+ if (allowTracing) {
+ createParentTraceContext(records);
+ }
- if ((busTopicParams.isPartnerInvalid())
- && StringUtils.isBlank(dme2RouteOffer)) {
- throw new IllegalArgumentException(
- "Must provide at least " + PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS
- + "." + busTopicParams.getTopic()
- + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX + " or "
- + PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "."
- + busTopicParams.getTopic()
- + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX + " for DME2");
+ for (TopicPartition partition : records.partitions()) {
+ List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
+ for (ConsumerRecord<String, String> partitionRecord : partitionRecords) {
+ messages.add(partitionRecord.value());
+ }
+ long lastOffset = partitionRecords.get(partitionRecords.size() - 1).offset();
+ consumer.commitSync(Collections.singletonMap(partition, new OffsetAndMetadata(lastOffset + 1)));
+ }
+ } catch (Exception e) {
+ logger.error("{}: cannot fetch, throwing exception after sleep...", this);
+ sleepAfterFetchFailure();
+ throw e;
}
+ return messages;
+ }
- final String serviceName = busTopicParams.getServers().get(0);
-
- this.consumer.setProtocolFlag(ProtocolTypeConstants.DME2.getValue());
-
- this.consumer.setUsername(busTopicParams.getUserName());
- this.consumer.setPassword(busTopicParams.getPassword());
-
- props = new Properties();
-
- props.setProperty(PolicyEndPointProperties.DME2_SERVICE_NAME_PROPERTY, serviceName);
-
- props.setProperty("username", busTopicParams.getUserName());
- props.setProperty("password", busTopicParams.getPassword());
-
- /* These are required, no defaults */
- props.setProperty("topic", busTopicParams.getTopic());
-
- props.setProperty("Environment", busTopicParams.getEnvironment());
- props.setProperty("AFT_ENVIRONMENT", busTopicParams.getAftEnvironment());
+ private void createParentTraceContext(ConsumerRecords<String, String> records) {
+ TraceParentInfo traceParentInfo = new TraceParentInfo();
+ for (ConsumerRecord<String, String> consumerRecord : records) {
- if (busTopicParams.getPartner() != null) {
- props.setProperty("Partner", busTopicParams.getPartner());
- }
- if (dme2RouteOffer != null) {
- props.setProperty(PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer);
+ Headers consumerRecordHeaders = consumerRecord.headers();
+ traceParentInfo = processTraceParentHeader(consumerRecordHeaders);
}
- props.setProperty("Latitude", busTopicParams.getLatitude());
- props.setProperty("Longitude", busTopicParams.getLongitude());
-
- /* These are optional, will default to these values if not set in additionalProps */
- props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", "50000");
- props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", "240000");
- props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", "15000");
- props.setProperty("Version", "1.0");
- props.setProperty("SubContextPath", "/");
- props.setProperty("sessionstickinessrequired", "no");
-
- /* These should not change */
- props.setProperty("TransportType", "DME2");
- props.setProperty("MethodType", "GET");
-
- if (busTopicParams.isUseHttps()) {
- props.setProperty(PROTOCOL_PROP, "https");
+ SpanContext spanContext = SpanContext.createFromRemoteParent(
+ traceParentInfo.getTraceId(), traceParentInfo.getSpanId(),
+ TraceFlags.getSampled(), TraceState.builder().build());
- } else {
- props.setProperty(PROTOCOL_PROP, "http");
- }
+ Context.current().with(Span.wrap(spanContext)).makeCurrent();
+ }
- props.setProperty("contenttype", "application/json");
+ private TraceParentInfo processTraceParentHeader(Headers headers) {
+ TraceParentInfo traceParentInfo = new TraceParentInfo();
+ if (headers.lastHeader("traceparent") != null) {
+ traceParentInfo.setParentTraceId(new String(headers.lastHeader(
+ "traceparent").value(), StandardCharsets.UTF_8));
- if (busTopicParams.isAdditionalPropsValid()) {
- for (Map.Entry<String, String> entry : busTopicParams.getAdditionalProps().entrySet()) {
- props.put(entry.getKey(), entry.getValue());
- }
+ String[] parts = traceParentInfo.getParentTraceId().split("-");
+ traceParentInfo.setTraceId(parts[1]);
+ traceParentInfo.setSpanId(parts[2]);
}
- MRClientFactory.prop = props;
- this.consumer.setProps(props);
+ return traceParentInfo;
+ }
- logger.info("{}: CREATION", this);
+ @Data
+ @NoArgsConstructor
+ private static class TraceParentInfo {
+ private String parentTraceId;
+ private String traceId;
+ private String spanId;
}
- private IllegalArgumentException parmException(String topic, String propnm) {
- return new IllegalArgumentException("Missing " + PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "."
- + topic + propnm + " property for DME2 in DMaaP");
+ @Override
+ public void close() {
+ super.close();
+ this.consumer.close();
+ logger.info("Kafka Consumer exited {}", this);
+ }
+ @Override
+ public String toString() {
+ return "KafkaConsumerWrapper [fetchTimeout=" + fetchTimeout + "]";
}
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java
index 469794c7..e2adde0d 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java
@@ -2,8 +2,10 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2020,2023 Bell Canada. All rights reserved.
+ * Modifications Copyright (C) 2022-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.
@@ -24,26 +26,25 @@ package org.onap.policy.common.endpoints.event.comm.bus.internal;
import com.att.nsa.apiClient.http.HttpClient.ConnectionType;
import com.att.nsa.cambria.client.CambriaBatchingPublisher;
import com.att.nsa.cambria.client.CambriaClientBuilders;
-import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
-import com.fasterxml.jackson.annotation.JsonIgnore;
+import io.opentelemetry.instrumentation.kafkaclients.v2_6.TracingProducerInterceptor;
import java.net.MalformedURLException;
import java.security.GeneralSecurityException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher;
-import org.onap.dmaap.mr.client.response.MRPublisherResponse;
-import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
-import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
+import java.util.UUID;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public interface BusPublisher {
+ String NO_MESSAGE_PROVIDED = "No message provided";
+ String LOG_CLOSE = "{}: CLOSE";
+ String LOG_CLOSE_FAILED = "{}: CLOSE FAILED";
+
/**
* sends a message.
*
@@ -52,24 +53,23 @@ public interface BusPublisher {
* @return true if success, false otherwise
* @throws IllegalArgumentException if no message provided
*/
- public boolean send(String partitionId, String message);
+ boolean send(String partitionId, String message);
/**
* closes the publisher.
*/
- public void close();
+ void close();
/**
* Cambria based library publisher.
*/
- public static class CambriaPublisherWrapper implements BusPublisher {
+ class CambriaPublisherWrapper implements BusPublisher {
- private static Logger logger = LoggerFactory.getLogger(CambriaPublisherWrapper.class);
+ private static final Logger logger = LoggerFactory.getLogger(CambriaPublisherWrapper.class);
/**
* The actual Cambria publisher.
*/
- @JsonIgnore
@GsonJsonIgnore
protected CambriaBatchingPublisher publisher;
@@ -80,7 +80,7 @@ public interface BusPublisher {
*/
public CambriaPublisherWrapper(BusTopicParams busTopicParams) {
- PublisherBuilder builder = new CambriaClientBuilders.PublisherBuilder();
+ var builder = new CambriaClientBuilders.PublisherBuilder();
builder.usingHosts(busTopicParams.getServers()).onTopic(busTopicParams.getTopic());
@@ -95,7 +95,6 @@ public interface BusPublisher {
}
}
-
if (busTopicParams.isApiKeyValid() && busTopicParams.isApiSecretValid()) {
builder.authenticatedBy(busTopicParams.getApiKey(), busTopicParams.getApiSecret());
}
@@ -114,7 +113,7 @@ public interface BusPublisher {
@Override
public boolean send(String partitionId, String message) {
if (message == null) {
- throw new IllegalArgumentException("No message provided");
+ throw new IllegalArgumentException(NO_MESSAGE_PROVIDED);
}
try {
@@ -128,7 +127,7 @@ public interface BusPublisher {
@Override
public void close() {
- logger.info("{}: CLOSE", this);
+ logger.info(LOG_CLOSE, this);
try {
this.publisher.close();
@@ -137,7 +136,6 @@ public interface BusPublisher {
}
}
-
@Override
public String toString() {
return "CambriaPublisherWrapper []";
@@ -146,245 +144,90 @@ public interface BusPublisher {
}
/**
- * DmaapClient library wrapper.
+ * Kafka based library publisher.
*/
- public abstract class DmaapPublisherWrapper implements BusPublisher {
+ class KafkaPublisherWrapper implements BusPublisher {
- private static Logger logger = LoggerFactory.getLogger(DmaapPublisherWrapper.class);
+ private static final Logger logger = LoggerFactory.getLogger(KafkaPublisherWrapper.class);
+ private static final String KEY_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer";
+
+ private final String topic;
/**
- * MR based Publisher.
+ * Kafka publisher.
*/
- protected MRSimplerBatchPublisher publisher;
- protected Properties props;
+ private final Producer<String, String> producer;
+ protected Properties kafkaProps;
/**
- * MR Publisher Wrapper.
+ * Kafka Publisher Wrapper.
*
- * @param servers messaging bus hosts
- * @param topic topic
- * @param username AAF or DME2 Login
- * @param password AAF or DME2 Password
+ * @param busTopicParams topic parameters
*/
- public DmaapPublisherWrapper(ProtocolTypeConstants protocol, List<String> servers, String topic,
- String username, String password, boolean useHttps) {
-
+ protected KafkaPublisherWrapper(BusTopicParams busTopicParams) {
- if (StringUtils.isBlank(topic)) {
- throw new IllegalArgumentException("No topic for DMaaP");
+ if (busTopicParams.isTopicInvalid()) {
+ throw new IllegalArgumentException("No topic for Kafka");
}
+ this.topic = busTopicParams.getTopic();
- configureProtocol(topic, protocol, servers, useHttps);
-
- this.publisher.logTo(LoggerFactory.getLogger(MRSimplerBatchPublisher.class.getName()));
-
- this.publisher.setUsername(username);
- this.publisher.setPassword(password);
-
- props = new Properties();
-
- props.setProperty("Protocol", (useHttps ? "https" : "http"));
- props.setProperty("contenttype", "application/json");
- props.setProperty("username", username);
- props.setProperty("password", password);
-
- props.setProperty("topic", topic);
-
- this.publisher.setProps(props);
+ // Setup Properties for consumer
+ kafkaProps = new Properties();
+ kafkaProps.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, busTopicParams.getServers().get(0));
+ if (busTopicParams.isAdditionalPropsValid()) {
+ kafkaProps.putAll(busTopicParams.getAdditionalProps());
+ }
+ if (kafkaProps.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG) == null) {
+ kafkaProps.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, KEY_SERIALIZER);
+ }
+ if (kafkaProps.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG) == null) {
+ kafkaProps.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KEY_SERIALIZER);
+ }
- if (protocol == ProtocolTypeConstants.AAF_AUTH) {
- this.publisher.setHost(servers.get(0));
+ if (busTopicParams.isAllowTracing()) {
+ kafkaProps.setProperty(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG,
+ TracingProducerInterceptor.class.getName());
}
- logger.info("{}: CREATION: using protocol {}", this, protocol.getValue());
+ producer = new KafkaProducer<>(kafkaProps);
}
- private void configureProtocol(String topic, ProtocolTypeConstants protocol, List<String> servers,
- boolean useHttps) {
-
- if (protocol == ProtocolTypeConstants.AAF_AUTH) {
- if (servers == null || servers.isEmpty()) {
- throw new IllegalArgumentException("No DMaaP servers or DME2 partner provided");
- }
-
- ArrayList<String> dmaapServers = new ArrayList<>();
- String port = useHttps ? ":3905" : ":3904";
- for (String server : servers) {
- dmaapServers.add(server + port);
- }
-
-
- this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
-
- this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
-
- } else if (protocol == ProtocolTypeConstants.DME2) {
- ArrayList<String> dmaapServers = new ArrayList<>();
- dmaapServers.add("0.0.0.0:3904");
-
- this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
+ @Override
+ public boolean send(String partitionId, String message) {
+ if (message == null) {
+ throw new IllegalArgumentException(NO_MESSAGE_PROVIDED);
+ }
- this.publisher.setProtocolFlag(ProtocolTypeConstants.DME2.getValue());
+ try {
+ // Create the record
+ ProducerRecord<String, String> producerRecord =
+ new ProducerRecord<>(topic, UUID.randomUUID().toString(), message);
- } else {
- throw new IllegalArgumentException("Invalid DMaaP protocol " + protocol);
+ this.producer.send(producerRecord);
+ producer.flush();
+ } catch (Exception e) {
+ logger.warn("{}: SEND of {} cannot be performed because of {}", this, message, e.getMessage(), e);
+ return false;
}
+ return true;
}
@Override
public void close() {
- logger.info("{}: CLOSE", this);
+ logger.info(LOG_CLOSE, this);
try {
- this.publisher.close(1, TimeUnit.SECONDS);
+ this.producer.close();
} catch (Exception e) {
logger.warn("{}: CLOSE FAILED because of {}", this, e.getMessage(), e);
}
}
@Override
- public boolean send(String partitionId, String message) {
- if (message == null) {
- throw new IllegalArgumentException("No message provided");
- }
-
- this.publisher.setPubResponse(new MRPublisherResponse());
- this.publisher.send(partitionId, message);
- MRPublisherResponse response = this.publisher.sendBatchWithResponse();
- if (response != null) {
- logger.debug("DMaaP publisher received {} : {}", response.getResponseCode(),
- response.getResponseMessage());
- }
-
- return true;
- }
-
- @Override
public String toString() {
- return "DmaapPublisherWrapper [" + "publisher.getAuthDate()=" + publisher.getAuthDate()
- + ", publisher.getAuthKey()=" + publisher.getAuthKey() + ", publisher.getHost()="
- + publisher.getHost() + ", publisher.getProtocolFlag()=" + publisher.getProtocolFlag()
- + ", publisher.getUsername()=" + publisher.getUsername() + "]";
+ return "KafkaPublisherWrapper []";
}
- }
- /**
- * DmaapClient library wrapper.
- */
- public static class DmaapAafPublisherWrapper extends DmaapPublisherWrapper {
- /**
- * MR based Publisher.
- */
- public DmaapAafPublisherWrapper(List<String> servers, String topic, String aafLogin, String aafPassword,
- boolean useHttps) {
-
- super(ProtocolTypeConstants.AAF_AUTH, servers, topic, aafLogin, aafPassword, useHttps);
- }
- }
-
- public static class DmaapDmePublisherWrapper extends DmaapPublisherWrapper {
-
- /**
- * Constructor.
- *
- * @param busTopicParams topic parameters
- */
- public DmaapDmePublisherWrapper(BusTopicParams busTopicParams) {
-
- super(ProtocolTypeConstants.DME2, busTopicParams.getServers(),busTopicParams.getTopic(),
- busTopicParams.getUserName(),busTopicParams.getPassword(),busTopicParams.isUseHttps());
-
- String dme2RouteOffer = busTopicParams.isAdditionalPropsValid()
- ? busTopicParams.getAdditionalProps().get(
- PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY)
- : null;
-
- validateParams(busTopicParams, dme2RouteOffer);
-
- String serviceName = busTopicParams.getServers().get(0);
-
- /* These are required, no defaults */
- props.setProperty("Environment", busTopicParams.getEnvironment());
- props.setProperty("AFT_ENVIRONMENT", busTopicParams.getAftEnvironment());
-
- props.setProperty(PolicyEndPointProperties.DME2_SERVICE_NAME_PROPERTY, serviceName);
-
- if (busTopicParams.getPartner() != null) {
- props.setProperty("Partner", busTopicParams.getPartner());
- }
- if (dme2RouteOffer != null) {
- props.setProperty(PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer);
- }
-
- props.setProperty("Latitude", busTopicParams.getLatitude());
- props.setProperty("Longitude", busTopicParams.getLongitude());
-
- // ServiceName also a default, found in additionalProps
-
- /* These are optional, will default to these values if not set in optionalProps */
- props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", "50000");
- props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", "240000");
- props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", "15000");
- props.setProperty("Version", "1.0");
- props.setProperty("SubContextPath", "/");
- props.setProperty("sessionstickinessrequired", "no");
-
- /* These should not change */
- props.setProperty("TransportType", "DME2");
- props.setProperty("MethodType", "POST");
-
- if (busTopicParams.isAdditionalPropsValid()) {
- addAdditionalProps(busTopicParams);
- }
-
- this.publisher.setProps(props);
- }
-
- private void validateParams(BusTopicParams busTopicParams, String dme2RouteOffer) {
- if (busTopicParams.isEnvironmentInvalid()) {
- throw parmException(busTopicParams.getTopic(),
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX);
- }
- if (busTopicParams.isAftEnvironmentInvalid()) {
- throw parmException(busTopicParams.getTopic(),
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX);
- }
- if (busTopicParams.isLatitudeInvalid()) {
- throw parmException(busTopicParams.getTopic(),
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX);
- }
- if (busTopicParams.isLongitudeInvalid()) {
- throw parmException(busTopicParams.getTopic(),
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX);
- }
-
- if ((busTopicParams.isPartnerInvalid())
- && StringUtils.isBlank(dme2RouteOffer)) {
- throw new IllegalArgumentException(
- "Must provide at least " + PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "."
- + busTopicParams.getTopic()
- + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX + " or "
- + PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + busTopicParams.getTopic()
- + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX + " for DME2");
- }
- }
-
- private void addAdditionalProps(BusTopicParams busTopicParams) {
- for (Map.Entry<String, String> entry : busTopicParams.getAdditionalProps().entrySet()) {
- String key = entry.getKey();
- String value = entry.getValue();
-
- if (value != null) {
- props.setProperty(key, value);
- }
- }
- }
-
- private IllegalArgumentException parmException(String topic, String propnm) {
- return new IllegalArgumentException("Missing " + PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "."
- + topic + propnm + " property for DME2 in DMaaP");
-
- }
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBase.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBase.java
index ccf25753..f8236d3d 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBase.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBase.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020 Bell Canada. 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.
@@ -20,11 +21,13 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import lombok.Getter;
import org.onap.policy.common.endpoints.event.comm.bus.ApiKeyEnabled;
/**
* Bus Topic Base.
*/
+@Getter
public abstract class BusTopicBase extends TopicBase implements ApiKeyEnabled {
/**
@@ -43,58 +46,37 @@ public abstract class BusTopicBase extends TopicBase implements ApiKeyEnabled {
protected boolean useHttps;
/**
+ * Allow tracing.
+ */
+ protected boolean allowTracing;
+
+ /**
* allow self signed certificates.
*/
protected boolean allowSelfSignedCerts;
/**
* Instantiates a new Bus Topic Base.
- *
+ *
* <p>servers list of servers
* topic topic name
* apiKey API Key
* apiSecret API Secret
* useHttps does connection use HTTPS?
+ * allowTracing Is tracing allowed?
* allowSelfSignedCerts are self-signed certificates allow
* @param busTopicParams holds all our parameters
* @throws IllegalArgumentException if invalid parameters are present
*/
- public BusTopicBase(BusTopicParams busTopicParams) {
+ protected BusTopicBase(BusTopicParams busTopicParams) {
super(busTopicParams.getServers(), busTopicParams.getTopic(), busTopicParams.getEffectiveTopic());
this.apiKey = busTopicParams.getApiKey();
this.apiSecret = busTopicParams.getApiSecret();
this.useHttps = busTopicParams.isUseHttps();
+ this.allowTracing = busTopicParams.isAllowTracing();
this.allowSelfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
}
- @Override
- public String getApiKey() {
- return apiKey;
- }
-
- @Override
- public String getApiSecret() {
- return apiSecret;
- }
-
- /**
- * Is using HTTPS.
- *
- * @return if using https
- */
- public boolean isUseHttps() {
- return useHttps;
- }
-
- /**
- * Is self signed certificates allowed.
- *
- * @return if self signed certificates are allowed
- */
- public boolean isAllowSelfSignedCerts() {
- return allowSelfSignedCerts;
- }
-
protected boolean anyNullOrEmpty(String... args) {
for (String arg : args) {
if (arg == null || arg.isEmpty()) {
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParams.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParams.java
index 9df7221f..53a6ab66 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParams.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParams.java
@@ -3,8 +3,8 @@
* ONAP
* ================================================================================
* Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- * Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2018-2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019, 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.
@@ -24,21 +24,23 @@ package org.onap.policy.common.endpoints.event.comm.bus.internal;
import java.util.List;
import java.util.Map;
+import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
/**
* Member variables of this Params class are as follows.
*
- * <p>servers DMaaP servers
- * topic DMaaP Topic to be monitored
- * apiKey DMaaP API Key (optional)
- * apiSecret DMaaP API Secret (optional)
- * consumerGroup DMaaP Reader Consumer Group
- * consumerInstance DMaaP Reader Instance
- * fetchTimeout DMaaP fetch timeout
- * fetchLimit DMaaP fetch limit
+ * <p>servers Kafka servers
+ * topic Kafka Topic to be monitored
+ * apiKey Kafka API Key (optional)
+ * apiSecret Kafka API Secret (optional)
+ * consumerGroup kafka Reader Consumer Group
+ * consumerInstance Kafka Reader Instance
+ * fetchTimeout kafka fetch timeout
+ * fetchLimit Kafka fetch limit
* environment DME2 Environment
* aftEnvironment DME2 AFT Environment
* partner DME2 Partner
@@ -46,6 +48,7 @@ import org.apache.commons.lang3.StringUtils;
* longitude DME2 Longitude
* additionalProps Additional properties to pass to DME2
* useHttps does connection use HTTPS?
+ * allowTracing is message tracing allowed?
* allowSelfSignedCerts are self-signed certificates allow
*/
@Getter
@@ -64,6 +67,7 @@ public class BusTopicParams {
private int fetchTimeout;
private int fetchLimit;
private boolean useHttps;
+ private boolean allowTracing;
private boolean allowSelfSignedCerts;
private boolean managed;
@@ -78,6 +82,7 @@ public class BusTopicParams {
private String clientName;
private String hostname;
private String basePath;
+ @Getter
private String serializationProvider;
public static TopicParamsBuilder builder() {
@@ -165,29 +170,43 @@ public class BusTopicParams {
return additionalProps != null;
}
- public String getSerializationProvider() {
- return serializationProvider;
+ public void setEffectiveTopic(String effectiveTopic) {
+ this.effectiveTopic = topicToLowerCase(effectiveTopic);
}
+ public void setTopic(String topic) {
+ this.topic = topicToLowerCase(topic);
+ }
+
+ public String getEffectiveTopic() {
+ return topicToLowerCase(effectiveTopic);
+ }
+
+ public String getTopic() {
+ return topicToLowerCase(topic);
+ }
+
+ private String topicToLowerCase(String topic) {
+ return (topic == null || topic.isEmpty()) ? topic : topic.toLowerCase();
+ }
+
+ @NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class TopicParamsBuilder {
final BusTopicParams params = new BusTopicParams();
- private TopicParamsBuilder() {
- }
-
public TopicParamsBuilder servers(List<String> servers) {
this.params.servers = servers;
return this;
}
public TopicParamsBuilder topic(String topic) {
- this.params.topic = topic;
+ this.params.setTopic(topic);
return this;
}
public TopicParamsBuilder effectiveTopic(String effectiveTopic) {
- this.params.effectiveTopic = effectiveTopic;
+ this.params.setEffectiveTopic(effectiveTopic);
return this;
}
@@ -226,6 +245,11 @@ public class BusTopicParams {
return this;
}
+ public TopicParamsBuilder allowTracing(boolean allowTracing) {
+ this.params.allowTracing = allowTracing;
+ return this;
+ }
+
public TopicParamsBuilder allowSelfSignedCerts(boolean allowSelfSignedCerts) {
this.params.allowSelfSignedCerts = allowSelfSignedCerts;
return this;
@@ -309,7 +333,6 @@ public class BusTopicParams {
this.params.serializationProvider = serializationProvider;
return this;
}
-
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSink.java
index e94bdffa..dfdc7b3c 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSink.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSink.java
@@ -2,8 +2,10 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
+ * 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.
@@ -22,7 +24,8 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
import java.util.UUID;
-
+import lombok.Getter;
+import lombok.Setter;
import org.onap.policy.common.endpoints.event.comm.bus.BusTopicSink;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
@@ -31,7 +34,7 @@ import org.slf4j.LoggerFactory;
/**
* Transport Agnostic Bus Topic Sink to carry out the core functionality to interact with a sink
- * regardless if it is UEB or DMaaP.
+ * regardless if it is UEB or Kafka.
*
*/
public abstract class InlineBusTopicSink extends BusTopicBase implements BusTopicSink {
@@ -44,7 +47,9 @@ public abstract class InlineBusTopicSink extends BusTopicBase implements BusTopi
/**
* The partition key to publish to.
*/
- protected String partitionId;
+ @Getter
+ @Setter
+ protected String partitionKey;
/**
* Message bus publisher.
@@ -60,17 +65,18 @@ public abstract class InlineBusTopicSink extends BusTopicBase implements BusTopi
* apiSecret api secret
* partitionId partition id
* useHttps does connection use HTTPS?
+ * allowTracing is tracing allowed?
* allowSelfSignedCerts are self-signed certificates allow *
- * @throws IllegalArgumentException in invalid parameters are passed in
+ * @throws IllegalArgumentException if invalid parameters are passed in
*/
- public InlineBusTopicSink(BusTopicParams busTopicParams) {
+ protected InlineBusTopicSink(BusTopicParams busTopicParams) {
super(busTopicParams);
if (busTopicParams.isPartitionIdInvalid()) {
- this.partitionId = UUID.randomUUID().toString();
+ this.partitionKey = UUID.randomUUID().toString();
} else {
- this.partitionId = busTopicParams.getPartitionId();
+ this.partitionKey = busTopicParams.getPartitionId();
}
}
@@ -84,17 +90,14 @@ public abstract class InlineBusTopicSink extends BusTopicBase implements BusTopi
logger.info("{}: starting", this);
synchronized (this) {
+ if (!this.alive) {
+ if (locked) {
+ throw new IllegalStateException(this + " is locked.");
+ }
- if (this.alive) {
- return true;
- }
-
- if (locked) {
- throw new IllegalStateException(this + " is locked.");
+ this.init();
+ this.alive = true;
}
-
- this.init();
- this.alive = true;
}
return true;
@@ -142,7 +145,7 @@ public abstract class InlineBusTopicSink extends BusTopicBase implements BusTopi
NetLoggerUtil.log(EventType.OUT, this.getTopicCommInfrastructure(), this.topic, message);
- publisher.send(this.partitionId, message);
+ publisher.send(this.partitionKey, message);
broadcast(message);
} catch (Exception e) {
logger.warn("{}: cannot send because of {}", this, e.getMessage(), e);
@@ -153,44 +156,13 @@ public abstract class InlineBusTopicSink extends BusTopicBase implements BusTopi
}
@Override
- public void setPartitionKey(String partitionKey) {
- this.partitionId = partitionKey;
- }
-
- @Override
- public String getPartitionKey() {
- return this.partitionId;
- }
-
- @Override
public void shutdown() {
this.stop();
}
@Override
- protected boolean anyNullOrEmpty(String... args) {
- for (String arg : args) {
- if (arg == null || arg.isEmpty()) {
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- protected boolean allNullOrEmpty(String... args) {
- for (String arg : args) {
- if (!(arg == null || arg.isEmpty())) {
- return false;
- }
- }
-
- return true;
- }
-
- @Override
public String toString() {
- return "InlineBusTopicSink [partitionId=" + partitionId + ", alive=" + alive + ", publisher=" + publisher + "]";
+ return "InlineBusTopicSink [partitionId=" + partitionKey + ", alive=" + alive + ", publisher=" + publisher
+ + "]";
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSink.java
deleted file mode 100644
index ba556bb8..00000000
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSink.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
- * ================================================================================
- * 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.endpoints.event.comm.bus.internal;
-
-import java.util.Map;
-
-import org.onap.policy.common.endpoints.event.comm.Topic;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSink;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This implementation publishes events for the associated DMAAP topic, inline with the calling
- * thread.
- */
-public class InlineDmaapTopicSink extends InlineBusTopicSink implements DmaapTopicSink {
-
- protected static Logger logger = LoggerFactory.getLogger(InlineDmaapTopicSink.class);
-
- protected final String userName;
- protected final String password;
-
- protected String environment = null;
- protected String aftEnvironment = null;
- protected String partner = null;
- protected String latitude = null;
- protected String longitude = null;
-
- protected Map<String, String> additionalProps = null;
-
- /**
- * BusTopicParams contains the below mentioned attributes.
- * servers DMaaP servers
- * topic DMaaP Topic to be monitored
- * apiKey DMaaP API Key (optional)
- * apiSecret DMaaP API Secret (optional)
- * environment DME2 Environment
- * aftEnvironment DME2 AFT Environment
- * partner DME2 Partner
- * latitude DME2 Latitude
- * longitude DME2 Longitude
- * additionalProps Additional properties to pass to DME2
- * useHttps does connection use HTTPS?
- * allowSelfSignedCerts are self-signed certificates allow
- * @param busTopicParams Contains the above mentioned parameters
- * @throws IllegalArgumentException An invalid parameter passed in
- */
- public InlineDmaapTopicSink(BusTopicParams busTopicParams) {
-
- super(busTopicParams);
-
- this.userName = busTopicParams.getUserName();
- this.password = busTopicParams.getPassword();
-
- this.environment = busTopicParams.getEnvironment();
- this.aftEnvironment = busTopicParams.getAftEnvironment();
- this.partner = busTopicParams.getPartner();
-
- this.latitude = busTopicParams.getLatitude();
- this.longitude = busTopicParams.getLongitude();
-
- this.additionalProps = busTopicParams.getAdditionalProps();
- }
-
-
- @Override
- public void init() {
- if (allNullOrEmpty(this.environment, this.aftEnvironment, this.latitude, this.longitude, this.partner)) {
- this.publisher = new BusPublisher.CambriaPublisherWrapper(BusTopicParams.builder()
- .servers(this.servers)
- .topic(this.effectiveTopic)
- .apiKey(this.apiKey)
- .apiSecret(this.apiSecret)
- .userName(this.userName)
- .password(this.password)
- .useHttps(this.useHttps)
- .allowSelfSignedCerts(this.allowSelfSignedCerts)
- .build());
- } else {
- this.publisher = new BusPublisher.DmaapDmePublisherWrapper(BusTopicParams.builder()
- .servers(this.servers)
- .topic(this.effectiveTopic)
- .userName(this.userName)
- .password(this.password)
- .environment(this.environment)
- .aftEnvironment(this.aftEnvironment)
- .partner(this.partner)
- .latitude(this.latitude)
- .longitude(this.longitude)
- .additionalProps(this.additionalProps)
- .useHttps(this.useHttps)
- .build());
- }
-
- logger.info("{}: DMAAP SINK created", this);
- }
-
- @Override
- public CommInfrastructure getTopicCommInfrastructure() {
- return Topic.CommInfrastructure.DMAAP;
- }
-
-
- @Override
- public String toString() {
- return "InlineDmaapTopicSink [userName=" + userName + ", password=" + password
- + ", getTopicCommInfrastructure()=" + getTopicCommInfrastructure() + ", toString()=" + super.toString()
- + "]";
- }
-
-}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSink.java
new file mode 100644
index 00000000..6354f762
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSink.java
@@ -0,0 +1,82 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2022-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.endpoints.event.comm.bus.internal;
+
+import java.util.Map;
+import org.onap.policy.common.endpoints.event.comm.Topic;
+import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicSink;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This implementation publishes events for the associated KAFKA topic, inline with the calling
+ * thread.
+ */
+public class InlineKafkaTopicSink extends InlineBusTopicSink implements KafkaTopicSink {
+
+ /**
+ * Logger.
+ */
+ private static final Logger logger = LoggerFactory.getLogger(InlineKafkaTopicSink.class);
+
+ protected Map<String, String> additionalProps;
+
+ /**
+ * Argument-based KAFKA Topic Writer instantiation. BusTopicParams contains the below
+ * attributes.
+ *
+ * <p>servers list of KAFKA servers available for publishing
+ * topic the topic to publish to
+ * partitionId the partition key (optional, autogenerated if not provided)
+ * useHttps does connection use HTTPS?
+ * @param busTopicParams contains attributes needed
+ * @throws IllegalArgumentException if invalid arguments are detected
+ */
+ public InlineKafkaTopicSink(BusTopicParams busTopicParams) {
+ super(busTopicParams);
+ this.additionalProps = busTopicParams.getAdditionalProps();
+ }
+
+ /**
+ * Instantiation of internal resources.
+ */
+ @Override
+ public void init() {
+
+ this.publisher = new BusPublisher.KafkaPublisherWrapper(BusTopicParams.builder()
+ .servers(this.servers)
+ .topic(this.effectiveTopic)
+ .useHttps(this.useHttps)
+ .allowTracing(this.allowTracing)
+ .additionalProps(this.additionalProps)
+ .build());
+ logger.info("{}: KAFKA SINK created", this);
+ }
+
+ @Override
+ public String toString() {
+ return "InlineKafkaTopicSink [getTopicCommInfrastructure()=" + getTopicCommInfrastructure() + ", toString()="
+ + super.toString() + "]";
+ }
+
+ @Override
+ public CommInfrastructure getTopicCommInfrastructure() {
+ return Topic.CommInfrastructure.KAFKA;
+ }
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSink.java
index f258d5d9..896cb3bb 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSink.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSink.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -47,6 +47,7 @@ public class InlineUebTopicSink extends InlineBusTopicSink implements UebTopicSi
* apiSecret the api secret (optional)
* partitionId the partition key (optional, autogenerated if not provided)
* useHttps does connection use HTTPS?
+ * allowTracing is tracing allowed?
* allowSelfSignedCerts are self-signed certificates allow
* @param busTopicParams contains attributes needed
* @throws IllegalArgumentException if invalid arguments are detected
@@ -67,6 +68,7 @@ public class InlineUebTopicSink extends InlineBusTopicSink implements UebTopicSi
.apiKey(this.apiKey)
.apiSecret(this.apiSecret)
.useHttps(this.useHttps)
+ .allowTracing(this.allowTracing)
.allowSelfSignedCerts(this.allowSelfSignedCerts)
.build());
logger.info("{}: UEB SINK created", this);
@@ -74,10 +76,8 @@ public class InlineUebTopicSink extends InlineBusTopicSink implements UebTopicSi
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("InlineUebTopicSink [getTopicCommInfrastructure()=").append(getTopicCommInfrastructure())
- .append(", toString()=").append(super.toString()).append("]");
- return builder.toString();
+ return "InlineUebTopicSink [getTopicCommInfrastructure()=" + getTopicCommInfrastructure() + ", toString()="
+ + super.toString() + "]";
}
@Override
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSource.java
index 164f2b16..f98b481f 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSource.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSource.java
@@ -2,8 +2,9 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2020 Bell Canada. 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.
@@ -24,11 +25,9 @@ package org.onap.policy.common.endpoints.event.comm.bus.internal;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.UUID;
-
-import org.onap.policy.common.endpoints.event.comm.FilterableTopicSource;
+import lombok.Getter;
import org.onap.policy.common.endpoints.event.comm.TopicListener;
import org.onap.policy.common.endpoints.event.comm.bus.BusTopicSource;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.FilterableBusConsumer;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
@@ -41,32 +40,36 @@ import org.slf4j.LoggerFactory;
* notifying its listeners.
*/
public abstract class SingleThreadedBusTopicSource extends BusTopicBase
- implements Runnable, BusTopicSource, FilterableTopicSource {
+ implements Runnable, BusTopicSource {
/**
* Not to be converted to PolicyLogger. This will contain all instract /out traffic and only
* that in a single file in a concise format.
*/
- private static Logger logger = LoggerFactory.getLogger(InlineBusTopicSink.class);
+ private static Logger logger = LoggerFactory.getLogger(SingleThreadedBusTopicSource.class);
/**
* Bus consumer group.
*/
+ @Getter
protected final String consumerGroup;
/**
* Bus consumer instance.
*/
+ @Getter
protected final String consumerInstance;
/**
* Bus fetch timeout.
*/
+ @Getter
protected final int fetchTimeout;
/**
* Bus fetch limit.
*/
+ @Getter
protected final int fetchLimit;
/**
@@ -87,19 +90,24 @@ public abstract class SingleThreadedBusTopicSource extends BusTopicBase
*
* @throws IllegalArgumentException An invalid parameter passed in
*/
- public SingleThreadedBusTopicSource(BusTopicParams busTopicParams) {
+ protected SingleThreadedBusTopicSource(BusTopicParams busTopicParams) {
super(busTopicParams);
- if (busTopicParams.isConsumerGroupInvalid()) {
+ if (busTopicParams.isConsumerGroupInvalid() && busTopicParams.isConsumerInstanceInvalid()) {
this.consumerGroup = UUID.randomUUID().toString();
- } else {
+ this.consumerInstance = NetworkUtil.getHostname();
+
+ } else if (busTopicParams.isConsumerGroupInvalid()) {
+ this.consumerGroup = UUID.randomUUID().toString();
+ this.consumerInstance = busTopicParams.getConsumerInstance();
+
+ } else if (busTopicParams.isConsumerInstanceInvalid()) {
this.consumerGroup = busTopicParams.getConsumerGroup();
- }
+ this.consumerInstance = UUID.randomUUID().toString();
- if (busTopicParams.isConsumerInstanceInvalid()) {
- this.consumerInstance = NetworkUtil.getHostname();
} else {
+ this.consumerGroup = busTopicParams.getConsumerGroup();
this.consumerInstance = busTopicParams.getConsumerInstance();
}
@@ -134,8 +142,7 @@ public abstract class SingleThreadedBusTopicSource extends BusTopicBase
logger.info("{}: register: start not attempted", this);
}
} catch (Exception e) {
- logger.warn("{}: cannot start after registration of because of: {}", this, topicListener, e.getMessage(),
- e);
+ logger.warn("{}: cannot start after registration of because of: {}", this, topicListener, e);
}
}
@@ -176,8 +183,7 @@ public abstract class SingleThreadedBusTopicSource extends BusTopicBase
busPollerThread.start();
return true;
} catch (Exception e) {
- logger.warn("{}: cannot start because of {}", this, e.getMessage(), e);
- throw new IllegalStateException(e);
+ throw new IllegalStateException(this + ": cannot start", e);
}
}
}
@@ -227,7 +233,7 @@ public abstract class SingleThreadedBusTopicSource extends BusTopicBase
try {
fetchAllMessages();
} catch (IOException | RuntimeException e) {
- logger.error("{}: cannot fetch because of ", this, e.getMessage(), e);
+ logger.error("{}: cannot fetch", this, e);
}
}
@@ -265,17 +271,6 @@ public abstract class SingleThreadedBusTopicSource extends BusTopicBase
return broadcast(event);
}
-
- @Override
- public void setFilter(String filter) {
- if (consumer instanceof FilterableBusConsumer) {
- ((FilterableBusConsumer) consumer).setFilter(filter);
-
- } else {
- throw new UnsupportedOperationException("no server-side filtering for topic " + topic);
- }
- }
-
@Override
public String toString() {
return "SingleThreadedBusTopicSource [consumerGroup=" + consumerGroup + ", consumerInstance=" + consumerInstance
@@ -285,29 +280,8 @@ public abstract class SingleThreadedBusTopicSource extends BusTopicBase
}
@Override
- public String getConsumerGroup() {
- return consumerGroup;
- }
-
- @Override
- public String getConsumerInstance() {
- return consumerInstance;
- }
-
- @Override
public void shutdown() {
this.stop();
this.topicListeners.clear();
}
-
- @Override
- public int getFetchTimeout() {
- return fetchTimeout;
- }
-
- @Override
- public int getFetchLimit() {
- return fetchLimit;
- }
-
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSource.java
deleted file mode 100644
index e5d08a2a..00000000
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSource.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
- * ================================================================================
- * 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.endpoints.event.comm.bus.internal;
-
-import java.net.MalformedURLException;
-import java.util.Map;
-
-import org.onap.policy.common.endpoints.event.comm.Topic;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This topic reader implementation specializes in reading messages over DMAAP topic and notifying
- * its listeners.
- */
-public class SingleThreadedDmaapTopicSource extends SingleThreadedBusTopicSource implements DmaapTopicSource, Runnable {
-
- private static Logger logger = LoggerFactory.getLogger(SingleThreadedDmaapTopicSource.class);
-
-
- protected final String userName;
- protected final String password;
-
- protected String environment = null;
- protected String aftEnvironment = null;
- protected String partner = null;
- protected String latitude = null;
- protected String longitude = null;
-
- protected Map<String, String> additionalProps = null;
-
-
- /**
- * Constructor.
- *
- * @param busTopicParams Parameters object containing all the required inputs
- *
- * @throws IllegalArgumentException An invalid parameter passed in
- */
- public SingleThreadedDmaapTopicSource(BusTopicParams busTopicParams) {
-
- super(busTopicParams);
-
- this.userName = busTopicParams.getUserName();
- this.password = busTopicParams.getPassword();
-
- this.environment = busTopicParams.getEnvironment();
- this.aftEnvironment = busTopicParams.getAftEnvironment();
- this.partner = busTopicParams.getPartner();
-
- this.latitude = busTopicParams.getLatitude();
- this.longitude = busTopicParams.getLongitude();
-
- this.additionalProps = busTopicParams.getAdditionalProps();
- try {
- this.init();
- } catch (Exception e) {
- logger.error("ERROR during init in dmaap-source: cannot create topic {} because of {}",
- topic, e.getMessage(), e);
- throw new IllegalArgumentException(e);
- }
- }
-
-
- /**
- * Initialize the Cambria or MR Client.
- */
- @Override
- public void init() throws MalformedURLException {
- BusTopicParams.TopicParamsBuilder builder = BusTopicParams.builder()
- .servers(this.servers)
- .topic(this.effectiveTopic)
- .apiKey(this.apiKey)
- .apiSecret(this.apiSecret)
- .consumerGroup(this.consumerGroup)
- .consumerInstance(this.consumerInstance)
- .fetchTimeout(this.fetchTimeout)
- .fetchLimit(this.fetchLimit)
- .useHttps(this.useHttps);
-
- if (anyNullOrEmpty(this.userName, this.password)) {
- this.consumer = new BusConsumer.CambriaConsumerWrapper(builder
- .allowSelfSignedCerts(this.allowSelfSignedCerts)
- .build());
- } else if (allNullOrEmpty(this.environment, this.aftEnvironment, this.latitude, this.longitude, this.partner)) {
- this.consumer = new BusConsumer.CambriaConsumerWrapper(builder
- .userName(this.userName)
- .password(this.password)
- .allowSelfSignedCerts(this.allowSelfSignedCerts)
- .build());
- } else {
- this.consumer = new BusConsumer.DmaapDmeConsumerWrapper(builder
- .userName(this.userName)
- .password(this.password)
- .environment(this.environment)
- .aftEnvironment(this.aftEnvironment)
- .partner(this.partner)
- .latitude(this.latitude)
- .longitude(this.longitude)
- .additionalProps(this.additionalProps)
- .build());
- }
-
- logger.info("{}: INITTED", this);
- }
-
- @Override
- public CommInfrastructure getTopicCommInfrastructure() {
- return Topic.CommInfrastructure.DMAAP;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("SingleThreadedDmaapTopicSource [userName=").append(userName).append(", password=")
- .append((password == null || password.isEmpty()) ? "-" : password.length())
- .append(", getTopicCommInfrastructure()=").append(getTopicCommInfrastructure()).append(", toString()=")
- .append(super.toString()).append("]");
- return builder.toString();
- }
-
-
-}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSource.java
new file mode 100644
index 00000000..869273f0
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSource.java
@@ -0,0 +1,79 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2022-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.endpoints.event.comm.bus.internal;
+
+import java.net.MalformedURLException;
+import java.util.Map;
+import org.onap.policy.common.endpoints.event.comm.Topic;
+import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicSource;
+
+/**
+ * This topic source implementation specializes in reading messages over a Kafka Bus topic source and
+ * notifying its listeners.
+ */
+public class SingleThreadedKafkaTopicSource extends SingleThreadedBusTopicSource implements KafkaTopicSource {
+
+ protected Map<String, String> additionalProps = null;
+
+ /**
+ * Constructor.
+ *
+ * @param busTopicParams Parameters object containing all the required inputs
+ * @throws IllegalArgumentException An invalid parameter passed in
+ */
+ public SingleThreadedKafkaTopicSource(BusTopicParams busTopicParams) {
+ super(busTopicParams);
+ this.additionalProps = busTopicParams.getAdditionalProps();
+ try {
+ this.init();
+ } catch (Exception e) {
+ throw new IllegalArgumentException("ERROR during init in kafka-source: cannot create topic " + topic, e);
+ }
+ }
+
+ /**
+ * Initialize the Cambria client.
+ */
+ @Override
+ public void init() throws MalformedURLException {
+ BusTopicParams.TopicParamsBuilder builder = BusTopicParams.builder()
+ .servers(this.servers)
+ .topic(this.effectiveTopic)
+ .fetchTimeout(this.fetchTimeout)
+ .consumerGroup(this.consumerGroup)
+ .useHttps(this.useHttps)
+ .allowTracing(this.allowTracing);
+
+ this.consumer = new BusConsumer.KafkaConsumerWrapper(builder
+ .additionalProps(this.additionalProps)
+ .build());
+ }
+
+ @Override
+ public CommInfrastructure getTopicCommInfrastructure() {
+ return Topic.CommInfrastructure.KAFKA;
+ }
+
+ @Override
+ public String toString() {
+ return "SingleThreadedKafkaTopicSource [getTopicCommInfrastructure()=" + getTopicCommInfrastructure()
+ + ", toString()=" + super.toString() + "]";
+ }
+
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSource.java
index e210762d..ead04594 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSource.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSource.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -56,6 +56,7 @@ public class SingleThreadedUebTopicSource extends SingleThreadedBusTopicSource i
.fetchTimeout(this.fetchTimeout)
.fetchLimit(this.fetchLimit)
.useHttps(this.useHttps)
+ .allowTracing(this.allowTracing)
.allowSelfSignedCerts(this.allowSelfSignedCerts).build());
}
@@ -66,10 +67,8 @@ public class SingleThreadedUebTopicSource extends SingleThreadedBusTopicSource i
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("SingleThreadedUebTopicSource [getTopicCommInfrastructure()=")
- .append(getTopicCommInfrastructure()).append(", toString()=").append(super.toString()).append("]");
- return builder.toString();
+ return "SingleThreadedUebTopicSource [getTopicCommInfrastructure()=" + getTopicCommInfrastructure()
+ + ", toString()=" + super.toString() + "]";
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBase.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBase.java
index 6f07df1b..c63fbcc2 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBase.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBase.java
@@ -2,14 +2,16 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020 Bell Canada. 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.
@@ -22,19 +24,21 @@ package org.onap.policy.common.endpoints.event.comm.bus.internal;
import java.util.ArrayList;
import java.util.List;
-
+import lombok.AccessLevel;
+import lombok.Getter;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.onap.policy.common.endpoints.event.comm.Topic;
import org.onap.policy.common.endpoints.event.comm.TopicListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@Getter
public abstract class TopicBase implements Topic {
/**
* Logger.
*/
- private static Logger logger = LoggerFactory.getLogger(TopicBase.class);
+ private static final Logger logger = LoggerFactory.getLogger(TopicBase.class);
/**
* List of servers.
@@ -72,17 +76,18 @@ public abstract class TopicBase implements Topic {
/**
* All my subscribers for new message notifications.
*/
+ @Getter(AccessLevel.NONE)
protected final ArrayList<TopicListener> topicListeners = new ArrayList<>();
/**
* Instantiates a new Topic Base.
- *
+ *
* @param servers list of servers
* @param topic topic name
- *
+ *
* @throws IllegalArgumentException if invalid parameters are present
*/
- public TopicBase(List<String> servers, String topic) {
+ protected TopicBase(List<String> servers, String topic) {
this(servers, topic, topic);
}
@@ -94,7 +99,7 @@ public abstract class TopicBase implements Topic {
*
* @throws IllegalArgumentException if invalid parameters are present
*/
- public TopicBase(List<String> servers, String topic, String effectiveTopic) {
+ protected TopicBase(List<String> servers, String topic, String effectiveTopic) {
if (servers == null || servers.isEmpty()) {
throw new IllegalArgumentException("Server(s) must be provided");
@@ -112,8 +117,8 @@ public abstract class TopicBase implements Topic {
}
this.servers = servers;
- this.topic = topic;
- this.effectiveTopic = effectiveTopicCopy;
+ this.topic = topic.toLowerCase();
+ this.effectiveTopic = effectiveTopicCopy.toLowerCase();
}
@Override
@@ -152,14 +157,14 @@ public abstract class TopicBase implements Topic {
/**
* Broadcast event to all listeners.
- *
+ *
* @param message the event
* @return true if all notifications are performed with no error, false otherwise
*/
protected boolean broadcast(String message) {
List<TopicListener> snapshotListeners = this.snapshotTopicListeners();
- boolean success = true;
+ var success = true;
for (TopicListener topicListener : snapshotListeners) {
try {
topicListener.onTopicEvent(this.getTopicCommInfrastructure(), this.topic, message);
@@ -173,7 +178,7 @@ public abstract class TopicBase implements Topic {
/**
* Take a snapshot of current topic listeners.
- *
+ *
* @return the topic listeners
*/
protected synchronized List<TopicListener> snapshotTopicListeners() {
@@ -219,33 +224,8 @@ public abstract class TopicBase implements Topic {
}
@Override
- public boolean isLocked() {
- return this.locked;
- }
-
- @Override
- public String getTopic() {
- return topic;
- }
-
- @Override
- public String getEffectiveTopic() {
- return effectiveTopic;
- }
-
- @Override
- public boolean isAlive() {
- return this.alive;
- }
-
- @Override
- public List<String> getServers() {
- return servers;
- }
-
- @Override
public synchronized String[] getRecentEvents() {
- String[] events = new String[recentEvents.size()];
+ var events = new String[recentEvents.size()];
return recentEvents.toArray(events);
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClient.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClient.java
new file mode 100644
index 00000000..4f601fa8
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClient.java
@@ -0,0 +1,224 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.endpoints.event.comm.client;
+
+import jakarta.validation.constraints.NotNull;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.BlockingDeque;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.TimeUnit;
+import lombok.Getter;
+import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
+import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
+import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
+import org.onap.policy.common.endpoints.event.comm.TopicListener;
+import org.onap.policy.common.endpoints.event.comm.TopicSink;
+import org.onap.policy.common.endpoints.event.comm.TopicSource;
+import org.onap.policy.common.utils.coder.Coder;
+import org.onap.policy.common.utils.coder.CoderException;
+import org.onap.policy.common.utils.coder.StandardCoder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A "bidirectional" topic, which is a pair of topics, one of which is used to publish
+ * requests and the other to receive responses.
+ */
+@Getter
+public class BidirectionalTopicClient {
+ private static final Logger logger = LoggerFactory.getLogger(BidirectionalTopicClient.class);
+ private static final Coder coder = new StandardCoder();
+
+ private final String sinkTopic;
+ private final String sourceTopic;
+ private final TopicSink sink;
+ private final TopicSource source;
+ private final CommInfrastructure sinkTopicCommInfrastructure;
+ private final CommInfrastructure sourceTopicCommInfrastructure;
+
+ /**
+ * Used when checking whether a message sent on the sink topic can be received
+ * on the source topic. When a matching message is received on the incoming topic,
+ * {@code true} is placed on the queue. If {@link #stopWaiting()} is called or the waiting
+ * thread is interrupted, then {@code false} is placed on the queue. Whenever a value
+ * is pulled from the queue, it is immediately placed back on the queue.
+ */
+ private final BlockingDeque<Boolean> checkerQueue = new LinkedBlockingDeque<>();
+
+
+ /**
+ * Constructs the object.
+ *
+ * @param sinkTopic sink topic name
+ * @param sourceTopic source topic name
+ * @throws BidirectionalTopicClientException if either topic does not exist
+ */
+ public BidirectionalTopicClient(String sinkTopic, String sourceTopic) throws BidirectionalTopicClientException {
+ this.sinkTopic = sinkTopic.toLowerCase();
+ this.sourceTopic = sourceTopic.toLowerCase();
+
+ // init sinkClient
+ List<TopicSink> sinks = getTopicEndpointManager().getTopicSinks(sinkTopic);
+ if (sinks.isEmpty()) {
+ throw new BidirectionalTopicClientException("no sinks for topic: " + sinkTopic);
+ } else if (sinks.size() > 1) {
+ throw new BidirectionalTopicClientException("too many sinks for topic: " + sinkTopic);
+ }
+
+ this.sink = sinks.get(0);
+
+ // init source
+ List<TopicSource> sources = getTopicEndpointManager().getTopicSources(Collections.singletonList(sourceTopic));
+ if (sources.isEmpty()) {
+ throw new BidirectionalTopicClientException("no sources for topic: " + sourceTopic);
+ } else if (sources.size() > 1) {
+ throw new BidirectionalTopicClientException("too many sources for topic: " + sourceTopic);
+ }
+
+ this.source = sources.get(0);
+
+ this.sinkTopicCommInfrastructure = sink.getTopicCommInfrastructure();
+ this.sourceTopicCommInfrastructure = source.getTopicCommInfrastructure();
+ }
+
+ public boolean send(String message) {
+ return sink.send(message);
+ }
+
+ public void register(TopicListener topicListener) {
+ source.register(topicListener);
+ }
+
+ public boolean offer(String event) {
+ return source.offer(event);
+ }
+
+ public void unregister(TopicListener topicListener) {
+ source.unregister(topicListener);
+ }
+
+ /**
+ * Determines whether the topic is ready (i.e., {@link #awaitReady(Object, long)} has
+ * previously returned {@code true}).
+ *
+ * @return {@code true}, if the topic is ready to send and receive
+ */
+ public boolean isReady() {
+ return Boolean.TRUE.equals(checkerQueue.peek());
+ }
+
+ /**
+ * Waits for the bidirectional topic to become "ready" by publishing a message on the
+ * sink topic and awaiting receipt of the message on the source topic. If the message
+ * is not received within a few seconds, then it tries again. This process is
+ * continued until the message is received, {@link #stopWaiting()} is called, or this thread
+ * is interrupted. Once this returns, subsequent calls will return immediately, always
+ * with the same value.
+ *
+ * @param message message to be sent to the sink topic. Note: the equals() method must
+ * return {@code true} if and only if two messages are the same
+ * @param waitMs time to wait, in milliseconds, before re-sending the message
+ * @return {@code true} if the message was received from the source topic,
+ * {@code false} if this method was stopped or interrupted before receipt of
+ * the message
+ * @throws CoderException if the message cannot be encoded
+ */
+ public synchronized <T> boolean awaitReady(T message, long waitMs) throws CoderException {
+ // see if we already know the answer
+ if (!checkerQueue.isEmpty()) {
+ return checkerQueue.peek();
+ }
+
+ final String messageText = coder.encode(message);
+
+ // class of message to be decoded
+ final TopicListener listener = getTopicListener(message);
+
+ source.register(listener);
+
+ // loop until the message is received
+ try {
+ Boolean result;
+ do {
+ send(messageText);
+ } while ((result = checkerQueue.poll(waitMs, TimeUnit.MILLISECONDS)) == null);
+
+ // put it back on the queue
+ checkerQueue.add(result);
+
+ } catch (InterruptedException e) {
+ logger.error("interrupted waiting for topic sink {} source {}", sink.getTopic(), source.getTopic(), e);
+ Thread.currentThread().interrupt();
+ checkerQueue.add(Boolean.FALSE);
+
+ } finally {
+ source.unregister(listener);
+ }
+
+ return checkerQueue.peek();
+ }
+
+ @NotNull
+ private <T> TopicListener getTopicListener(T message) {
+ @SuppressWarnings("unchecked")
+ final Class<? extends T> clazz = (Class<? extends T>) message.getClass();
+
+ // create a listener to detect when a matching message is received
+ return (infra, topic, msg) -> {
+ try {
+ T incoming = decode(msg, clazz);
+
+ if (message.equals(incoming)) {
+ logger.info("topic {} is ready; found matching message {}", topic, incoming);
+ checkerQueue.add(Boolean.TRUE);
+ }
+
+ } catch (CoderException e) {
+ logger.warn("cannot decode message from topic {}", topic, e);
+ decodeFailed();
+ }
+ };
+ }
+
+ /**
+ * Stops any listeners that are currently stuck in {@link #awaitReady(Object)} by
+ * adding {@code false} to the queue.
+ */
+ public void stopWaiting() {
+ checkerQueue.add(Boolean.FALSE);
+ }
+
+ // these may be overridden by junit tests
+
+ protected TopicEndpoint getTopicEndpointManager() {
+ return TopicEndpointManager.getManager();
+ }
+
+ protected <T> T decode(String msg, Class<? extends T> clazz) throws CoderException {
+ return coder.decode(msg, clazz);
+ }
+
+ protected void decodeFailed() {
+ // already logged - nothing else to do
+ }
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientException.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientException.java
new file mode 100644
index 00000000..1037d3af
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientException.java
@@ -0,0 +1,53 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2020 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.endpoints.event.comm.client;
+
+import java.io.Serial;
+
+/**
+ * Exception thrown by BidirectionalTopicClient class.
+ */
+public class BidirectionalTopicClientException extends Exception {
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ public BidirectionalTopicClientException() {
+ super();
+ }
+
+ public BidirectionalTopicClientException(String message) {
+ super(message);
+ }
+
+ public BidirectionalTopicClientException(Throwable cause) {
+ super(cause);
+ }
+
+ public BidirectionalTopicClientException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public BidirectionalTopicClientException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClient.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClient.java
index 9f8b3c06..5f49ea34 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClient.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClient.java
@@ -56,9 +56,9 @@ public class TopicSinkClient {
* @throws TopicSinkClientException if the topic does not exist
*/
public TopicSinkClient(final String topic) throws TopicSinkClientException {
- final List<TopicSink> lst = getTopicSinks(topic);
+ final List<TopicSink> lst = getTopicSinks(topic.toLowerCase());
if (lst.isEmpty()) {
- throw new TopicSinkClientException("no sinks for topic: " + topic);
+ throw new TopicSinkClientException("no sinks for topic: " + topic.toLowerCase());
}
this.sink = lst.get(0);
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientException.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientException.java
index 608393b3..431d4f34 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientException.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientException.java
@@ -3,7 +3,7 @@
* ONAP PAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019, 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.
@@ -21,10 +21,13 @@
package org.onap.policy.common.endpoints.event.comm.client;
+import java.io.Serial;
+
/**
* Exception thrown by TopicSink client classes.
*/
public class TopicSinkClientException extends Exception {
+ @Serial
private static final long serialVersionUID = 1L;
public TopicSinkClientException() {
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/features/NetLoggerFeatureProviders.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/features/NetLoggerFeatureProviders.java
index 8b09f386..ba84b551 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/features/NetLoggerFeatureProviders.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/features/NetLoggerFeatureProviders.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,12 +20,15 @@
package org.onap.policy.common.endpoints.features;
+import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import org.onap.policy.common.utils.services.OrderedServiceImpl;
/**
* Providers for network logging feature.
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class NetLoggerFeatureProviders {
/**
@@ -34,8 +37,4 @@ public class NetLoggerFeatureProviders {
@Getter
private static final OrderedServiceImpl<NetLoggerFeatureApi> providers =
new OrderedServiceImpl<>(NetLoggerFeatureApi.class);
-
- private NetLoggerFeatureProviders() {
- // do nothing
- }
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClient.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClient.java
index 2fe46fb3..01deaa2d 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClient.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClient.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -20,15 +21,17 @@
package org.onap.policy.common.endpoints.http.client;
+import jakarta.ws.rs.client.Entity;
+import jakarta.ws.rs.client.InvocationCallback;
+import jakarta.ws.rs.client.WebTarget;
+import jakarta.ws.rs.core.Response;
import java.util.Map;
-
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Response;
-
+import java.util.concurrent.Future;
import org.onap.policy.common.capabilities.Startable;
/**
- * Http Client interface.
+ * Http Client interface. Supports both synchronous and asynchronous operations.
+ *
*/
public interface HttpClient extends Startable {
@@ -48,6 +51,26 @@ public interface HttpClient extends Startable {
Response get();
/**
+ * Asynchronous GET request.
+ *
+ * @param callback callback to be invoked, asynchronously, when the request completes
+ * @param path context uri path
+ * @param headers request headers
+ *
+ * @return future that can be used to cancel the request or await the response
+ */
+ Future<Response> get(InvocationCallback<Response> callback, String path, Map<String, Object> headers);
+
+ /**
+ * Asynchronous GET request.
+ *
+ * @param callback callback to be invoked, asynchronously, when the request completes
+ * @param headers request headers
+ * @return future that can be used to cancel the request or await the response
+ */
+ Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers);
+
+ /**
* PUT request.
*
* @param path context uri path
@@ -59,6 +82,19 @@ public interface HttpClient extends Startable {
Response put(String path, Entity<?> entity, Map<String, Object> headers);
/**
+ * Asynchronous PUT request.
+ *
+ * @param callback callback to be invoked, asynchronously, when the request completes
+ * @param path context uri path
+ * @param entity body
+ * @param headers headers
+ *
+ * @return future that can be used to cancel the request or await the response
+ */
+ Future<Response> put(InvocationCallback<Response> callback, String path, Entity<?> entity,
+ Map<String, Object> headers);
+
+ /**
* POST request.
*
* @param path context uri path
@@ -70,6 +106,19 @@ public interface HttpClient extends Startable {
Response post(String path, Entity<?> entity, Map<String, Object> headers);
/**
+ * Asynchronous POST request.
+ *
+ * @param callback callback to be invoked, asynchronously, when the request completes
+ * @param path context uri path
+ * @param entity body
+ * @param headers headers
+ *
+ * @return future that can be used to cancel the request or await the response
+ */
+ Future<Response> post(InvocationCallback<Response> callback, String path, Entity<?> entity,
+ Map<String, Object> headers);
+
+ /**
* DELETE request.
*
* @param path context uri path
@@ -80,6 +129,17 @@ public interface HttpClient extends Startable {
Response delete(String path, Map<String, Object> headers);
/**
+ * Asynchronous DELETE request.
+ *
+ * @param callback callback to be invoked, asynchronously, when the request completes
+ * @param path context uri path
+ * @param headers headers
+ *
+ * @return future that can be used to cancel the request or await the response
+ */
+ Future<Response> delete(InvocationCallback<Response> callback, String path, Map<String, Object> headers);
+
+ /**
* Retrieve the body from the HTTP transaction.
*
* @param response response.
@@ -134,9 +194,9 @@ public interface HttpClient extends Startable {
String getBasePath();
/**
- * Get the user name.
+ * Get the username.
*
- * @return the user name
+ * @return the username
*/
String getUserName();
@@ -154,4 +214,10 @@ public interface HttpClient extends Startable {
*/
String getBaseUrl();
+ /**
+ * Gets a web target associated with the base URL.
+ *
+ * @return a webtarget
+ */
+ WebTarget getWebTarget();
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientConfigException.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientConfigException.java
index 98ec576f..bb871fa0 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientConfigException.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientConfigException.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 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.
@@ -20,10 +21,13 @@
package org.onap.policy.common.endpoints.http.client;
+import java.io.Serial;
+
/**
* Exception generated by HttpClient builder.
*/
public class HttpClientConfigException extends Exception {
+ @Serial
private static final long serialVersionUID = 1L;
public HttpClientConfigException() {
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientFactoryInstance.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientFactoryInstance.java
index c2921640..f64be30e 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientFactoryInstance.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/HttpClientFactoryInstance.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,8 +20,11 @@
package org.onap.policy.common.endpoints.http.client;
+import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class HttpClientFactoryInstance {
/**
@@ -29,9 +32,4 @@ public class HttpClientFactoryInstance {
*/
@Getter
private static final HttpClientFactory clientFactory = new IndexedHttpClientFactory();
-
-
- private HttpClientFactoryInstance() {
- // do nothing
- }
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/IndexedHttpClientFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/IndexedHttpClientFactory.java
index edf8ff6f..5f0b1d6e 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/IndexedHttpClientFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/IndexedHttpClientFactory.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 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.
@@ -20,6 +21,7 @@
package org.onap.policy.common.endpoints.http.client;
+import com.google.re2j.Pattern;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
@@ -38,11 +40,12 @@ import org.slf4j.LoggerFactory;
* HTTP client factory implementation indexed by name.
*/
class IndexedHttpClientFactory implements HttpClientFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
/**
* Logger.
*/
- private static Logger logger = LoggerFactory.getLogger(IndexedHttpClientFactory.class);
+ private static final Logger logger = LoggerFactory.getLogger(IndexedHttpClientFactory.class);
protected HashMap<String, HttpClient> clients = new HashMap<>();
@@ -75,7 +78,7 @@ class IndexedHttpClientFactory implements HttpClientFactory {
return clientList;
}
- for (String clientName : clientNames.split("\\s*,\\s*")) {
+ for (String clientName : COMMA_SPACE_PAT.split(clientNames)) {
addClient(clientList, clientName, properties);
}
@@ -85,23 +88,22 @@ class IndexedHttpClientFactory implements HttpClientFactory {
private void addClient(ArrayList<HttpClient> clientList, String clientName, Properties properties) {
String clientPrefix = PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + clientName;
- PropertyUtils props = new PropertyUtils(properties, clientPrefix,
+ var props = new PropertyUtils(properties, clientPrefix,
(name, value, ex) ->
logger.warn("{}: {} {} is in invalid format for http client {} ", this, name, value, clientName));
- int port = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
+ var port = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
if (port < 0) {
logger.warn("No HTTP port for client in {}", clientName);
return;
}
- boolean https = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false);
-
try {
HttpClient client = this.build(BusTopicParams.builder()
.clientName(clientName)
- .useHttps(https)
- .allowSelfSignedCerts(https)
+ .useHttps(props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false))
+ .allowSelfSignedCerts(
+ props.getBoolean(PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX, false))
.hostname(props.getString(PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, null))
.port(port)
.basePath(props.getString(PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, null))
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/internal/JerseyClient.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/internal/JerseyClient.java
index 8a717712..130b6c15 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/internal/JerseyClient.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/internal/JerseyClient.java
@@ -2,9 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019, 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.
@@ -22,24 +22,29 @@
package org.onap.policy.common.endpoints.http.client.internal;
-import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.google.re2j.Pattern;
+import jakarta.ws.rs.client.Client;
+import jakarta.ws.rs.client.ClientBuilder;
+import jakarta.ws.rs.client.Entity;
+import jakarta.ws.rs.client.Invocation.Builder;
+import jakarta.ws.rs.client.InvocationCallback;
+import jakarta.ws.rs.client.WebTarget;
+import jakarta.ws.rs.core.Response;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
+import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.concurrent.Future;
import javax.net.ssl.SSLContext;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.client.Invocation.Builder;
-import javax.ws.rs.core.Response;
+import lombok.Getter;
+import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.http.client.HttpClient;
-import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
import org.onap.policy.common.utils.network.NetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,15 +52,18 @@ import org.slf4j.LoggerFactory;
/**
* Http Client implementation using a Jersey Client.
*/
+@Getter
+@ToString
public class JerseyClient implements HttpClient {
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
/**
* Logger.
*/
- private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
+ private static final Logger logger = LoggerFactory.getLogger(JerseyClient.class);
protected static final String JERSEY_DEFAULT_SERIALIZATION_PROVIDER =
- "org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider";
+ "org.onap.policy.common.gson.GsonMessageBodyHandler";
protected final String name;
protected final boolean https;
@@ -74,9 +82,14 @@ public class JerseyClient implements HttpClient {
/**
* Constructor.
*
- * <p>name the name https is it https or not selfSignedCerts are there self signed certs
- * hostname the hostname port port being used basePath base context userName user
- * password password
+ * <p>name - the name
+ * https - is it https or not
+ * selfSignedCerts - are there self-signed certs
+ * hostname - the hostname
+ * port - port being used
+ * basePath - base context
+ * userName - user credentials
+ * password - password credentials
*
* @param busTopicParams Input parameters object
* @throws KeyManagementException key exception
@@ -109,7 +122,7 @@ public class JerseyClient implements HttpClient {
this.client = detmClient();
if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
- HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
+ var authFeature = HttpAuthenticationFeature.basic(userName, password);
this.client.register(authFeature);
}
@@ -124,11 +137,17 @@ public class JerseyClient implements HttpClient {
private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
if (this.https) {
ClientBuilder clientBuilder;
- SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
+ var sslContext = SSLContext.getInstance("TLSv1.2");
if (this.selfSignedCerts) {
sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
+
+ // This falls under self-signed certs which is used for non-production testing environments where
+ // the hostname in the cert is unlikely to be crafted properly. We always return true for the
+ // hostname verifier. This causes a sonar vuln, but we ignore it as it could cause problems in some
+ // testing environments.
clientBuilder =
- ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier((host, session) -> true);
+ ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(
+ (host, session) -> true); //NOSONAR
} else {
sslContext.init(null, null, null);
clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
@@ -149,23 +168,48 @@ public class JerseyClient implements HttpClient {
private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
String providers = (StringUtils.isBlank(serializationProvider)
? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
- for (String prov : providers.split(",")) {
+ for (String prov : COMMA_PAT.split(providers)) {
this.client.register(Class.forName(prov));
}
}
@Override
+ public WebTarget getWebTarget() {
+ return this.client.target(this.baseUrl);
+ }
+
+ @Override
public Response get(String path) {
if (!StringUtils.isBlank(path)) {
- return this.client.target(this.baseUrl).path(path).request().get();
+ return getWebTarget().path(path).request().get();
} else {
- return this.client.target(this.baseUrl).request().get();
+ return getWebTarget().request().get();
}
}
@Override
public Response get() {
- return this.client.target(this.baseUrl).request().get();
+ return getWebTarget().request().get();
+ }
+
+ @Override
+ public Future<Response> get(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
+ Map<String, Object> headers2 = (headers != null ? headers : Collections.emptyMap());
+
+ if (!StringUtils.isBlank(path)) {
+ return getBuilder(path, headers2).async().get(callback);
+ } else {
+ return get(callback, headers2);
+ }
+ }
+
+ @Override
+ public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
+ var builder = getWebTarget().request();
+ if (headers != null) {
+ headers.forEach(builder::header);
+ }
+ return builder.async().get(callback);
}
@Override
@@ -174,16 +218,33 @@ public class JerseyClient implements HttpClient {
}
@Override
+ public Future<Response> put(InvocationCallback<Response> callback, String path, Entity<?> entity,
+ Map<String, Object> headers) {
+ return getBuilder(path, headers).async().put(entity, callback);
+ }
+
+ @Override
public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
return getBuilder(path, headers).post(entity);
}
@Override
+ public Future<Response> post(InvocationCallback<Response> callback, String path, Entity<?> entity,
+ Map<String, Object> headers) {
+ return getBuilder(path, headers).async().post(entity, callback);
+ }
+
+ @Override
public Response delete(String path, Map<String, Object> headers) {
return getBuilder(path, headers).delete();
}
@Override
+ public Future<Response> delete(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
+ return getBuilder(path, headers).async().delete(callback);
+ }
+
+ @Override
public boolean start() {
return alive;
}
@@ -211,84 +272,8 @@ public class JerseyClient implements HttpClient {
return this.alive;
}
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public boolean isHttps() {
- return https;
- }
-
- @Override
- public boolean isSelfSignedCerts() {
- return selfSignedCerts;
- }
-
- @Override
- public String getHostname() {
- return hostname;
- }
-
- @Override
- public int getPort() {
- return port;
- }
-
- @Override
- public String getBasePath() {
- return basePath;
- }
-
- @Override
- public String getUserName() {
- return userName;
- }
-
- @JsonIgnore
- @GsonJsonIgnore
- @Override
- public String getPassword() {
- return password;
- }
-
- @Override
- public String getBaseUrl() {
- return baseUrl;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("JerseyClient [name=");
- builder.append(name);
- builder.append(", https=");
- builder.append(https);
- builder.append(", selfSignedCerts=");
- builder.append(selfSignedCerts);
- builder.append(", hostname=");
- builder.append(hostname);
- builder.append(", port=");
- builder.append(port);
- builder.append(", basePath=");
- builder.append(basePath);
- builder.append(", userName=");
- builder.append(userName);
- builder.append(", password=");
- builder.append(password);
- builder.append(", client=");
- builder.append(client);
- builder.append(", baseUrl=");
- builder.append(baseUrl);
- builder.append(", alive=");
- builder.append(alive);
- builder.append("]");
- return builder.toString();
- }
-
private Builder getBuilder(String path, Map<String, Object> headers) {
- Builder builder = this.client.target(this.baseUrl).path(path).request();
+ var builder = getWebTarget().path(path).request();
for (Entry<String, Object> header : headers.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/AuthorizationFilter.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/AuthorizationFilter.java
index d884b869..44204cfd 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/AuthorizationFilter.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/AuthorizationFilter.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2018 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.
@@ -20,36 +21,33 @@
package org.onap.policy.common.endpoints.http.server;
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AuthorizationFilter implements Filter {
- private static Logger logger = LoggerFactory.getLogger(AuthorizationFilter.class);
+ private static final Logger logger = LoggerFactory.getLogger(AuthorizationFilter.class);
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
- if (!(servletRequest instanceof HttpServletRequest)) {
+ if (!(servletRequest instanceof HttpServletRequest request)) {
throw new ServletException("Not an HttpServletRequest instance");
}
- if (!(servletResponse instanceof HttpServletResponse)) {
+ if (!(servletResponse instanceof HttpServletResponse response)) {
throw new ServletException("Not an HttpServletResponse instance");
}
- HttpServletRequest request = (HttpServletRequest) servletRequest;
- HttpServletResponse response = (HttpServletResponse) servletResponse;
-
String role = getRole(request);
boolean authorized = request.isUserInRole(role);
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServer.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServer.java
index 0adf782c..a20c125d 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServer.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServer.java
@@ -3,6 +3,8 @@
* ONAP
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation.
+ * Modifications Copyright (C) 2021 Bell Canada. 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.
@@ -50,18 +52,6 @@ public interface HttpServletServer extends Startable {
void setBasicAuthentication(String user, String password, String relativeUriPath);
/**
- * Enables AAF based authentication.
- *
- * @param filterPath filter path
- */
- void setAafAuthentication(String filterPath);
-
- /**
- * Checks if AAF authentication has been enabled.
- */
- boolean isAaf();
-
- /**
* Sets the serialization provider to be used when classes are added to the service.
*
* @param provider the provider to use for message serialization and de-serialization
@@ -83,22 +73,44 @@ public interface HttpServletServer extends Startable {
* @param restClass JAX-RS API Class
*
* @throws IllegalArgumentException unable to process because of invalid input
- * @throws IllegalStateException unable to process because of invalid state
+ * @throws IllegalStateException unable to process because of invalid state, for example
+ * different types of servlets map to the same servletPath
*/
void addServletClass(String servletPath, String restClass);
/**
+ * Adds a Java Servlet.
+ *
+ * @param servletPath servlet path
+ * @param plainServletClass servlet class
+ */
+ void addStdServletClass(String servletPath, String plainServletClass);
+
+ /**
* Adds a package containing JAX-RS classes to serve REST requests.
*
* @param servletPath servlet path
* @param restPackage JAX-RS package to scan
*
* @throws IllegalArgumentException unable to process because of invalid input
- * @throws IllegalStateException unable to process because of invalid state
+ * @throws IllegalStateException unable to process because of invalid state, for example
+ * different types of servlets map to the same servletPath
*/
void addServletPackage(String servletPath, String restPackage);
/**
+ * Add a static resource path to manage static resources.
+ *
+ * @param servletPath servlet path
+ * @param resourceBase static resources folder
+ *
+ * @throws IllegalArgumentException unable to process because of invalid input
+ * @throws IllegalStateException unable to process because of invalid state, for example
+ * different types of servlets map to the same servletPath
+ */
+ void addServletResource(String servletPath, String resourceBase);
+
+ /**
* Blocking start of the http server.
*
* @param maxWaitTime max time to wait for the start to take place
@@ -108,4 +120,14 @@ public interface HttpServletServer extends Startable {
* @throws InterruptedException if the blocking operation is interrupted
*/
boolean waitedStart(long maxWaitTime) throws InterruptedException;
+
+ /**
+ * Are prometheus metrics enabled?.
+ */
+ public boolean isPrometheus();
+
+ /**
+ * Enable prometheus metrics.
+ */
+ public void setPrometheus(String metricsPath);
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactory.java
index 0c30e3e5..7ce0becd 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactory.java
@@ -3,13 +3,14 @@
* policy-endpoints
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020,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.
@@ -29,23 +30,24 @@ import java.util.Properties;
public interface HttpServletServerFactory {
/**
- * Builds an http or https server with support for servlets.
- *
+ * Builds a http or https rest server with support for servlets.
+ *
* @param name name
* @param https use secured http over tls connection
* @param host binding host
* @param port port
+ * @param sniHostCheck SNI Host checking flag
* @param contextPath server base path
* @param swagger enable swagger documentation
* @param managed is it managed by infrastructure
* @return http server
* @throws IllegalArgumentException when invalid parameters are provided
*/
- HttpServletServer build(String name, boolean https, String host, int port, String contextPath, boolean swagger,
- boolean managed);
+ HttpServletServer build(String name, boolean https, String host, int port, boolean sniHostCheck, String contextPath,
+ boolean swagger, boolean managed);
/**
- * Builds an http server with support for servlets.
+ * Builds a http rest server with support for servlets.
*
* @param name name
* @param host binding host
@@ -59,8 +61,8 @@ public interface HttpServletServerFactory {
HttpServletServer build(String name, String host, int port, String contextPath, boolean swagger, boolean managed);
/**
- * Build a list of http servers per properties.
- *
+ * Build a list of http rest servers per properties.
+ *
* @param properties properties based configuration
* @return list of http servers
* @throws IllegalArgumentException when invalid parameters are provided
@@ -68,8 +70,24 @@ public interface HttpServletServerFactory {
List<HttpServletServer> build(Properties properties);
/**
+ * Builds a http or https server to manage static resources.
+ *
+ * @param name name
+ * @param https use secured http over tls connection
+ * @param host binding host
+ * @param port port
+ * @param sniHostCheck SNI Host checking flag
+ * @param contextPath server base path
+ * @param managed is it managed by infrastructure
+ * @return http server
+ * @throws IllegalArgumentException when invalid parameters are provided
+ */
+ HttpServletServer buildStaticResourceServer(String name, boolean https, String host, int port, boolean sniHostCheck,
+ String contextPath, boolean managed);
+
+ /**
* Gets a server based on the port.
- *
+ *
* @param port port
* @return http server
*/
@@ -77,14 +95,14 @@ public interface HttpServletServerFactory {
/**
* Provides an inventory of servers.
- *
+ *
* @return inventory of servers
*/
List<HttpServletServer> inventory();
/**
* Destroys server bound to a port.
- *
+ *
* @param port the port the server is bound to
*/
void destroy(int port);
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactoryInstance.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactoryInstance.java
index a56be701..58e27cbf 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactoryInstance.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/HttpServletServerFactoryInstance.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,8 +20,11 @@
package org.onap.policy.common.endpoints.http.server;
+import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class HttpServletServerFactoryInstance {
/**
@@ -29,10 +32,4 @@ public class HttpServletServerFactoryInstance {
*/
@Getter
private static final HttpServletServerFactory serverFactory = new IndexedHttpServletServerFactory();
-
-
- private HttpServletServerFactoryInstance() {
- // do nothing
- }
-
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/IndexedHttpServletServerFactory.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/IndexedHttpServletServerFactory.java
index 517ad208..7c9aca4c 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/IndexedHttpServletServerFactory.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/IndexedHttpServletServerFactory.java
@@ -2,7 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020,2023-2024 Nordix Foundation.
+ * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,12 +22,14 @@
package org.onap.policy.common.endpoints.http.server;
+import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.http.server.internal.JettyJerseyServer;
+import org.onap.policy.common.endpoints.http.server.internal.JettyStaticResourceServer;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.onap.policy.common.endpoints.utils.PropertyUtils;
import org.slf4j.Logger;
@@ -35,8 +39,7 @@ import org.slf4j.LoggerFactory;
* Indexed factory implementation.
*/
class IndexedHttpServletServerFactory implements HttpServletServerFactory {
-
- private static final String SPACES_COMMA_SPACES = "\\s*,\\s*";
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
/**
* logger.
@@ -49,14 +52,14 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
protected HashMap<Integer, HttpServletServer> servers = new HashMap<>();
@Override
- public synchronized HttpServletServer build(String name, boolean https, String host, int port, String contextPath,
- boolean swagger, boolean managed) {
+ public synchronized HttpServletServer build(String name, boolean https, String host, int port, boolean sniHostCheck,
+ String contextPath, boolean swagger, boolean managed) {
if (servers.containsKey(port)) {
return servers.get(port);
}
- JettyJerseyServer server = new JettyJerseyServer(name, https, host, port, contextPath, swagger);
+ var server = new JettyJerseyServer(name, https, host, port, sniHostCheck, contextPath, swagger);
if (managed) {
servers.put(port, server);
}
@@ -67,7 +70,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
@Override
public synchronized HttpServletServer build(String name, String host, int port, String contextPath, boolean swagger,
boolean managed) {
- return build(name, false, host, port, contextPath, swagger, managed);
+ return build(name, false, host, port, false, contextPath, swagger, managed);
}
@Override
@@ -81,103 +84,132 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
return serviceList;
}
- for (String serviceName : serviceNames.split(SPACES_COMMA_SPACES)) {
+ for (String serviceName : COMMA_SPACE_PAT.split(serviceNames)) {
addService(serviceList, serviceName, properties);
}
return serviceList;
}
+ @Override
+ public HttpServletServer buildStaticResourceServer(String name, boolean https, String host, int port,
+ boolean sniHostCheck, String contextPath, boolean managed) {
+ if (servers.containsKey(port)) {
+ return servers.get(port);
+ }
+
+ var server = new JettyStaticResourceServer(name, https, host, port, sniHostCheck, contextPath);
+ if (managed) {
+ servers.put(port, server);
+ }
+
+ return server;
+ }
+
private void addService(ArrayList<HttpServletServer> serviceList, String serviceName, Properties properties) {
String servicePrefix = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + serviceName;
- PropertyUtils props = new PropertyUtils(properties, servicePrefix,
+ var props = new PropertyUtils(properties, servicePrefix,
(name, value, ex) -> logger
- .warn("{}: {} {} is in invalid format for http service {} ", this, name, value, serviceName));
+ .warn("{}: {} {} is in invalid format for http service {} ", this, name, value, serviceName));
- int servicePort = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
+ var servicePort = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
if (servicePort < 0) {
logger.warn("No HTTP port for service in {}", serviceName);
return;
}
- final String hostName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, null);
- final String contextUriPath =
- props.getString(PolicyEndPointProperties.PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX, null);
- boolean managed = props.getBoolean(PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, true);
- boolean swagger = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, false);
- boolean https = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false);
+ final var hostName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, null);
+ final var contextUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX, null);
+ var managed = props.getBoolean(PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, true);
+ var swagger = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, false);
+ var https = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false);
+ var sniHostCheck = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_SNI_HOST_CHECK_SUFFIX, false);
// create the service
- HttpServletServer service = build(serviceName, https, hostName, servicePort, contextUriPath, swagger, managed);
+ HttpServletServer service =
+ build(serviceName, https, hostName, servicePort, sniHostCheck, contextUriPath, swagger, managed);
// configure the service
setSerializationProvider(props, service);
- setAuthentication(props, service, contextUriPath);
+ setAuthentication(props, service);
- final String restUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_URIPATH_SUFFIX, null);
+ final var restUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_URIPATH_SUFFIX, null);
addFilterClasses(props, service, restUriPath);
- addServletClasses(props, service, restUriPath);
+ addRestServletClasses(props, service, restUriPath);
addServletPackages(props, service, restUriPath);
+ addServletClass(props, service);
+ setPrometheus(props, service);
+
serviceList.add(service);
}
private void setSerializationProvider(PropertyUtils props, HttpServletServer service) {
- final String classProv = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, null);
+ final var classProv = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, null);
if (!StringUtils.isBlank(classProv)) {
service.setSerializationProvider(classProv);
}
}
- private void setAuthentication(PropertyUtils props, HttpServletServer service, final String contextUriPath) {
- /* authentication method either AAF or HTTP Basic Auth */
-
- boolean aaf = props.getBoolean(PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, false);
- final String userName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, null);
- final String password = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, null);
- final String authUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_URIPATH_SUFFIX, null);
+ private void setAuthentication(PropertyUtils props, HttpServletServer service) {
+ /* authentication method HTTP Basic Auth */
+ final var userName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, null);
+ final var password = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, null);
+ final var authUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_URIPATH_SUFFIX, null);
- if (aaf) {
- service.setAafAuthentication(contextUriPath);
- } else if (!StringUtils.isBlank(userName) && !StringUtils.isBlank(password)) {
+ if (!StringUtils.isBlank(userName) && !StringUtils.isBlank(password)) {
service.setBasicAuthentication(userName, password, authUriPath);
}
}
+ private void setPrometheus(PropertyUtils props, HttpServletServer service) {
+ if (props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX, false)) {
+ service.setPrometheus("/metrics");
+ }
+ }
+
private void addFilterClasses(PropertyUtils props, HttpServletServer service, final String restUriPath) {
- final String filterClasses =
- props.getString(PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX, null);
+ final var filterClasses =
+ props.getString(PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX, null);
if (!StringUtils.isBlank(filterClasses)) {
- for (String filterClass : filterClasses.split(SPACES_COMMA_SPACES)) {
+ for (String filterClass : COMMA_SPACE_PAT.split(filterClasses)) {
service.addFilterClass(restUriPath, filterClass);
}
}
}
- private void addServletClasses(PropertyUtils props, HttpServletServer service, final String restUriPath) {
-
- final String restClasses = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, null);
+ private void addRestServletClasses(PropertyUtils props, HttpServletServer service, final String restUriPath) {
+ final var restClasses = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, null);
if (!StringUtils.isBlank(restClasses)) {
- for (String restClass : restClasses.split(SPACES_COMMA_SPACES)) {
+ for (String restClass : COMMA_SPACE_PAT.split(restClasses)) {
service.addServletClass(restUriPath, restClass);
}
}
}
+ private void addServletClass(PropertyUtils props, HttpServletServer service) {
+ var servletClass = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_CLASS_SUFFIX, null);
+ var servletUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX, null);
+
+ if (!StringUtils.isBlank(servletClass) && !StringUtils.isBlank(servletUriPath)) {
+ service.addStdServletClass(servletUriPath, servletClass);
+ }
+ }
+
private void addServletPackages(PropertyUtils props, HttpServletServer service, final String restUriPath) {
- final String restPackages = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX, null);
+ final var restPackages = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX, null);
if (!StringUtils.isBlank(restPackages)) {
- for (String restPackage : restPackages.split(SPACES_COMMA_SPACES)) {
+ for (String restPackage : COMMA_SPACE_PAT.split(restPackages)) {
service.addServletPackage(restUriPath, restPackage);
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/JsonExceptionMapper.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/JsonExceptionMapper.java
index 55b3a0d5..0030c121 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/JsonExceptionMapper.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/JsonExceptionMapper.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 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.
@@ -21,11 +22,12 @@
package org.onap.policy.common.endpoints.http.server;
import com.google.gson.JsonSyntaxException;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ExceptionMapper;
-import javax.ws.rs.ext.Provider;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.ExceptionMapper;
+import jakarta.ws.rs.ext.Provider;
+import lombok.AllArgsConstructor;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,7 +39,7 @@ import org.slf4j.LoggerFactory;
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonExceptionMapper implements ExceptionMapper<JsonSyntaxException> {
- private static Logger logger = LoggerFactory.getLogger(JsonExceptionMapper.class);
+ private static final Logger logger = LoggerFactory.getLogger(JsonExceptionMapper.class);
@Override
public Response toResponse(JsonSyntaxException exception) {
@@ -46,11 +48,8 @@ public class JsonExceptionMapper implements ExceptionMapper<JsonSyntaxException>
}
@Getter
+ @AllArgsConstructor
private static class SimpleResponse {
private String errorDetails;
-
- public SimpleResponse(String errorDetails) {
- this.errorDetails = errorDetails;
- }
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/RestServer.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/RestServer.java
index 43e39d33..7e6ce866 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/RestServer.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/RestServer.java
@@ -1,7 +1,8 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
+ * Copyright (C) 2019, 2023-2024 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property.
+ * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,9 +22,13 @@
package org.onap.policy.common.endpoints.http.server;
+import jakarta.servlet.Filter;
+import java.util.Arrays;
import java.util.List;
+import java.util.Optional;
import java.util.Properties;
-import org.onap.policy.common.endpoints.http.server.aaf.AafAuthFilter;
+import java.util.stream.Collectors;
+import lombok.ToString;
import org.onap.policy.common.endpoints.parameters.RestServerParameters;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.onap.policy.common.gson.GsonMessageBodyHandler;
@@ -34,6 +39,7 @@ import org.onap.policy.common.utils.services.ServiceManagerContainer;
*
* @author Ram Krishna Verma (ram.krishna.verma@est.tech)
*/
+@ToString
public class RestServer extends ServiceManagerContainer {
/**
@@ -47,24 +53,34 @@ public class RestServer extends ServiceManagerContainer {
* Constructs the object.
*
* @param restServerParameters the rest server parameters
- * @param aafFilter class of object to use to filter AAF requests, or {@code null}
* @param jaxrsProviders classes providing the services
*/
- public RestServer(final RestServerParameters restServerParameters, Class<? extends AafAuthFilter> aafFilter,
- Class<?>... jaxrsProviders) {
+ public RestServer(final RestServerParameters restServerParameters,
+ Class<?>... jaxrsProviders) {
+ this(restServerParameters, null, Arrays.asList(jaxrsProviders));
+ }
+
+ /**
+ * Constructs the object.
+ *
+ * @param restServerParameters the rest server parameters
+ * @param filters class of object to use to filter requests, or {@code null}
+ * @param jaxrsProviders classes providing the services
+ */
+ public RestServer(final RestServerParameters restServerParameters, List<Class<? extends Filter>> filters,
+ List<Class<?>> jaxrsProviders) {
- if (jaxrsProviders.length == 0) {
+ if (jaxrsProviders == null || jaxrsProviders.isEmpty()) {
throw new IllegalArgumentException("no providers specified");
}
this.servers = factory.getServerFactory()
- .build(getServerProperties(restServerParameters, getProviderClassNames(jaxrsProviders)));
+ .build(getServerProperties(restServerParameters, getProviderClassNames(jaxrsProviders)));
for (HttpServletServer server : this.servers) {
- if (aafFilter != null && server.isAaf()) {
- server.addFilterClass(null, aafFilter.getName());
+ if (filters != null && !filters.isEmpty()) {
+ filters.forEach(filter -> server.addFilterClass(null, filter.getName()));
}
-
addAction("REST " + server.getName(), server::start, server::stop);
}
}
@@ -78,29 +94,36 @@ public class RestServer extends ServiceManagerContainer {
* @return the properties object
*/
protected Properties getServerProperties(RestServerParameters restServerParameters, String names) {
- final Properties props = new Properties();
+ final var props = new Properties();
props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, restServerParameters.getName());
final String svcpfx =
- PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + restServerParameters.getName();
+ PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + restServerParameters.getName();
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, restServerParameters.getHost());
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
- Integer.toString(restServerParameters.getPort()));
+ Integer.toString(restServerParameters.getPort()));
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, names);
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "false");
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "true");
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX,
- restServerParameters.getUserName());
+ getValue(restServerParameters.getUserName()));
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX,
- restServerParameters.getPassword());
+ getValue(restServerParameters.getPassword()));
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX,
- String.valueOf(restServerParameters.isHttps()));
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX,
- String.valueOf(restServerParameters.isAaf()));
+ String.valueOf(restServerParameters.isHttps()));
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SNI_HOST_CHECK_SUFFIX,
+ String.valueOf(restServerParameters.isSniHostCHeck()));
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
- String.join(",", GsonMessageBodyHandler.class.getName(), YamlMessageBodyHandler.class.getName(),
- JsonExceptionMapper.class.getName(), YamlExceptionMapper.class.getName()));
+ String.join(",", GsonMessageBodyHandler.class.getName(), YamlMessageBodyHandler.class.getName(),
+ JsonExceptionMapper.class.getName(), YamlExceptionMapper.class.getName()));
+
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX,
+ Optional.ofNullable(restServerParameters.getServletUriPath()).orElse(""));
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_CLASS_SUFFIX,
+ Optional.ofNullable(restServerParameters.getServletClass()).orElse(""));
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX,
+ String.valueOf(restServerParameters.isPrometheus()));
return props;
}
@@ -110,23 +133,15 @@ public class RestServer extends ServiceManagerContainer {
* @param jaxrsProviders classes providing the services
* @return the provider class names
*/
- private String getProviderClassNames(Class<?>[] jaxrsProviders) {
- StringBuilder names = new StringBuilder();
-
- for (Class<?> prov : jaxrsProviders) {
- if (names.length() > 0) {
- names.append(',');
- }
-
- names.append(prov.getName());
- }
-
- return names.toString();
+ private String getProviderClassNames(List<Class<?>> jaxrsProviders) {
+ return jaxrsProviders.stream().map(Class::getName).collect(Collectors.joining(","));
}
- @Override
- public String toString() {
- return "RestServer [servers=" + servers + "]";
+ private String getValue(final String value) {
+ if (value != null && value.startsWith("${") && value.endsWith("}")) {
+ return System.getenv(value.substring(2, value.length() - 1));
+ }
+ return value;
}
/**
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlExceptionMapper.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlExceptionMapper.java
index 7eac932a..c30c2072 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlExceptionMapper.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlExceptionMapper.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 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.
@@ -20,10 +21,11 @@
package org.onap.policy.common.endpoints.http.server;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ExceptionMapper;
-import javax.ws.rs.ext.Provider;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.ExceptionMapper;
+import jakarta.ws.rs.ext.Provider;
+import lombok.AllArgsConstructor;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -36,7 +38,7 @@ import org.yaml.snakeyaml.error.YAMLException;
@Provider
@Produces(YamlMessageBodyHandler.APPLICATION_YAML)
public class YamlExceptionMapper implements ExceptionMapper<YAMLException> {
- private static Logger logger = LoggerFactory.getLogger(YamlExceptionMapper.class);
+ private static final Logger logger = LoggerFactory.getLogger(YamlExceptionMapper.class);
@Override
public Response toResponse(YAMLException exception) {
@@ -45,11 +47,8 @@ public class YamlExceptionMapper implements ExceptionMapper<YAMLException> {
}
@Getter
+ @AllArgsConstructor
private static class SimpleResponse {
private String errorDetails;
-
- public SimpleResponse(String errorDetails) {
- this.errorDetails = errorDetails;
- }
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlJacksonHandler.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlJacksonHandler.java
index f71aa90f..4639e6a2 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlJacksonHandler.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlJacksonHandler.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 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.
@@ -21,10 +22,10 @@
package org.onap.policy.common.endpoints.http.server;
import com.google.gson.GsonBuilder;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.ext.Provider;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.ext.Provider;
import org.onap.policy.common.gson.JacksonHandler;
import org.onap.policy.common.utils.coder.YamlJsonTranslator;
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlMessageBodyHandler.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlMessageBodyHandler.java
index 8506a283..6de6b754 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlMessageBodyHandler.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlMessageBodyHandler.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 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.
@@ -22,6 +23,13 @@ package org.onap.policy.common.endpoints.http.server;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.ext.MessageBodyReader;
+import jakarta.ws.rs.ext.MessageBodyWriter;
+import jakarta.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -30,13 +38,6 @@ import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
import org.onap.policy.common.gson.GsonMessageBodyHandler;
import org.onap.policy.common.utils.coder.YamlJsonTranslator;
import org.slf4j.Logger;
@@ -96,7 +97,7 @@ public class YamlMessageBodyHandler implements MessageBodyReader<Object>, Messag
public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
- try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
+ try (var writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
translator.toYaml(writer, object);
}
}
@@ -121,7 +122,7 @@ public class YamlMessageBodyHandler implements MessageBodyReader<Object>, Messag
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
- try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
+ try (var streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
Class<?> clazz = (Class<?>) genericType;
return translator.fromYaml(streamReader, clazz);
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/aaf/AafAuthFilter.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/aaf/AafAuthFilter.java
deleted file mode 100644
index df1f6044..00000000
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/aaf/AafAuthFilter.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * 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.endpoints.http.server.aaf;
-
-import javax.servlet.http.HttpServletRequest;
-import org.onap.policy.common.endpoints.http.server.AuthorizationFilter;
-
-/**
- * Generic Authorization AAF Filter Skeleton. This class will return
- * a permission in AAF format. Subclasses are responsible to provide
- * the AAF permission type and instance.
- */
-public abstract class AafAuthFilter extends AuthorizationFilter {
-
- public static final String DEFAULT_NAMESPACE = "org.onap.policy";
-
- @Override
- protected String getRole(HttpServletRequest request) {
- return
- String.format("%s|%s|%s", getPermissionType(request), getPermissionInstance(request),
- request.getMethod().toLowerCase());
- }
-
- protected abstract String getPermissionType(HttpServletRequest request);
-
- protected abstract String getPermissionInstance(HttpServletRequest request);
-}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/aaf/AafGranularAuthFilter.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/aaf/AafGranularAuthFilter.java
deleted file mode 100644
index 27b15a9c..00000000
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/aaf/AafGranularAuthFilter.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * 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.endpoints.http.server.aaf;
-
-import javax.servlet.http.HttpServletRequest;
-import org.onap.policy.common.utils.network.NetworkUtil;
-
-/**
- * This generic class allows the mapping of REST APIs to AAF permissions
- * to be evaluated in an AAF context. This class can be used for
- * highly granular permissions where each REST resource can be directly
- * mapped transparently to an AAF permission type, the instance being the host
- * server, and the HTTP method corresponding to the action.
- * Subclasses are responsible to provide the root permission prefix, typically
- * the namespace.
- */
-public abstract class AafGranularAuthFilter extends AafAuthFilter {
-
- @Override
- protected String getPermissionType(HttpServletRequest request) {
- return getPermissionTypeRoot() + request.getRequestURI().replace('/', '.');
- }
-
- @Override
- protected String getPermissionInstance(HttpServletRequest request) {
- return NetworkUtil.getHostname();
- }
-
- public abstract String getPermissionTypeRoot();
-}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java
index d809479a..d4c392b9 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java
@@ -2,8 +2,9 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,11 +22,13 @@
package org.onap.policy.common.endpoints.http.server.internal;
-import io.swagger.jersey.config.JerseyJaxrsConfig;
-import java.util.HashMap;
import org.apache.commons.lang3.StringUtils;
+import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ServerProperties;
+import org.glassfish.jersey.servlet.ServletContainer;
+import org.onap.policy.common.endpoints.http.server.JsonExceptionMapper;
+import org.onap.policy.common.gson.GsonMessageBodyHandler;
import org.onap.policy.common.utils.network.NetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -35,7 +38,7 @@ import org.slf4j.LoggerFactory;
*
* <p>Note: the serialization provider will always be added to the server's class providers, as will the swagger
* providers (assuming swagger has been enabled). This happens whether {@link #addServletClass(String, String)} is used
- * or {@link #addServletPackage(String, String)} is used. Thus it's possible to have both the server's class provider
+ * or {@link #addServletPackage(String, String)} is used. Thus, it's possible to have both the server's class provider
* property and the server's package provider property populated.
*/
public class JettyJerseyServer extends JettyServletServer {
@@ -61,27 +64,17 @@ public class JettyJerseyServer extends JettyServletServer {
protected static final String SWAGGER_PRETTY_PRINT = "swagger.pretty.print";
/**
- * Jersey Jackson Classes Init Param Value.
+ * Jersey GSON Classes Init Param Value.
*/
- protected static final String JERSEY_JACKSON_INIT_CLASSNAMES_PARAM_VALUE =
- "org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider";
+ protected static final String JERSEY_GSON_INIT_CLASSNAMES_PARAM_VALUE =
+ String.join(",", GsonMessageBodyHandler.class.getName(), JsonExceptionMapper.class.getName());
/**
- * Jersey Swagger Classes Init Param Value.
- */
- protected static final String SWAGGER_INIT_CLASSNAMES_PARAM_VALUE =
- "io.swagger.jaxrs.listing.ApiListingResource," + "io.swagger.jaxrs.listing.SwaggerSerializers";
- /**
* Logger.
*/
protected static Logger logger = LoggerFactory.getLogger(JettyJerseyServer.class);
/**
- * Container for servlets.
- */
- protected HashMap<String, ServletHolder> servlets = new HashMap<>();
-
- /**
* Swagger ID.
*/
protected String swaggerId = null;
@@ -89,7 +82,7 @@ public class JettyJerseyServer extends JettyServletServer {
/**
* The serialization provider to be used when classes are added to the service.
*/
- private String classProvider = JERSEY_JACKSON_INIT_CLASSNAMES_PARAM_VALUE;
+ private String classProvider = JERSEY_GSON_INIT_CLASSNAMES_PARAM_VALUE;
/**
* Constructor.
@@ -98,14 +91,15 @@ public class JettyJerseyServer extends JettyServletServer {
* @param https enable https?
* @param host host server host
* @param port port server port
+ * @param sniHostCheck SNI Host checking flag
* @param swagger support swagger?
* @param contextPath context path
- *
* @throws IllegalArgumentException in invalid arguments are provided
*/
- public JettyJerseyServer(String name, boolean https, String host, int port, String contextPath, boolean swagger) {
+ public JettyJerseyServer(String name, boolean https, String host, int port, boolean sniHostCheck,
+ String contextPath, boolean swagger) {
- super(name, https, host, port, contextPath);
+ super(name, https, host, port, sniHostCheck, contextPath);
if (swagger) {
this.swaggerId = "swagger-" + this.port;
attachSwaggerServlet(https);
@@ -117,7 +111,10 @@ public class JettyJerseyServer extends JettyServletServer {
*/
protected void attachSwaggerServlet(boolean https) {
- ServletHolder swaggerServlet = context.addServlet(JerseyJaxrsConfig.class, "/");
+ ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
+ handler.setContextPath("/");
+
+ ServletHolder swaggerServlet = handler.addServlet(ServletContainer.class, "/*");
String hostname = this.connector.getHost();
if (StringUtils.isBlank(hostname) || hostname.equals(NetworkUtil.IPV4_WILDCARD_ADDRESS)) {
@@ -125,7 +122,7 @@ public class JettyJerseyServer extends JettyServletServer {
}
swaggerServlet.setInitParameter(SWAGGER_API_BASEPATH,
- ((https) ? "https://" : "http://") + hostname + ":" + this.connector.getPort() + "/");
+ ((https) ? "https://" : "http://") + hostname + ":" + this.connector.getPort() + "/");
swaggerServlet.setInitParameter(SWAGGER_CONTEXT_ID, swaggerId);
swaggerServlet.setInitParameter(SWAGGER_SCANNER_ID, swaggerId);
swaggerServlet.setInitParameter(SWAGGER_PRETTY_PRINT, "true");
@@ -145,21 +142,16 @@ public class JettyJerseyServer extends JettyServletServer {
* @throws IllegalArgumentException if invalid arguments are provided
*/
protected synchronized ServletHolder getServlet(String servletPath) {
-
- return servlets.computeIfAbsent(servletPath, key -> {
-
- ServletHolder jerseyServlet =
- context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, servletPath);
- jerseyServlet.setInitOrder(0);
-
- return jerseyServlet;
- });
+ ServletHolder jerseyServlet =
+ super.getServlet(org.glassfish.jersey.servlet.ServletContainer.class, servletPath);
+ jerseyServlet.setInitOrder(0);
+ return jerseyServlet;
}
@Override
public synchronized void addServletPackage(String servletPath, String restPackage) {
String servPath = servletPath;
- if (restPackage == null || restPackage.isEmpty()) {
+ if (StringUtils.isBlank(restPackage)) {
throw new IllegalArgumentException("No discoverable REST package provided");
}
@@ -189,7 +181,7 @@ public class JettyJerseyServer extends JettyServletServer {
@Override
public synchronized void addServletClass(String servletPath, String restClass) {
- if (restClass == null || restClass.isEmpty()) {
+ if (StringUtils.isBlank(restClass)) {
throw new IllegalArgumentException("No discoverable REST class provided");
}
@@ -232,8 +224,8 @@ public class JettyJerseyServer extends JettyServletServer {
initClasses = classProvider;
if (this.swaggerId != null) {
- initClasses += "," + SWAGGER_INIT_CLASSNAMES_PARAM_VALUE;
-
+ jerseyServlet.setInitParameter("jersey.config.server.provider.packages",
+ "io.swagger.v3.jaxrs2.integration.resources,io.swagger.sample.resource");
jerseyServlet.setInitParameter(SWAGGER_CONTEXT_ID, swaggerId);
jerseyServlet.setInitParameter(SWAGGER_SCANNER_ID, swaggerId);
}
@@ -254,9 +246,9 @@ public class JettyJerseyServer extends JettyServletServer {
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("JettyJerseyServer [servlets=").append(servlets).append(", swaggerId=").append(swaggerId)
- .append(", toString()=").append(super.toString()).append("]");
- return builder.toString();
+ return "JettyJerseyServer [Jerseyservlets=" + servlets
+ + ", swaggerId=" + swaggerId
+ + ", toString()=" + super.toString()
+ + "]";
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyServletServer.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyServletServer.java
index 133adade..78858a77 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyServletServer.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyServletServer.java
@@ -2,7 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020, 2023-2024 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,9 +22,15 @@
package org.onap.policy.common.endpoints.http.server.internal;
-import com.fasterxml.jackson.annotation.JsonIgnore;
+import io.prometheus.client.hotspot.DefaultExports;
+import io.prometheus.client.servlet.jakarta.exporter.MetricsServlet;
+import jakarta.servlet.Servlet;
import java.util.EnumSet;
-import javax.servlet.DispatcherType;
+import java.util.HashMap;
+import java.util.Map;
+import lombok.Getter;
+import lombok.NonNull;
+import lombok.ToString;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
@@ -35,58 +43,70 @@ import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.Slf4jRequestLogWriter;
-import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.security.Credential;
import org.eclipse.jetty.util.ssl.SslContextFactory;
-import org.onap.aaf.cadi.filter.CadiFilter;
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
-import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Http Server implementation using Embedded Jetty.
*/
+@ToString
public abstract class JettyServletServer implements HttpServletServer, Runnable {
/**
* Keystore/Truststore system property names.
*/
public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
- public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword"; //NOSONAR
+ public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword"; // NOSONAR
public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
- public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword"; //NOSONAR
+ public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword"; // NOSONAR
/**
* Logger.
*/
- private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
+ private static final Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
+
+ private static final String NOT_SUPPORTED = " is not supported on this type of jetty server";
/**
* Server name.
*/
+ @Getter
protected final String name;
/**
* Server host address.
*/
+ @Getter
protected final String host;
/**
* Server port to bind.
*/
+ @Getter
protected final int port;
/**
- * Server auth user name.
+ * Should SNI host checking be done.
+ */
+ @Getter
+ protected boolean sniHostCheck;
+
+ /**
+ * Server auth username.
*/
+ @Getter
protected String user;
/**
* Server auth password name.
*/
+ @Getter
protected String password;
/**
@@ -112,12 +132,18 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
/**
* Jetty thread.
*/
- protected volatile Thread jettyThread;
+ protected Thread jettyThread;
+
+ /**
+ * Container for default servlets.
+ */
+ protected final Map<String, ServletHolder> servlets = new HashMap<>();
/**
* Start condition.
*/
- protected Object startCondition = new Object();
+ @ToString.Exclude
+ protected final Object startCondition = new Object();
/**
* Constructor.
@@ -125,11 +151,13 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
* @param name server name
* @param host server host
* @param port server port
+ * @param sniHostCheck SNI Host checking flag
* @param contextPath context path
*
* @throws IllegalArgumentException if invalid parameters are passed in
*/
- public JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
+ protected JettyServletServer(String name, boolean https, String host, int port, boolean sniHostCheck,
+ String contextPath) {
String srvName = name;
if (srvName == null || srvName.isEmpty()) {
@@ -154,6 +182,7 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
this.host = srvHost;
this.port = port;
+ this.sniHostCheck = sniHostCheck;
this.contextPath = ctxtPath;
@@ -162,8 +191,7 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
this.jettyServer = new Server();
- CustomRequestLog requestLog =
- new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
+ var requestLog = new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
this.jettyServer.setRequestLog(requestLog);
if (https) {
@@ -181,8 +209,8 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
this.jettyServer.setHandler(context);
}
- public JettyServletServer(String name, String host, int port, String contextPath) {
- this(name, false, host, port, contextPath);
+ protected JettyServletServer(String name, String host, int port, boolean sniHostCheck, String contextPath) {
+ this(name, false, host, port, sniHostCheck, contextPath);
}
@Override
@@ -196,7 +224,20 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
tempFilterPath = "/*";
}
- context.addFilter(filterClass, tempFilterPath, EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
+ context.addFilter(filterClass, tempFilterPath,
+ EnumSet.of(jakarta.servlet.DispatcherType.INCLUDE, jakarta.servlet.DispatcherType.REQUEST));
+ }
+
+ protected ServletHolder getServlet(@NonNull Class<? extends Servlet> servlet, @NonNull String servletPath) {
+ synchronized (servlets) {
+ return servlets.computeIfAbsent(servletPath, key -> context.addServlet(servlet, servletPath));
+ }
+ }
+
+ protected ServletHolder getServlet(String servletClass, String servletPath) {
+ synchronized (servlets) {
+ return servlets.computeIfAbsent(servletPath, key -> context.addServlet(servletClass, servletPath));
+ }
}
/**
@@ -205,32 +246,35 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
* @return the server connector
*/
public ServerConnector httpsConnector() {
- SslContextFactory sslContextFactory = new SslContextFactory.Server();
+ SslContextFactory.Server sslContextFactoryServer = new SslContextFactory.Server();
String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
if (keyStore != null) {
- sslContextFactory.setKeyStorePath(keyStore);
+ sslContextFactoryServer.setKeyStorePath(keyStore);
String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
if (ksPassword != null) {
- sslContextFactory.setKeyStorePassword(ksPassword);
+ sslContextFactoryServer.setKeyStorePassword(ksPassword);
}
}
String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
if (trustStore != null) {
- sslContextFactory.setTrustStorePath(trustStore);
+ sslContextFactoryServer.setTrustStorePath(trustStore);
String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
if (tsPassword != null) {
- sslContextFactory.setTrustStorePassword(tsPassword);
+ sslContextFactoryServer.setTrustStorePassword(tsPassword);
}
}
- HttpConfiguration https = new HttpConfiguration();
- https.addCustomizer(new SecureRequestCustomizer());
- return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
+ var httpsConfiguration = new HttpConfiguration();
+ SecureRequestCustomizer src = new SecureRequestCustomizer();
+ src.setSniHostCheck(sniHostCheck);
+ httpsConfiguration.addCustomizer(src);
+
+ return new ServerConnector(jettyServer, sslContextFactoryServer, new HttpConnectionFactory(httpsConfiguration));
}
public ServerConnector httpConnector() {
@@ -238,21 +282,6 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
}
@Override
- public void setAafAuthentication(String filterPath) {
- this.addFilterClass(filterPath, CadiFilter.class.getName());
- }
-
- @Override
- public boolean isAaf() {
- for (FilterHolder filter : context.getServletHandler().getFilters()) {
- if (CadiFilter.class.getName().equals(filter.getClassName())) {
- return true;
- }
- }
- return false;
- }
-
- @Override
public void setBasicAuthentication(String user, String password, String servletPath) {
String srvltPath = servletPath;
@@ -264,22 +293,26 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
srvltPath = "/*";
}
- final HashLoginService hashLoginService = new HashLoginService();
- final UserStore userStore = new UserStore();
- userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
+ final var hashLoginService = new HashLoginService();
+ final var userStore = new UserStore();
+ userStore.addUser(user, Credential.getCredential(password), new String[] {
+ "user"
+ });
hashLoginService.setUserStore(userStore);
hashLoginService.setName(this.connector.getName() + "-login-service");
- Constraint constraint = new Constraint();
+ var constraint = new Constraint();
constraint.setName(Constraint.__BASIC_AUTH);
- constraint.setRoles(new String[] {"user"});
+ constraint.setRoles(new String[] {
+ "user"
+ });
constraint.setAuthenticate(true);
- ConstraintMapping constraintMapping = new ConstraintMapping();
+ var constraintMapping = new ConstraintMapping();
constraintMapping.setConstraint(constraint);
constraintMapping.setPathSpec(srvltPath);
- ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
+ var securityHandler = new ConstraintSecurityHandler();
securityHandler.setAuthenticator(new BasicAuthenticator());
securityHandler.setRealmName(this.connector.getName() + "-realm");
securityHandler.addConstraintMapping(constraintMapping);
@@ -310,6 +343,11 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
}
this.jettyServer.join();
+
+ } catch (InterruptedException e) {
+ logger.error("{}: error found while bringing up server", this, e);
+ Thread.currentThread().interrupt();
+
} catch (Exception e) {
logger.error("{}: error found while bringing up server", this, e);
}
@@ -415,12 +453,13 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
this.stop();
- if (this.jettyThread == null) {
- return;
+ Thread jettyThreadCopy;
+ synchronized (this) {
+ if ((jettyThreadCopy = this.jettyThread) == null) {
+ return;
+ }
}
- Thread jettyThreadCopy = this.jettyThread;
-
if (jettyThreadCopy.isAlive()) {
try {
jettyThreadCopy.join(2000L);
@@ -451,58 +490,44 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
}
@Override
- public int getPort() {
- return this.port;
+ public void setSerializationProvider(String provider) {
+ throw new UnsupportedOperationException("setSerializationProvider()" + NOT_SUPPORTED);
}
- /**
- * Get name.
- *
- * @return the name
- */
@Override
- public String getName() {
- return name;
+ public void addServletClass(String servletPath, String servletClass) {
+ throw new UnsupportedOperationException("addServletClass()" + NOT_SUPPORTED);
}
- /**
- * Get host.
- *
- * @return the host
- */
- public String getHost() {
- return host;
+ @Override
+ public void addStdServletClass(@NonNull String servletPath, @NonNull String plainServletClass) {
+ this.getServlet(plainServletClass, servletPath);
}
- /**
- * Get user.
- *
- * @return the user
- */
- public String getUser() {
- return user;
+ @Override
+ public void setPrometheus(String metricsPath) {
+ this.getServlet(MetricsServlet.class, metricsPath);
+ DefaultExports.initialize();
}
- /**
- * Get password.
- *
- * @return the password
- */
- @JsonIgnore
- @GsonJsonIgnore
- public String getPassword() {
- return password;
+ @Override
+ public boolean isPrometheus() {
+ for (ServletHolder servlet : context.getServletHandler().getServlets()) {
+ if (MetricsServlet.class.getName().equals(servlet.getClassName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void addServletPackage(String servletPath, String restPackage) {
+ throw new UnsupportedOperationException("addServletPackage()" + NOT_SUPPORTED);
}
@Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
- .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
- .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
- .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
- .append(jettyThread).append("]");
- return builder.toString();
+ public void addServletResource(String servletPath, String resourceBase) {
+ throw new UnsupportedOperationException("addServletResource()" + NOT_SUPPORTED);
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyStaticResourceServer.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyStaticResourceServer.java
new file mode 100644
index 00000000..ee2b0540
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyStaticResourceServer.java
@@ -0,0 +1,107 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020, 2023-2024 Nordix Foundation.
+ * Modifications Copyright (C) 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.endpoints.http.server.internal;
+
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+import org.eclipse.jetty.servlet.DefaultServlet;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Jetty Server that uses DefaultServlets to support web static resources' management.
+ */
+@ToString
+public class JettyStaticResourceServer extends JettyServletServer {
+
+ /**
+ * Servlet Holder Resource Base Path.
+ */
+ protected static final String SERVLET_HOLDER_RESOURCE_BASE = "resourceBase";
+
+ /**
+ * Servlet Holder Directory Allowed.
+ */
+ protected static final String SERVLET_HOLDER_DIR_ALLOWED = "dirAllowed";
+
+ /**
+ * Servlet Holder Path Information Only.
+ */
+ protected static final String SERVLET_HOLDER_PATH_INFO_ONLY = "pathInfoOnly";
+
+ /**
+ * Logger.
+ */
+ protected static Logger logger = LoggerFactory.getLogger(JettyStaticResourceServer.class);
+
+ /**
+ * Constructor.
+ *
+ * @param name name
+ * @param https enable https?
+ * @param host host server host
+ * @param port port server port
+ * @param sniHostCheck SNI Host checking flag
+ * @param contextPath context path
+ * @throws IllegalArgumentException in invalid arguments are provided
+ */
+ public JettyStaticResourceServer(String name, boolean https, String host, int port, boolean sniHostCheck,
+ String contextPath) {
+
+ super(name, https, host, port, sniHostCheck, contextPath);
+ }
+
+ /**
+ * Retrieves cached default servlet based on servlet path.
+ *
+ * @param servletPath servlet path
+ * @return the jetty servlet holder
+ *
+ * @throws IllegalArgumentException if invalid arguments are provided
+ */
+ protected synchronized ServletHolder getDefaultServlet(String servletPath) {
+ return super.getServlet(DefaultServlet.class, servletPath);
+ }
+
+ @Override
+ public synchronized void addServletResource(String servletPath, String resourceBase) {
+
+ if (StringUtils.isBlank(resourceBase)) {
+ throw new IllegalArgumentException("No resourceBase provided");
+ }
+
+ if (servletPath == null || servletPath.isEmpty()) {
+ servletPath = "/*";
+ }
+
+ ServletHolder defaultServlet = this.getDefaultServlet(servletPath);
+
+ defaultServlet.setInitParameter(SERVLET_HOLDER_RESOURCE_BASE, resourceBase);
+ defaultServlet.setInitParameter(SERVLET_HOLDER_DIR_ALLOWED, "false");
+ defaultServlet.setInitParameter(SERVLET_HOLDER_PATH_INFO_ONLY, "true");
+
+ if (logger.isDebugEnabled()) {
+ logger.debug("{}: added Default Servlet: {}", this, defaultServlet.dump());
+ }
+ }
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/JsonListener.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/JsonListener.java
index ff8cbc5b..2e171070 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/JsonListener.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/JsonListener.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +21,8 @@
package org.onap.policy.common.endpoints.listeners;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.TopicListener;
import org.onap.policy.common.utils.coder.Coder;
@@ -33,6 +36,7 @@ import org.slf4j.LoggerFactory;
* Listens for messages received on a topic, in JSON format, decodes them into a
* {@link StandardCoderObject}, and then offers the objects to the subclass.
*/
+@NoArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class JsonListener implements TopicListener {
private static final Logger logger = LoggerFactory.getLogger(JsonListener.class);
@@ -41,13 +45,6 @@ public abstract class JsonListener implements TopicListener {
*/
private static final Coder coder = new StandardCoder();
- /**
- * Constructs the object.
- */
- public JsonListener() {
- super();
- }
-
@Override
public void onTopicEvent(CommInfrastructure infra, String topic, String event) {
// decode from JSON into a standard object
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcher.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcher.java
index 195a7eec..41f9abdb 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcher.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcher.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -36,7 +36,7 @@ public class MessageTypeDispatcher extends JsonListener {
/**
* Name of the message field, which may be hierarchical.
*/
- private final String[] messageFieldNames;
+ private final Object[] messageFieldNames;
/**
* Name of the message field, joined with "." - for logging.
@@ -80,7 +80,7 @@ public class MessageTypeDispatcher extends JsonListener {
@Override
public void onTopicEvent(CommInfrastructure infra, String topic, StandardCoderObject sco) {
// extract the message type
- final String type = sco.getString(messageFieldNames);
+ final var type = sco.getString(messageFieldNames);
if (type == null) {
logger.warn("unable to extract {}: {}", fullMessageFieldName, sco);
return;
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcher.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcher.java
index fcf9c9a9..e575e33b 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcher.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcher.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -43,7 +43,7 @@ public class RequestIdDispatcher<T> extends ScoListener<T> {
/**
* Name of the request id field, which may be hierarchical.
*/
- private final String[] requestIdFieldNames;
+ private final Object[] requestIdFieldNames;
/**
* Listeners for autonomous messages.
@@ -111,7 +111,7 @@ public class RequestIdDispatcher<T> extends ScoListener<T> {
public void onTopicEvent(CommInfrastructure infra, String topic, StandardCoderObject sco, T message) {
// extract the request id
- String reqid = sco.getString(requestIdFieldNames);
+ var reqid = sco.getString(requestIdFieldNames);
// dispatch the message
if (Strings.isNullOrEmpty(reqid)) {
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/ScoListener.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/ScoListener.java
index a3d33965..dc6ff12a 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/ScoListener.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/ScoListener.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +21,8 @@
package org.onap.policy.common.endpoints.listeners;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.utils.coder.Coder;
import org.onap.policy.common.utils.coder.CoderException;
@@ -34,6 +37,7 @@ import org.slf4j.LoggerFactory;
*
* @param <T> type of message/POJO this handles
*/
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class ScoListener<T> {
private static final Logger logger = LoggerFactory.getLogger(ScoListener.class);
@@ -49,15 +53,6 @@ public abstract class ScoListener<T> {
private final Class<T> clazz;
/**
- * Constructs the object.
- *
- * @param clazz class of message this handles
- */
- public ScoListener(Class<T> clazz) {
- this.clazz = clazz;
- }
-
- /**
* Receives an event, translates it into the desired type of object, and passes it to
* the subclass.
*
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestClientParameters.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestClientParameters.java
new file mode 100644
index 00000000..5d02e753
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestClientParameters.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.endpoints.parameters;
+
+import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ParameterGroup;
+import org.onap.policy.common.parameters.ValidationStatus;
+
+public class RestClientParameters extends BusTopicParams implements ParameterGroup {
+
+ private static final String MSG_IS_BLANK = "is blank";
+
+ @Override
+ public String getName() {
+ return getClientName();
+ }
+
+ @Override
+ public void setName(String name) {
+ setClientName(name);
+ }
+
+ @Override
+ public BeanValidationResult validate() {
+ var result = new BeanValidationResult(getClientName(), this);
+ if (isHostnameInvalid()) {
+ result.addResult("hostname", getHostname(), ValidationStatus.INVALID, MSG_IS_BLANK);
+ }
+ if (isClientNameInvalid()) {
+ result.addResult("clientName", getClientName(), ValidationStatus.INVALID, MSG_IS_BLANK);
+ }
+ if (isPortInvalid()) {
+ result.addResult("port", getPort(), ValidationStatus.INVALID, "is not valid");
+ }
+ return result;
+ }
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestServerParameters.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestServerParameters.java
index 85f1f455..9ffe5cb7 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestServerParameters.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/RestServerParameters.java
@@ -1,6 +1,8 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
+ * Copyright (C) 2019,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +23,6 @@
package org.onap.policy.common.endpoints.parameters;
import lombok.Getter;
-
import org.onap.policy.common.parameters.ParameterGroupImpl;
import org.onap.policy.common.parameters.annotations.Min;
import org.onap.policy.common.parameters.annotations.NotBlank;
@@ -32,10 +33,10 @@ import org.onap.policy.common.parameters.annotations.NotNull;
*
* @author Ajith Sreekumar (ajith.sreekumar@est.tech)
*/
-@NotNull
@NotBlank
@Getter
public class RestServerParameters extends ParameterGroupImpl {
+ @NotNull
private String host;
@Min(value = 1)
@@ -44,7 +45,11 @@ public class RestServerParameters extends ParameterGroupImpl {
private String userName;
private String password;
private boolean https;
+ private boolean sniHostCHeck;
private boolean aaf;
+ private boolean prometheus;
+ private String servletClass;
+ private String servletUriPath;
public RestServerParameters() {
super(RestServerParameters.class.getSimpleName());
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroup.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroup.java
index 4cd3893d..d63134bc 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroup.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroup.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2024 Nordix Foundation.
+ * Modifications 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.
@@ -25,7 +25,7 @@ import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.parameters.GroupValidationResult;
+import org.onap.policy.common.parameters.BeanValidationResult;
import org.onap.policy.common.parameters.ParameterGroupImpl;
import org.onap.policy.common.parameters.ValidationStatus;
import org.onap.policy.common.parameters.annotations.NotBlank;
@@ -53,20 +53,20 @@ public class TopicParameterGroup extends ParameterGroupImpl {
* {@inheritDoc}.
*/
@Override
- public GroupValidationResult validate() {
- GroupValidationResult result = super.validate();
+ public BeanValidationResult validate() {
+ BeanValidationResult result = super.validate();
if (result.isValid()) {
- StringBuilder errorMsg = new StringBuilder();
+ var errorMsg = new StringBuilder();
StringBuilder missingSourceParams = checkMissingMandatoryParams(topicSources);
- if (missingSourceParams.length() > 0) {
+ if (!missingSourceParams.isEmpty()) {
errorMsg.append(missingSourceParams.append("missing in topicSources. "));
}
StringBuilder missingSinkParams = checkMissingMandatoryParams(topicSinks);
- if (missingSinkParams.length() > 0) {
+ if (!missingSinkParams.isEmpty()) {
errorMsg.append(missingSinkParams.append("missing in topicSinks."));
}
- if (errorMsg.length() > 0) {
+ if (!errorMsg.isEmpty()) {
errorMsg.insert(0, "Mandatory parameters are missing. ");
result.setResult(ValidationStatus.INVALID, errorMsg.toString());
}
@@ -75,7 +75,7 @@ public class TopicParameterGroup extends ParameterGroupImpl {
}
private StringBuilder checkMissingMandatoryParams(List<TopicParameters> topicParametersList) {
- StringBuilder missingParams = new StringBuilder();
+ var missingParams = new StringBuilder();
for (TopicParameters topicParameters : topicParametersList) {
if (StringUtils.isBlank(topicParameters.getTopic())) {
missingParams.append("topic, ");
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/properties/PolicyEndPointProperties.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/properties/PolicyEndPointProperties.java
index ef9259bf..4b4bf502 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/properties/PolicyEndPointProperties.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/properties/PolicyEndPointProperties.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2022,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.
@@ -20,7 +21,11 @@
package org.onap.policy.common.endpoints.properties;
-public class PolicyEndPointProperties {
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class PolicyEndPointProperties {
/* Generic property suffixes */
@@ -28,8 +33,6 @@ public class PolicyEndPointProperties {
public static final String PROPERTY_TOPIC_TOPICS_SUFFIX = ".topics";
public static final String PROPERTY_TOPIC_API_KEY_SUFFIX = ".apiKey";
public static final String PROPERTY_TOPIC_API_SECRET_SUFFIX = ".apiSecret";
- public static final String PROPERTY_TOPIC_AAF_MECHID_SUFFIX = ".aafMechId";
- public static final String PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX = ".aafPassword"; //NOSONAR
public static final String PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX = ".effectiveTopic";
public static final String PROPERTY_TOPIC_EVENTS_SUFFIX = ".events";
public static final String PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX = ".filter";
@@ -40,7 +43,6 @@ public class PolicyEndPointProperties {
public static final String PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX = ".fetchTimeout";
public static final String PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX = ".fetchLimit";
public static final String PROPERTY_MANAGED_SUFFIX = ".managed";
- public static final String PROPERTY_AAF_SUFFIX = ".aaf";
public static final String PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX = ".partitionKey";
@@ -51,30 +53,14 @@ public class PolicyEndPointProperties {
public static final String PROPERTY_UEB_SOURCE_TOPICS = "ueb.source.topics";
public static final String PROPERTY_UEB_SINK_TOPICS = "ueb.sink.topics";
- /* DMAAP Properties */
-
- public static final String PROPERTY_DMAAP_SOURCE_TOPICS = "dmaap.source.topics";
- public static final String PROPERTY_DMAAP_SINK_TOPICS = "dmaap.sink.topics";
-
- public static final String PROPERTY_DMAAP_DME2_PARTNER_SUFFIX = ".dme2.partner";
- public static final String PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX = ".dme2.routeOffer";
- public static final String PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX = ".dme2.environment";
- public static final String PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX = ".dme2.aft.environment";
- public static final String PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX = ".dme2.latitude";
- public static final String PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX = ".dme2.longitude";
-
- public static final String PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX = ".dme2.epReadTimeoutMs";
- public static final String PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX = ".dme2.epConnTimeout";
- public static final String PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX = ".dme2.roundtripTimeoutMs";
- public static final String PROPERTY_DMAAP_DME2_VERSION_SUFFIX = ".dme2.version";
- public static final String PROPERTY_DMAAP_DME2_SERVICE_NAME_SUFFIX = ".dme2.serviceName";
- public static final String PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX = ".dme2.subContextPath";
- public static final String PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX =
- ".dme2.sessionStickinessRequired";
-
public static final String PROPERTY_NOOP_SOURCE_TOPICS = "noop.source.topics";
public static final String PROPERTY_NOOP_SINK_TOPICS = "noop.sink.topics";
+ /* KAFKA Properties */
+
+ public static final String PROPERTY_KAFKA_SOURCE_TOPICS = "kafka.source.topics";
+ public static final String PROPERTY_KAFKA_SINK_TOPICS = "kafka.sink.topics";
+
/* HTTP Server Properties */
public static final String PROPERTY_HTTP_SERVER_SERVICES = "http.server.services";
@@ -92,8 +78,13 @@ public class PolicyEndPointProperties {
public static final String PROPERTY_HTTP_REST_PACKAGES_SUFFIX = ".restPackages";
public static final String PROPERTY_HTTP_REST_URIPATH_SUFFIX = ".restUriPath";
+ public static final String PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX = ".servletUriPath";
+ public static final String PROPERTY_HTTP_SERVLET_CLASS_SUFFIX = ".servletClass";
+ public static final String PROPERTY_HTTP_PROMETHEUS_SUFFIX = ".prometheus";
+
public static final String PROPERTY_HTTP_HTTPS_SUFFIX = ".https";
public static final String PROPERTY_HTTP_SWAGGER_SUFFIX = ".swagger";
+ public static final String PROPERTY_HTTP_SNI_HOST_CHECK_SUFFIX = ".sniHostCheck";
public static final String PROPERTY_HTTP_SERIALIZATION_PROVIDER = ".serialization.provider";
@@ -103,19 +94,6 @@ public class PolicyEndPointProperties {
public static final String PROPERTY_HTTP_URL_SUFFIX = PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX;
-
- /* DMaaP DME2 Topic Properties */
-
- public static final String DME2_READ_TIMEOUT_PROPERTY = "AFT_DME2_EP_READ_TIMEOUT_MS";
- public static final String DME2_EP_CONN_TIMEOUT_PROPERTY = "AFT_DME2_EP_CONN_TIMEOUT";
- public static final String DME2_ROUNDTRIP_TIMEOUT_PROPERTY = "AFT_DME2_ROUNDTRIP_TIMEOUT_MS";
- public static final String DME2_VERSION_PROPERTY = "Version";
- public static final String DME2_ROUTE_OFFER_PROPERTY = "routeOffer";
- public static final String DME2_SERVICE_NAME_PROPERTY = "ServiceName";
- public static final String DME2_SUBCONTEXT_PATH_PROPERTY = "SubContextPath";
- public static final String DME2_SESSION_STICKINESS_REQUIRED_PROPERTY = "sessionstickinessrequired";
-
-
/* Topic Sink Values */
/**
@@ -145,9 +123,4 @@ public class PolicyEndPointProperties {
* Definition of No limit fetching.
*/
public static final int NO_LIMIT_FETCH = -1;
-
-
- private PolicyEndPointProperties() {
- // do nothing
- }
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/report/HealthCheckReport.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/report/HealthCheckReport.java
index fa2f3d23..bb80fccb 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/report/HealthCheckReport.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/report/HealthCheckReport.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications 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.
@@ -21,11 +21,18 @@
package org.onap.policy.common.endpoints.report;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
/**
* Class to represent health check report of a service.
*
* @author Ram Krishna Verma (ram.krishna.verma@ericsson.com)
*/
+@Getter
+@Setter
+@ToString
public class HealthCheckReport {
private String name;
@@ -33,111 +40,4 @@ public class HealthCheckReport {
private boolean healthy;
private int code;
private String message;
-
- /**
- * Returns the name of this report.
- *
- * @return the name
- */
- public String getName() {
- return name;
- }
-
- /**
- * Set the name of this report.
- *
- * @param name the name to set
- */
- public void setName(final String name) {
- this.name = name;
- }
-
- /**
- * Returns the url of this report.
- *
- * @return the url
- */
- public String getUrl() {
- return url;
- }
-
- /**
- * Set the url of this report.
- *
- * @param url the url to set
- */
- public void setUrl(final String url) {
- this.url = url;
- }
-
- /**
- * Returns the health status of this report.
- *
- * @return the healthy
- */
- public boolean isHealthy() {
- return healthy;
- }
-
- /**
- * Set the health status of this report.
- *
- * @param healthy the healthy to set
- */
- public void setHealthy(final boolean healthy) {
- this.healthy = healthy;
- }
-
- /**
- * Returns the code of this report.
- *
- * @return the code
- */
- public int getCode() {
- return code;
- }
-
- /**
- * Set the code of this report.
- *
- * @param code the code to set
- */
- public void setCode(final int code) {
- this.code = code;
- }
-
- /**
- * Returns the message of this report.
- *
- * @return the message
- */
- public String getMessage() {
- return message;
- }
-
- /**
- * Set the message of this report.
- *
- * @param message the message to set
- */
- public void setMessage(final String message) {
- this.message = message;
- }
-
- @Override
- public String toString() {
- final StringBuilder builder = new StringBuilder();
- builder.append("Report [name=");
- builder.append(getName());
- builder.append(", url=");
- builder.append(getUrl());
- builder.append(", healthy=");
- builder.append(isHealthy());
- builder.append(", code=");
- builder.append(getCode());
- builder.append(", message=");
- builder.append(getMessage());
- builder.append("]");
- return builder.toString();
- }
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/DmaapPropertyUtils.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/DmaapPropertyUtils.java
deleted file mode 100644
index 7e0d3ff6..00000000
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/DmaapPropertyUtils.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 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.endpoints.utils;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
-import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
-
-public class DmaapPropertyUtils {
-
- /**
- * Maps a topic property to a DME property.
- */
- private static final Map<String,String> PROP_TO_DME;
-
- static {
- Map<String,String> map = new HashMap<>();
-
- map.put(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX,
- PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY);
-
- map.put(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX,
- PolicyEndPointProperties.DME2_READ_TIMEOUT_PROPERTY);
-
- map.put(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX,
- PolicyEndPointProperties.DME2_EP_CONN_TIMEOUT_PROPERTY);
-
- map.put(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX,
- PolicyEndPointProperties.DME2_ROUNDTRIP_TIMEOUT_PROPERTY);
-
- map.put(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_VERSION_SUFFIX,
- PolicyEndPointProperties.DME2_VERSION_PROPERTY);
-
- map.put(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX,
- PolicyEndPointProperties.DME2_SUBCONTEXT_PATH_PROPERTY);
-
- map.put(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX,
- PolicyEndPointProperties.DME2_SESSION_STICKINESS_REQUIRED_PROPERTY);
-
- PROP_TO_DME = Collections.unmodifiableMap(map);
- }
-
- private DmaapPropertyUtils() {
- // do nothing
- }
-
- /**
- * Makes a topic builder, configuring it with properties that are common to both
- * sources and sinks.
- *
- * @param props properties to be used to configure the builder
- * @param topic topic being configured
- * @param servers target servers
- * @return a topic builder
- */
- public static TopicParamsBuilder makeBuilder(PropertyUtils props, String topic, String servers) {
-
- /* Additional DME2 Properties */
-
- Map<String, String> dme2AdditionalProps = new HashMap<>();
-
- for (Map.Entry<String, String> ent : PROP_TO_DME.entrySet()) {
- String propName = ent.getKey();
- String value = props.getString(propName, null);
-
- if (!StringUtils.isBlank(value)) {
- String dmeName = ent.getValue();
- dme2AdditionalProps.put(dmeName, value);
- }
- }
-
- final List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
-
- return BusTopicParams.builder()
- .servers(serverList)
- .topic(topic)
- .effectiveTopic(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX,
- topic))
- .apiKey(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_API_KEY_SUFFIX, null))
- .apiSecret(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX, null))
- .userName(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX, null))
- .password(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX, null))
- .environment(props.getString(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX,
- null))
- .aftEnvironment(props.getString(
- PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX, null))
- .partner(props.getString(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX, null))
- .latitude(props.getString(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX, null))
- .longitude(props.getString(PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX, null))
- .additionalProps(dme2AdditionalProps)
- .managed(props.getBoolean(PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, true))
- .useHttps(props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false))
- .allowSelfSignedCerts(props.getBoolean(
- PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX, false));
- }
-}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/KafkaPropertyUtils.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/KafkaPropertyUtils.java
new file mode 100644
index 00000000..03e20762
--- /dev/null
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/KafkaPropertyUtils.java
@@ -0,0 +1,58 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2022-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.endpoints.utils;
+
+import com.google.re2j.Pattern;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
+import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class KafkaPropertyUtils {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
+
+ /**
+ * Makes a topic builder, configuring it with properties that are common to both
+ * sources and sinks.
+ *
+ * @param props properties to be used to configure the builder
+ * @param topic topic being configured
+ * @param servers target servers
+ * @return a topic builder
+ */
+ public static TopicParamsBuilder makeBuilder(PropertyUtils props, String topic, String servers) {
+
+ final List<String> serverList = new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
+
+ return BusTopicParams.builder()
+ .servers(serverList)
+ .topic(topic)
+ .effectiveTopic(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX,
+ topic))
+ .managed(props.getBoolean(PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, true));
+ }
+}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/NetLoggerUtil.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/NetLoggerUtil.java
index c7dd516f..6002c3f6 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/NetLoggerUtil.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/NetLoggerUtil.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.utils;
+import lombok.Getter;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.features.NetLoggerFeatureProviders;
import org.onap.policy.common.utils.services.FeatureApiUtils;
@@ -37,7 +38,8 @@ public class NetLoggerUtil {
* Loggers.
*/
private static final Logger logger = LoggerFactory.getLogger(NetLoggerUtil.class);
- private static final Logger netLogger = LoggerFactory.getLogger("network");
+ @Getter
+ private static final Logger networkLogger = LoggerFactory.getLogger("network");
/**
* Constant for the system line separator.
@@ -52,15 +54,6 @@ public class NetLoggerUtil {
}
/**
- * Get Network Logger.
- *
- * @return logger instance
- */
- public static Logger getNetworkLogger() {
- return netLogger;
- }
-
- /**
* Logs a message to the network logger.
*
* @param type can either be IN or OUT
@@ -69,7 +62,7 @@ public class NetLoggerUtil {
* @param message message to be logged
*/
public static void log(EventType type, CommInfrastructure protocol, String topic, String message) {
- log(netLogger, type, protocol, topic, message);
+ log(networkLogger, type, protocol, topic, message);
}
/**
@@ -85,7 +78,7 @@ public class NetLoggerUtil {
String message) {
if (eventLogger == null) {
logger.debug("the logger is null, defaulting to network logger");
- eventLogger = netLogger;
+ eventLogger = networkLogger;
}
if (featureBeforeLog(eventLogger, type, protocol, topic, message)) {
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/PropertyUtils.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/PropertyUtils.java
index 265346c9..904f9535 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/PropertyUtils.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/PropertyUtils.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,11 +21,13 @@
package org.onap.policy.common.endpoints.utils;
import java.util.Properties;
+import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* Utilities for extracting property values and converting them to other types.
*/
+@AllArgsConstructor
public class PropertyUtils {
/**
* Properties on which to work.
@@ -42,20 +44,6 @@ public class PropertyUtils {
*/
private TriConsumer<String, String, Exception> invalidHandler;
-
- /**
- * Constructs the object.
- *
- * @param properties properties on which to work
- * @param prefix prefix to prepend to property names
- * @param invalidHandler function to invoke if a property value is invalid
- */
- public PropertyUtils(Properties properties, String prefix, TriConsumer<String, String, Exception> invalidHandler) {
- this.properties = properties;
- this.prefix = prefix;
- this.invalidHandler = invalidHandler;
- }
-
/**
* Gets a string property.
*
@@ -129,7 +117,7 @@ public class PropertyUtils {
}
@FunctionalInterface
- public static interface TriConsumer<A,B,C> {
+ public static interface TriConsumer<A, B, C> {
public void accept(A propName, B propValue, C exception);
}
}
diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/UebPropertyUtils.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/UebPropertyUtils.java
index d0217518..8aff9f20 100644
--- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/UebPropertyUtils.java
+++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/UebPropertyUtils.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,18 +20,19 @@
package org.onap.policy.common.endpoints.utils;
+import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UebPropertyUtils {
-
- private UebPropertyUtils() {
- // do nothing
- }
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
/**
* Makes a topic builder, configuring it with properties that are common to both
@@ -44,7 +45,7 @@ public class UebPropertyUtils {
*/
public static TopicParamsBuilder makeBuilder(PropertyUtils props, String topic, String servers) {
- final List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
+ final List<String> serverList = new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
return BusTopicParams.builder()
.servers(serverList)
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java
index a661b063..92dd6483 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -31,12 +32,9 @@ import static org.junit.Assert.assertTrue;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
-
import org.junit.After;
import org.junit.Test;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicFactories;
-import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicPropertyBuilder;
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories;
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicPropertyBuilder;
import org.onap.policy.common.endpoints.event.comm.bus.UebTopicFactories;
@@ -54,9 +52,6 @@ public class TopicEndpointProxyTest {
private static final String UEB_SOURCE_TOPIC = "ueb-source";
private static final String UEB_SINK_TOPIC = "ueb-sink";
- private static final String DMAAP_SOURCE_TOPIC = "dmaap-source";
- private static final String DMAAP_SINK_TOPIC = "dmaap-sink";
-
private Properties configuration = new Properties();
private TopicParameterGroup group = new TopicParameterGroup();
@@ -91,18 +86,6 @@ public class TopicEndpointProxyTest {
configuration.putAll(uebSinkBuilder.build());
group.getTopicSinks().add(uebSinkBuilder.getParams());
- DmaapTopicPropertyBuilder dmaapSourceBuilder =
- new DmaapTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS)
- .makeTopic(DMAAP_SOURCE_TOPIC);
- configuration.putAll(dmaapSourceBuilder.build());
- group.getTopicSources().add(dmaapSourceBuilder.getParams());
-
- DmaapTopicPropertyBuilder dmaapSinkBuilder =
- new DmaapTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS)
- .makeTopic(DMAAP_SINK_TOPIC);
- configuration.putAll(dmaapSinkBuilder.build());
- group.getTopicSinks().add(dmaapSinkBuilder.getParams());
-
TopicParameters invalidCommInfraParams =
new NoopTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS)
.makeTopic(NOOP_SOURCE_TOPIC).getParams();
@@ -116,21 +99,19 @@ public class TopicEndpointProxyTest {
}
private <T extends Topic> boolean allSources(List<T> topics) {
- return exists(topics, NOOP_SOURCE_TOPIC) && exists(topics, UEB_SOURCE_TOPIC)
- && exists(topics, DMAAP_SOURCE_TOPIC);
+ return exists(topics, NOOP_SOURCE_TOPIC) && exists(topics, UEB_SOURCE_TOPIC);
}
private <T extends Topic> boolean allSinks(List<T> topics) {
- return exists(topics, NOOP_SINK_TOPIC) && exists(topics, UEB_SINK_TOPIC) && exists(topics, DMAAP_SINK_TOPIC);
+ return exists(topics, NOOP_SINK_TOPIC) && exists(topics, UEB_SINK_TOPIC);
}
private <T extends Topic> boolean anySource(List<T> topics) {
- return exists(topics, NOOP_SOURCE_TOPIC) || exists(topics, UEB_SOURCE_TOPIC)
- || exists(topics, DMAAP_SOURCE_TOPIC);
+ return exists(topics, NOOP_SOURCE_TOPIC) || exists(topics, UEB_SOURCE_TOPIC);
}
private <T extends Topic> boolean anySink(List<T> topics) {
- return exists(topics, NOOP_SINK_TOPIC) || exists(topics, UEB_SINK_TOPIC) || exists(topics, DMAAP_SINK_TOPIC);
+ return exists(topics, NOOP_SINK_TOPIC) || exists(topics, UEB_SINK_TOPIC);
}
/**
@@ -143,9 +124,6 @@ public class TopicEndpointProxyTest {
UebTopicFactories.getSinkFactory().destroy();
UebTopicFactories.getSourceFactory().destroy();
-
- DmaapTopicFactories.getSinkFactory().destroy();
- DmaapTopicFactories.getSourceFactory().destroy();
}
@Test
@@ -164,7 +142,7 @@ public class TopicEndpointProxyTest {
TopicEndpoint manager = new TopicEndpointProxy();
List<TopicSource> sources = manager.addTopicSources(group.getTopicSources());
- assertSame(3, sources.size());
+ assertSame(2, sources.size());
assertTrue(allSources(sources));
assertFalse(anySink(sources));
@@ -175,7 +153,7 @@ public class TopicEndpointProxyTest {
TopicEndpoint manager = new TopicEndpointProxy();
List<TopicSource> sources = manager.addTopicSources(configuration);
- assertSame(3, sources.size());
+ assertSame(2, sources.size());
assertTrue(allSources(sources));
assertFalse(anySink(sources));
@@ -186,7 +164,7 @@ public class TopicEndpointProxyTest {
TopicEndpoint manager = new TopicEndpointProxy();
List<TopicSink> sinks = manager.addTopicSinks(group.getTopicSinks());
- assertSame(3, sinks.size());
+ assertSame(2, sinks.size());
assertFalse(anySource(sinks));
assertTrue(allSinks(sinks));
@@ -197,7 +175,7 @@ public class TopicEndpointProxyTest {
TopicEndpoint manager = new TopicEndpointProxy();
List<TopicSink> sinks = manager.addTopicSinks(configuration);
- assertSame(3, sinks.size());
+ assertSame(2, sinks.size());
assertFalse(anySource(sinks));
assertTrue(allSinks(sinks));
@@ -208,7 +186,7 @@ public class TopicEndpointProxyTest {
TopicEndpoint manager = new TopicEndpointProxy();
List<Topic> topics = manager.addTopics(configuration);
- assertSame(6, topics.size());
+ assertSame(4, topics.size());
assertTrue(allSources(topics));
assertTrue(allSinks(topics));
@@ -219,7 +197,7 @@ public class TopicEndpointProxyTest {
TopicEndpoint manager = new TopicEndpointProxy();
List<Topic> topics = manager.addTopics(group);
- assertSame(6, topics.size());
+ assertSame(4, topics.size());
assertTrue(allSources(topics));
assertTrue(allSinks(topics));
@@ -258,7 +236,7 @@ public class TopicEndpointProxyTest {
manager.addTopicSinks(configuration);
List<TopicSource> sources = manager.getTopicSources();
- assertSame(3, sources.size());
+ assertSame(2, sources.size());
assertTrue(allSources(sources));
assertFalse(anySink(sources));
@@ -272,7 +250,7 @@ public class TopicEndpointProxyTest {
manager.addTopicSinks(configuration);
List<TopicSink> sinks = manager.getTopicSinks();
- assertSame(3, sinks.size());
+ assertSame(2, sinks.size());
assertFalse(anySource(sinks));
assertTrue(allSinks(sinks));
@@ -287,14 +265,6 @@ public class TopicEndpointProxyTest {
}
@Test
- public void testGetDmaapTopicSources() {
- TopicEndpoint manager = new TopicEndpointProxy();
-
- manager.addTopicSources(configuration);
- assertSame(1, manager.getDmaapTopicSources().size());
- }
-
- @Test
public void testGetNoopTopicSources() {
TopicEndpoint manager = new TopicEndpointProxy();
@@ -311,14 +281,6 @@ public class TopicEndpointProxyTest {
}
@Test
- public void testGetDmaapTopicSinks() {
- TopicEndpoint manager = new TopicEndpointProxy();
-
- manager.addTopicSinks(configuration);
- assertSame(1, manager.getDmaapTopicSinks().size());
- }
-
- @Test
public void testGetNoopTopicSinks() {
TopicEndpoint manager = new TopicEndpointProxy();
@@ -361,14 +323,11 @@ public class TopicEndpointProxyTest {
assertSame(NOOP_SOURCE_TOPIC, manager.getTopicSource(CommInfrastructure.NOOP, NOOP_SOURCE_TOPIC).getTopic());
assertSame(UEB_SOURCE_TOPIC, manager.getTopicSource(CommInfrastructure.UEB, UEB_SOURCE_TOPIC).getTopic());
- assertSame(DMAAP_SOURCE_TOPIC, manager.getTopicSource(CommInfrastructure.DMAAP, DMAAP_SOURCE_TOPIC).getTopic());
assertThatIllegalStateException()
.isThrownBy(() -> manager.getTopicSource(CommInfrastructure.NOOP, NOOP_SINK_TOPIC));
assertThatIllegalStateException()
.isThrownBy(() -> manager.getTopicSource(CommInfrastructure.UEB, UEB_SINK_TOPIC));
- assertThatIllegalStateException()
- .isThrownBy(() -> manager.getTopicSource(CommInfrastructure.DMAAP, DMAAP_SINK_TOPIC));
}
@Test
@@ -378,14 +337,11 @@ public class TopicEndpointProxyTest {
assertSame(NOOP_SINK_TOPIC, manager.getTopicSink(CommInfrastructure.NOOP, NOOP_SINK_TOPIC).getTopic());
assertSame(UEB_SINK_TOPIC, manager.getTopicSink(CommInfrastructure.UEB, UEB_SINK_TOPIC).getTopic());
- assertSame(DMAAP_SINK_TOPIC, manager.getTopicSink(CommInfrastructure.DMAAP, DMAAP_SINK_TOPIC).getTopic());
assertThatIllegalStateException()
.isThrownBy(() -> manager.getTopicSink(CommInfrastructure.NOOP, NOOP_SOURCE_TOPIC));
assertThatIllegalStateException()
.isThrownBy(() -> manager.getTopicSink(CommInfrastructure.UEB, UEB_SOURCE_TOPIC));
- assertThatIllegalStateException()
- .isThrownBy(() -> manager.getTopicSink(CommInfrastructure.DMAAP, DMAAP_SOURCE_TOPIC));
}
@Test
@@ -396,7 +352,6 @@ public class TopicEndpointProxyTest {
assertSame(UEB_SOURCE_TOPIC, manager.getUebTopicSource(UEB_SOURCE_TOPIC).getTopic());
assertThatIllegalStateException().isThrownBy(() -> manager.getUebTopicSource(NOOP_SOURCE_TOPIC));
- assertThatIllegalStateException().isThrownBy(() -> manager.getUebTopicSource(DMAAP_SOURCE_TOPIC));
assertThatIllegalArgumentException().isThrownBy(() -> manager.getUebTopicSource(null));
assertThatIllegalArgumentException().isThrownBy(() -> manager.getUebTopicSource(""));
@@ -410,48 +365,18 @@ public class TopicEndpointProxyTest {
assertSame(UEB_SINK_TOPIC, manager.getUebTopicSink(UEB_SINK_TOPIC).getTopic());
assertThatIllegalStateException().isThrownBy(() -> manager.getUebTopicSink(NOOP_SINK_TOPIC));
- assertThatIllegalStateException().isThrownBy(() -> manager.getUebTopicSink(DMAAP_SINK_TOPIC));
assertThatIllegalArgumentException().isThrownBy(() -> manager.getUebTopicSink(null));
assertThatIllegalArgumentException().isThrownBy(() -> manager.getUebTopicSink(""));
}
@Test
- public void testGetDmaapTopicSource() {
- TopicEndpoint manager = new TopicEndpointProxy();
- manager.addTopicSources(configuration);
-
- assertSame(DMAAP_SOURCE_TOPIC, manager.getDmaapTopicSource(DMAAP_SOURCE_TOPIC).getTopic());
-
- assertThatIllegalStateException().isThrownBy(() -> manager.getDmaapTopicSource(NOOP_SOURCE_TOPIC));
- assertThatIllegalStateException().isThrownBy(() -> manager.getDmaapTopicSource(UEB_SOURCE_TOPIC));
-
- assertThatIllegalArgumentException().isThrownBy(() -> manager.getDmaapTopicSource(null));
- assertThatIllegalArgumentException().isThrownBy(() -> manager.getDmaapTopicSource(""));
- }
-
- @Test
- public void testGetDmaapTopicSink() {
- TopicEndpoint manager = new TopicEndpointProxy();
- manager.addTopicSinks(configuration);
-
- assertSame(DMAAP_SINK_TOPIC, manager.getDmaapTopicSink(DMAAP_SINK_TOPIC).getTopic());
-
- assertThatIllegalStateException().isThrownBy(() -> manager.getDmaapTopicSink(NOOP_SINK_TOPIC));
- assertThatIllegalStateException().isThrownBy(() -> manager.getDmaapTopicSink(UEB_SINK_TOPIC));
-
- assertThatIllegalArgumentException().isThrownBy(() -> manager.getDmaapTopicSink(null));
- assertThatIllegalArgumentException().isThrownBy(() -> manager.getDmaapTopicSink(""));
- }
-
- @Test
public void testGetNoopTopicSource() {
TopicEndpoint manager = new TopicEndpointProxy();
manager.addTopicSources(configuration);
assertSame(NOOP_SOURCE_TOPIC, manager.getNoopTopicSource(NOOP_SOURCE_TOPIC).getTopic());
- assertThatIllegalStateException().isThrownBy(() -> manager.getNoopTopicSource(DMAAP_SOURCE_TOPIC));
assertThatIllegalStateException().isThrownBy(() -> manager.getNoopTopicSource(UEB_SOURCE_TOPIC));
assertThatIllegalArgumentException().isThrownBy(() -> manager.getNoopTopicSource(null));
@@ -465,7 +390,6 @@ public class TopicEndpointProxyTest {
assertSame(NOOP_SINK_TOPIC, manager.getNoopTopicSink(NOOP_SINK_TOPIC).getTopic());
- assertThatIllegalStateException().isThrownBy(() -> manager.getNoopTopicSink(DMAAP_SINK_TOPIC));
assertThatIllegalStateException().isThrownBy(() -> manager.getNoopTopicSink(UEB_SINK_TOPIC));
assertThatIllegalArgumentException().isThrownBy(() -> manager.getNoopTopicSink(null));
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java
index b5c9e614..7a819e0d 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -25,6 +25,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX;
@@ -82,7 +84,7 @@ public abstract class BusTopicFactoryTestBase<T extends Topic> extends TopicFact
assertNotNull(item2);
assertEquals(item.getTopic(), item.getEffectiveTopic());
assertNotEquals(item2.getTopic(), item2.getEffectiveTopic());
- assertTrue(item != item2);
+ assertNotSame(item, item2);
// duplicate topics, but since they aren't managed, they should be different
T item3 = buildTopic(makeBuilder().managed(false).build());
@@ -91,9 +93,9 @@ public abstract class BusTopicFactoryTestBase<T extends Topic> extends TopicFact
assertNotNull(item4);
assertEquals(MY_TOPIC, item4.getTopic());
assertEquals(TOPIC2, item4.getEffectiveTopic());
- assertTrue(item != item3);
- assertTrue(item != item4);
- assertTrue(item3 != item4);
+ assertNotSame(item, item3);
+ assertNotSame(item, item4);
+ assertNotSame(item3, item4);
// two managed topics
T item5 = buildTopic(makeBuilder().build());
@@ -102,8 +104,8 @@ public abstract class BusTopicFactoryTestBase<T extends Topic> extends TopicFact
assertNotNull(item6);
// re-build same managed topics - should get exact same objects
- assertTrue(item5 == buildTopic(makeBuilder().topic(MY_TOPIC).build()));
- assertTrue(item6 == buildTopic(makeBuilder().topic(TOPIC2).build()));
+ assertSame(item5, buildTopic(makeBuilder().topic(MY_TOPIC).build()));
+ assertSame(item6, buildTopic(makeBuilder().topic(TOPIC2).build()));
}
/**
@@ -135,11 +137,11 @@ public abstract class BusTopicFactoryTestBase<T extends Topic> extends TopicFact
T item2 = buildTopic(servers, TOPIC2);
assertNotNull(item2);
- assertTrue(item1 != item2);
+ assertNotSame(item1, item2);
// duplicate - should be the same, as these topics are managed
T item3 = buildTopic(servers, TOPIC2);
- assertTrue(item2 == item3);
+ assertSame(item2, item3);
}
/**
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactoryTestBase.java
deleted file mode 100644
index 92d5a865..00000000
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactoryTestBase.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * policy-endpoints
- * ================================================================================
- * 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=========================================================
- */
-
-package org.onap.policy.common.endpoints.event.comm.bus;
-
-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
-import static org.junit.Assert.assertEquals;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_VERSION_SUFFIX;
-
-import java.util.Map;
-import org.onap.policy.common.endpoints.event.comm.Topic;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
-import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
-
-/**
- * Base class for DmaapTopicXxxFactory tests.
- *
- * @param <T> type of topic managed by the factory
- */
-public abstract class DmaapTopicFactoryTestBase<T extends Topic> extends BusTopicFactoryTestBase<T> {
-
- public static final String MY_CONN_TIMEOUT = "200";
- public static final String MY_READ_TIMEOUT = "201";
- public static final String MY_ROUNDTRIP_TIMEOUT = "202";
- public static final String MY_STICKINESS = "true";
- public static final String MY_SUBCONTEXT = "my-subcontext";
- public static final String MY_DME_VERSION = "my-version";
-
- @Override
- public void testBuildProperties() {
-
- super.testBuildProperties();
-
- // check properties specific to DMaaP/DME2
- initFactory();
-
- assertEquals(1, buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build()).size());
-
- BusTopicParams params = getLastParams();
- assertEquals(MY_ENV, params.getEnvironment());
- assertEquals(MY_LAT, params.getLatitude());
- assertEquals(MY_LONG, params.getLongitude());
- assertEquals(MY_PARTNER, params.getPartner());
-
- Map<String, String> add = params.getAdditionalProps();
- assertEquals(MY_CONN_TIMEOUT, add.get(PolicyEndPointProperties.DME2_EP_CONN_TIMEOUT_PROPERTY));
- assertEquals(MY_READ_TIMEOUT, add.get(PolicyEndPointProperties.DME2_READ_TIMEOUT_PROPERTY));
- assertEquals(MY_ROUNDTRIP_TIMEOUT, add.get(PolicyEndPointProperties.DME2_ROUNDTRIP_TIMEOUT_PROPERTY));
- assertEquals(MY_ROUTE, add.get(PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY));
- assertEquals(MY_STICKINESS, add.get(PolicyEndPointProperties.DME2_SESSION_STICKINESS_REQUIRED_PROPERTY));
- assertEquals(MY_SUBCONTEXT, add.get(PolicyEndPointProperties.DME2_SUBCONTEXT_PATH_PROPERTY));
- assertEquals(MY_DME_VERSION, add.get(PolicyEndPointProperties.DME2_VERSION_PROPERTY));
- }
-
- @Override
- public void testBuildProperties_Variations() {
- super.testBuildProperties_Variations();
-
- // check "additional" properties
- expectNullAddProp(PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX,
- PolicyEndPointProperties.DME2_EP_CONN_TIMEOUT_PROPERTY);
-
- expectNullAddProp(PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX,
- PolicyEndPointProperties.DME2_READ_TIMEOUT_PROPERTY);
-
- expectNullAddProp(PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX,
- PolicyEndPointProperties.DME2_ROUNDTRIP_TIMEOUT_PROPERTY);
-
- expectNullAddProp(PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX, PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY);
-
- expectNullAddProp(PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX,
- PolicyEndPointProperties.DME2_SESSION_STICKINESS_REQUIRED_PROPERTY);
-
- expectNullAddProp(PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX,
- PolicyEndPointProperties.DME2_SUBCONTEXT_PATH_PROPERTY);
-
- expectNullAddProp(PROPERTY_DMAAP_DME2_VERSION_SUFFIX, PolicyEndPointProperties.DME2_VERSION_PROPERTY);
- }
-
- @Override
- public void testBuildListOfStringString() {
- super.testBuildListOfStringString();
-
- // check parameters that were used
- BusTopicParams params = getLastParams();
- assertEquals(false, params.isAllowSelfSignedCerts());
- }
-
- /**
- * Tests exception cases with get(topic). DMaaP topics are special in that they
- * throw IllegalArgumentException, even for an unknown topic name; all of the
- * other Topic Factory classes throw IllegalStateException, thus we override
- * the default test method.
- */
- @Override
- public void testGet_Ex() {
- // null topic
- assertThatIllegalArgumentException().as("null topic").isThrownBy(() -> getTopic(null));
-
- // empty topic
- assertThatIllegalArgumentException().as("empty topic").isThrownBy(() -> getTopic(""));
-
- // unknown topic
- initFactory();
- buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build());
-
- assertThatIllegalStateException().as("unknown topic").isThrownBy(() -> getTopic(TOPIC2));
- }
-}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicPropertyBuilder.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicPropertyBuilder.java
deleted file mode 100644
index 2e9a6cd7..00000000
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicPropertyBuilder.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * 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=========================================================
- */
-
-package org.onap.policy.common.endpoints.event.comm.bus;
-
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_AFT_ENV;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_API_KEY;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_API_SECRET;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_CONS_GROUP;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_CONS_INST;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_EFFECTIVE_TOPIC;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_ENV;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_FETCH_LIMIT;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_FETCH_TIMEOUT;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_LAT;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_LONG;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_PARTITION;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_PARTNER;
-import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_ROUTE;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_VERSION_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_API_KEY_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX;
-
-import java.util.Arrays;
-import lombok.Getter;
-import org.onap.policy.common.endpoints.parameters.TopicParameters;
-
-public class DmaapTopicPropertyBuilder extends TopicPropertyBuilder {
-
- public static final String SERVER = "my-server";
- public static final String TOPIC2 = "my-topic-2";
-
- public static final String MY_CONN_TIMEOUT = "200";
- public static final String MY_READ_TIMEOUT = "201";
- public static final String MY_ROUNDTRIP_TIMEOUT = "202";
- public static final String MY_STICKINESS = "true";
- public static final String MY_SUBCONTEXT = "my-subcontext";
- public static final String MY_DME_VERSION = "my-version";
- public static final String MY_AAF_MECHID = "my-aaf-mechid";
- public static final String MY_AAF_PASS = "my-aaf-passwd";
-
- @Getter
- private TopicParameters params = new TopicParameters();
-
- /**
- * Constructs the object.
- *
- * @param prefix the prefix for the properties to be built
- */
- public DmaapTopicPropertyBuilder(String prefix) {
- super(prefix);
- }
-
- /**
- * Adds a topic and configures it's properties with default values.
- *
- * @param topic the topic to be added
- * @return this builder
- */
- public DmaapTopicPropertyBuilder makeTopic(String topic) {
- addTopic(topic);
-
- setTopicProperty(PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX, MY_EFFECTIVE_TOPIC);
- setTopicProperty(PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, MY_CONS_GROUP);
- setTopicProperty(PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX, MY_CONS_INST);
- setTopicProperty(PROPERTY_MANAGED_SUFFIX, "true");
- setTopicProperty(PROPERTY_HTTP_HTTPS_SUFFIX, "true");
- setTopicProperty(PROPERTY_TOPIC_AAF_MECHID_SUFFIX, MY_AAF_MECHID);
- setTopicProperty(PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX, MY_AAF_PASS);
- setTopicProperty(PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX, MY_AFT_ENV);
- setTopicProperty(PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX, "true");
- setTopicProperty(PROPERTY_TOPIC_API_KEY_SUFFIX, MY_API_KEY);
- setTopicProperty(PROPERTY_TOPIC_API_SECRET_SUFFIX, MY_API_SECRET);
- setTopicProperty(PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX, MY_FETCH_LIMIT);
- setTopicProperty(PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX, MY_FETCH_TIMEOUT);
- setTopicProperty(PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX, MY_CONN_TIMEOUT);
- setTopicProperty(PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX, MY_ENV);
- setTopicProperty(PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX, MY_LAT);
- setTopicProperty(PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX, MY_LONG);
- setTopicProperty(PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, MY_PARTITION);
- setTopicProperty(PROPERTY_DMAAP_DME2_PARTNER_SUFFIX, MY_PARTNER);
- setTopicProperty(PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX, MY_READ_TIMEOUT);
- setTopicProperty(PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX, MY_ROUNDTRIP_TIMEOUT);
- setTopicProperty(PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX, MY_ROUTE);
- setTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX, SERVER);
- setTopicProperty(PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX, MY_STICKINESS);
- setTopicProperty(PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX, MY_SUBCONTEXT);
- setTopicProperty(PROPERTY_DMAAP_DME2_VERSION_SUFFIX, MY_DME_VERSION);
-
- params.setTopicCommInfrastructure("dmaap");
- params.setTopic(topic);
- params.setEffectiveTopic(MY_EFFECTIVE_TOPIC);
- params.setConsumerGroup(MY_CONS_GROUP);
- params.setConsumerInstance(MY_CONS_INST);
- params.setManaged(true);
- params.setUseHttps(true);
- params.setUserName(MY_AAF_MECHID);
- params.setPassword(MY_AAF_PASS);
- params.setAftEnvironment(MY_AFT_ENV);
- params.setAllowSelfSignedCerts(true);
- params.setApiKey(MY_API_KEY);
- params.setApiSecret(MY_API_SECRET);
- params.setFetchLimit(MY_FETCH_LIMIT);
- params.setFetchTimeout(MY_FETCH_TIMEOUT);
- params.setEnvironment(MY_ENV);
- params.setLatitude(MY_LAT);
- params.setLongitude(MY_LONG);
- params.setPartitionId(MY_PARTITION);
- params.setPartner(MY_PARTNER);
- params.setServers(Arrays.asList(SERVER));
-
- return this;
- }
-}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicFactoryTestBase.java
new file mode 100644
index 00000000..3986549c
--- /dev/null
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicFactoryTestBase.java
@@ -0,0 +1,48 @@
+/*
+ * ============LICENSE_START=======================================================
+ * policy-endpoints
+ * ================================================================================
+ * 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=========================================================
+ */
+
+package org.onap.policy.common.endpoints.event.comm.bus;
+
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+
+import java.util.Collections;
+import org.onap.policy.common.endpoints.event.comm.Topic;
+
+/**
+ * Base class for KafkaTopicXxxFactory tests.
+ *
+ * @param <T> type of topic managed by the factory
+ */
+public abstract class KafkaTopicFactoryTestBase<T extends Topic> extends BusTopicFactoryTestBase<T> {
+
+ @Override
+ public void testBuildBusTopicParams_Ex() {
+
+ super.testBuildBusTopicParams_Ex();
+
+ // null servers
+ assertThatIllegalArgumentException().as("null servers")
+ .isThrownBy(() -> buildTopic(makeBuilder().servers(null).build()));
+
+ // empty servers
+ assertThatIllegalArgumentException().as("empty servers")
+ .isThrownBy(() -> buildTopic(makeBuilder().servers(Collections.emptyList()).build()));
+ }
+}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicPropertyBuilder.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicPropertyBuilder.java
new file mode 100644
index 00000000..a00879c1
--- /dev/null
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicPropertyBuilder.java
@@ -0,0 +1,75 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2022 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.endpoints.event.comm.bus;
+
+import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_EFFECTIVE_TOPIC;
+import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_PARTITION;
+import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX;
+import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX;
+import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX;
+import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX;
+import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX;
+
+import java.util.Arrays;
+import lombok.Getter;
+import org.onap.policy.common.endpoints.parameters.TopicParameters;
+
+public class KafkaTopicPropertyBuilder extends TopicPropertyBuilder {
+
+ public static final String SERVER = "localhost:9092";
+ public static final String TOPIC2 = "my-topic-2";
+
+ @Getter
+ private TopicParameters params = new TopicParameters();
+
+ /**
+ * Constructs the object.
+ *
+ * @param prefix the prefix for the properties to be built
+ */
+ public KafkaTopicPropertyBuilder(String prefix) {
+ super(prefix);
+ }
+
+ /**
+ * Adds a topic and configures it's properties with default values.
+ *
+ * @param topic the topic to be added
+ * @return this builder
+ */
+ public KafkaTopicPropertyBuilder makeTopic(String topic) {
+ addTopic(topic);
+
+ setTopicProperty(PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX, MY_EFFECTIVE_TOPIC);
+ setTopicProperty(PROPERTY_MANAGED_SUFFIX, "true");
+ setTopicProperty(PROPERTY_HTTP_HTTPS_SUFFIX, "true");
+ setTopicProperty(PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, MY_PARTITION);
+ setTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX, SERVER);
+
+ params.setTopicCommInfrastructure("kafka");
+ params.setTopic(topic);
+ params.setEffectiveTopic(MY_EFFECTIVE_TOPIC);
+ params.setManaged(true);
+ params.setUseHttps(true);
+ params.setPartitionId(MY_PARTITION);
+ params.setServers(Arrays.asList(SERVER));
+
+ return this;
+ }
+}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkFactoryTest.java
index 6c9dfcbd..c109e70a 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkFactoryTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2022 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +22,10 @@ package org.onap.policy.common.endpoints.event.comm.bus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS;
+import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS;
+import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX;
+import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
@@ -33,9 +35,10 @@ import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
-public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTopicSink> {
+public class KafkaTopicSinkFactoryTest extends KafkaTopicFactoryTestBase<KafkaTopicSink> {
private SinkFactory factory;
+ public static final String KAFKA_SERVER = "localhost:9092";
/**
* Creates the object to be tested.
@@ -64,18 +67,37 @@ public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTo
@Override
public void testBuildListOfStringString() {
super.testBuildListOfStringString();
+
+ // check parameters that were used
+ BusTopicParams params = getLastParams();
+ assertEquals(false, params.isAllowSelfSignedCerts());
}
@Test
@Override
public void testBuildProperties() {
- super.testBuildProperties();
- super.testBuildProperties_Variations();
- super.testBuildProperties_Multiple();
-
- // check sink-specific parameters that were used
- BusTopicParams params = factory.params.getFirst();
+ List<KafkaTopicSink> topics = buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build());
+ assertEquals(1, topics.size());
+ assertEquals(MY_TOPIC, topics.get(0).getTopic());
+ assertEquals(MY_EFFECTIVE_TOPIC, topics.get(0).getEffectiveTopic());
+
+ BusTopicParams params = getLastParams();
+ assertEquals(true, params.isManaged());
+ assertEquals(false, params.isUseHttps());
+ assertEquals(Arrays.asList(KAFKA_SERVER), params.getServers());
+ assertEquals(MY_TOPIC, params.getTopic());
+ assertEquals(MY_EFFECTIVE_TOPIC, params.getEffectiveTopic());
assertEquals(MY_PARTITION, params.getPartitionId());
+
+ List<KafkaTopicSink> topics2 = buildTopics(makePropBuilder().makeTopic(TOPIC3)
+ .removeTopicProperty(PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX).build());
+ assertEquals(1, topics2.size());
+ assertEquals(TOPIC3, topics2.get(0).getTopic());
+ assertEquals(topics2.get(0).getTopic(), topics2.get(0).getEffectiveTopic());
+
+ initFactory();
+
+ assertEquals(1, buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build()).size());
}
@Test
@@ -98,7 +120,7 @@ public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTo
@Test
public void testToString() {
- assertTrue(factory.toString().startsWith("IndexedDmaapTopicSinkFactory ["));
+ assertTrue(factory.toString().startsWith("IndexedKafkaTopicSinkFactory ["));
}
@Override
@@ -111,17 +133,17 @@ public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTo
}
@Override
- protected List<DmaapTopicSink> buildTopics(Properties properties) {
+ protected List<KafkaTopicSink> buildTopics(Properties properties) {
return factory.build(properties);
}
@Override
- protected DmaapTopicSink buildTopic(BusTopicParams params) {
+ protected KafkaTopicSink buildTopic(BusTopicParams params) {
return factory.build(params);
}
@Override
- protected DmaapTopicSink buildTopic(List<String> servers, String topic) {
+ protected KafkaTopicSink buildTopic(List<String> servers, String topic) {
return factory.build(servers, topic);
}
@@ -136,12 +158,12 @@ public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTo
}
@Override
- protected List<DmaapTopicSink> getInventory() {
+ protected List<KafkaTopicSink> getInventory() {
return factory.inventory();
}
@Override
- protected DmaapTopicSink getTopic(String topic) {
+ protected KafkaTopicSink getTopic(String topic) {
return factory.get(topic);
}
@@ -152,17 +174,17 @@ public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTo
@Override
protected TopicPropertyBuilder makePropBuilder() {
- return new DmaapTopicPropertyBuilder(PROPERTY_DMAAP_SINK_TOPICS);
+ return new KafkaTopicPropertyBuilder(PROPERTY_KAFKA_SINK_TOPICS);
}
/**
* Factory that records the parameters of all of the sinks it creates.
*/
- private static class SinkFactory extends IndexedDmaapTopicSinkFactory {
+ private static class SinkFactory extends IndexedKafkaTopicSinkFactory {
private Deque<BusTopicParams> params = new LinkedList<>();
@Override
- protected DmaapTopicSink makeSink(BusTopicParams busTopicParams) {
+ protected KafkaTopicSink makeSink(BusTopicParams busTopicParams) {
params.add(busTopicParams);
return super.makeSink(busTopicParams);
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkTest.java
index 9136108a..503e5131 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSinkTest.java
@@ -24,11 +24,11 @@ import static org.junit.Assert.assertNotNull;
import org.junit.Test;
-public class DmaapTopicSinkTest {
+public class KafkaTopicSinkTest {
@Test
public void test() {
- assertNotNull(DmaapTopicFactories.getSinkFactory());
+ assertNotNull(KafkaTopicFactories.getSinkFactory());
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceFactoryTest.java
index b4c2f758..1c6985ad 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceFactoryTest.java
@@ -3,6 +3,7 @@
* ONAP Policy Engine - Common Modules
* ================================================================================
* Copyright (C) 2018-2019 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.
@@ -21,12 +22,10 @@
package org.onap.policy.common.endpoints.event.comm.bus;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX;
+import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS;
+import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
@@ -35,12 +34,13 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
-import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
-public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<DmaapTopicSource> {
+public class KafkaTopicSourceFactoryTest extends KafkaTopicFactoryTestBase<KafkaTopicSource> {
private SourceFactory factory;
+ public static final String KAFKA_SERVER = "localhost:9092";
+
/**
* Creates the object to be tested.
*/
@@ -59,60 +59,21 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
@Test
@Override
- public void testBuildBusTopicParams() {
- super.testBuildBusTopicParams();
- super.testBuildBusTopicParams_Ex();
- }
-
- @Test
- @Override
public void testBuildProperties() {
- super.testBuildProperties();
-
- // check source-specific parameters that were used
- BusTopicParams params = factory.params.getFirst();
- assertEquals(MY_CONS_GROUP, params.getConsumerGroup());
- assertEquals(MY_CONS_INST, params.getConsumerInstance());
- assertEquals(MY_FETCH_LIMIT, params.getFetchLimit());
- assertEquals(MY_FETCH_TIMEOUT, params.getFetchTimeout());
- super.testBuildProperties_Variations();
- super.testBuildProperties_Multiple();
+ initFactory();
- // check default values for source-specific parameters
- checkDefault(PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX,
- params2 -> params2.getFetchLimit() == PolicyEndPointProperties.DEFAULT_LIMIT_FETCH,
- null, "", "invalid-limit-number");
-
- checkDefault(PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX,
- params2 -> params2.getFetchTimeout() == PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH,
- null, "", "invalid-timeout-number");
- }
-
- @Test
- public void testBuildListOfStringStringStringString() {
- DmaapTopicSource source1 = factory.build(servers, MY_TOPIC, MY_API_KEY, MY_API_SECRET);
- assertNotNull(source1);
-
- // check source-specific parameters that were used
- BusTopicParams params = factory.params.getFirst();
- assertEquals(MY_API_KEY, params.getApiKey());
- assertEquals(MY_API_SECRET, params.getApiSecret());
- assertEquals(PolicyEndPointProperties.DEFAULT_LIMIT_FETCH, params.getFetchLimit());
- assertEquals(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH, params.getFetchTimeout());
- }
-
- @Test
- @Override
- public void testBuildListOfStringString() {
- super.testBuildListOfStringString();
+ List<KafkaTopicSource> topics = buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build());
+ assertEquals(1, topics.size());
+ assertEquals(MY_TOPIC, topics.get(0).getTopic());
+ assertEquals(MY_EFFECTIVE_TOPIC, topics.get(0).getEffectiveTopic());
- // check source-specific parameters that were used
- BusTopicParams params = factory.params.getFirst();
- assertEquals(null, params.getApiKey());
- assertEquals(null, params.getApiSecret());
- assertEquals(PolicyEndPointProperties.DEFAULT_LIMIT_FETCH, params.getFetchLimit());
- assertEquals(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH, params.getFetchTimeout());
+ BusTopicParams params = getLastParams();
+ assertEquals(true, params.isManaged());
+ assertEquals(false, params.isUseHttps());
+ assertEquals(Arrays.asList(KAFKA_SERVER), params.getServers());
+ assertEquals(MY_TOPIC, params.getTopic());
+ assertEquals(MY_EFFECTIVE_TOPIC, params.getEffectiveTopic());
}
@Test
@@ -135,7 +96,7 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
@Test
public void testToString() {
- assertTrue(factory.toString().startsWith("IndexedDmaapTopicSourceFactory ["));
+ assertTrue(factory.toString().startsWith("IndexedKafkaTopicSourceFactory ["));
}
@Override
@@ -148,17 +109,17 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
}
@Override
- protected List<DmaapTopicSource> buildTopics(Properties properties) {
+ protected List<KafkaTopicSource> buildTopics(Properties properties) {
return factory.build(properties);
}
@Override
- protected DmaapTopicSource buildTopic(BusTopicParams params) {
+ protected KafkaTopicSource buildTopic(BusTopicParams params) {
return factory.build(params);
}
@Override
- protected DmaapTopicSource buildTopic(List<String> servers, String topic) {
+ protected KafkaTopicSource buildTopic(List<String> servers, String topic) {
return factory.build(servers, topic);
}
@@ -173,12 +134,12 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
}
@Override
- protected List<DmaapTopicSource> getInventory() {
+ protected List<KafkaTopicSource> getInventory() {
return factory.inventory();
}
@Override
- protected DmaapTopicSource getTopic(String topic) {
+ protected KafkaTopicSource getTopic(String topic) {
return factory.get(topic);
}
@@ -189,17 +150,17 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
@Override
protected TopicPropertyBuilder makePropBuilder() {
- return new DmaapTopicPropertyBuilder(PROPERTY_DMAAP_SOURCE_TOPICS);
+ return new KafkaTopicPropertyBuilder(PROPERTY_KAFKA_SOURCE_TOPICS);
}
/**
* Factory that records the parameters of all of the sources it creates.
*/
- private static class SourceFactory extends IndexedDmaapTopicSourceFactory {
+ private static class SourceFactory extends IndexedKafkaTopicSourceFactory {
private Deque<BusTopicParams> params = new LinkedList<>();
@Override
- protected DmaapTopicSource makeSource(BusTopicParams busTopicParams) {
+ protected KafkaTopicSource makeSource(BusTopicParams busTopicParams) {
params.add(busTopicParams);
return super.makeSource(busTopicParams);
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceTest.java
index 1735e2ee..ee2d1d7b 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/KafkaTopicSourceTest.java
@@ -24,11 +24,11 @@ import static org.junit.Assert.assertNotNull;
import org.junit.Test;
-public class DmaapTopicSourceTest {
+public class KafkaTopicSourceTest {
@Test
- public void test() {
- assertNotNull(DmaapTopicFactories.getSourceFactory());
+ public void verifyKafkaTopicFactoriesNotNull() {
+ assertNotNull(KafkaTopicFactories.getSourceFactory());
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpointTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpointTest.java
index 0974a041..6cdb628a 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpointTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpointTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -29,7 +29,6 @@ import static org.mockito.Mockito.verify;
import java.util.Arrays;
import java.util.Collections;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactoryTest.java
index 5cb9bcbd..af7a4b29 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactoryTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactoryTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -20,7 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
@@ -136,7 +136,7 @@ public abstract class NoopTopicFactoryTest<F extends NoopTopicFactory<T>, T exte
initFactory();
assertEquals(1, buildTopics(makePropBuilder().makeTopic(MY_TOPIC)
.setTopicProperty(PROPERTY_MANAGED_SUFFIX, "false").build()).size());
- assertThatThrownBy(() -> factory.get(MY_TOPIC));
+ assertThatIllegalStateException().isThrownBy(() -> factory.get(MY_TOPIC));
// managed undefined - default to true
initFactory();
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicFactoryTestBase.java
index d8a16428..9795fd30 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicFactoryTestBase.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicFactoryTestBase.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -24,6 +24,8 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX;
@@ -126,9 +128,9 @@ public abstract class TopicFactoryTestBase<T extends Topic> extends TopicTestBas
int index = 0;
T item = lst.get(index++);
- assertTrue(item != lst.get(index++));
- assertTrue(item == lst.get(index++));
- assertTrue(item == lst.get(index++));
+ assertNotSame(item, lst.get(index++));
+ assertSame(item, lst.get(index++));
+ assertSame(item, lst.get(index++));
}
/**
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicTestBase.java
index 8b75fa35..00111fb2 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicTestBase.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicTestBase.java
@@ -3,6 +3,7 @@
* policy-endpoints
* ================================================================================
* 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.
@@ -59,6 +60,8 @@ public class TopicTestBase {
public static final String ROUTE_PROP = "routeOffer";
public static final String MY_ROUTE = "my-route";
+ public static final String MY_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer";
+ public static final int KAFKA_PORT = 9092;
/**
* Message used within exceptions that are expected.
@@ -76,6 +79,11 @@ public class TopicTestBase {
protected List<String> servers;
/**
+ * Servers to be added to the parameter builder.
+ */
+ protected List<String> kafkaServers;
+
+ /**
* Parameter builder used to build topic parameters.
*/
protected TopicParamsBuilder builder;
@@ -89,13 +97,14 @@ public class TopicTestBase {
addProps.put("my-key-B", "my-value-B");
servers = Arrays.asList("svra", "svrb");
+ kafkaServers = Arrays.asList("localhost:9092", "10.1.2.3:9092");
builder = makeBuilder();
}
/**
* Makes a fully populated parameter builder.
- *
+ *
* @return a new parameter builder
*/
public TopicParamsBuilder makeBuilder() {
@@ -117,6 +126,39 @@ public class TopicTestBase {
.fetchLimit(MY_FETCH_LIMIT).fetchTimeout(MY_FETCH_TIMEOUT).hostname(MY_HOST).latitude(MY_LAT)
.longitude(MY_LONG).managed(true).partitionId(MY_PARTITION).partner(MY_PARTNER)
.password(MY_PASS).port(MY_PORT).servers(servers).topic(MY_TOPIC)
- .effectiveTopic(MY_EFFECTIVE_TOPIC).useHttps(true).userName(MY_USERNAME);
+ .effectiveTopic(MY_EFFECTIVE_TOPIC).useHttps(true).allowTracing(true).userName(MY_USERNAME)
+ .serializationProvider(MY_SERIALIZER);
+ }
+
+ /**
+ * Makes a fully populated parameter builder.
+ *
+ * @return a new parameter builder
+ */
+ public TopicParamsBuilder makeKafkaBuilder() {
+ addProps.clear();
+ String jaas = "org.apache.kafka.common.security.plain.PlainLoginModule "
+ + "required username=abc password=abc serviceName=kafka;";
+ addProps.put("sasl.jaas.config", jaas);
+ addProps.put("sasl.mechanism", "SCRAM-SHA-512");
+ addProps.put("security.protocol", "SASL_PLAINTEXT");
+
+ return makeKafkaBuilder(addProps, kafkaServers);
+ }
+
+ /**
+ * Makes a fully populated parameter builder.
+ *
+ * @param addProps additional properties to be added to the builder
+ * @param servers servers to be added to the builder
+ * @return a new parameter builder
+ */
+ public TopicParamsBuilder makeKafkaBuilder(Map<String, String> addProps, List<String> servers) {
+
+ return BusTopicParams.builder().additionalProps(addProps).basePath(MY_BASE_PATH).clientName(MY_CLIENT_NAME)
+ .consumerGroup(MY_CONS_GROUP).consumerInstance(MY_CONS_INST).environment(MY_ENV)
+ .hostname(MY_HOST).partitionId(MY_PARTITION).partner(MY_PARTNER).fetchTimeout(MY_FETCH_TIMEOUT)
+ .port(KAFKA_PORT).servers(servers).topic(MY_TOPIC)
+ .effectiveTopic(MY_EFFECTIVE_TOPIC).useHttps(false).allowTracing(true);
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicPropertyBuilder.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicPropertyBuilder.java
index cb5507e5..42ea6eba 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicPropertyBuilder.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicPropertyBuilder.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* 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.
@@ -30,11 +31,8 @@ import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_F
import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_FETCH_TIMEOUT;
import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_PARTITION;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX;
-import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_API_KEY_SUFFIX;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX;
@@ -45,20 +43,17 @@ import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperti
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX;
import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX;
-import java.util.Arrays;
+import java.util.List;
import lombok.Getter;
import org.onap.policy.common.endpoints.parameters.TopicParameters;
+@Getter
public class UebTopicPropertyBuilder extends TopicPropertyBuilder {
public static final String SERVER = "my-server";
public static final String TOPIC2 = "my-topic-2";
- public static final String MY_AAF_MECHID = "my-aaf-mechid";
- public static final String MY_AAF_PASS = "my-aaf-passwd";
-
- @Getter
- private TopicParameters params = new TopicParameters();
+ private final TopicParameters params = new TopicParameters();
/**
* Constructs the object.
@@ -70,7 +65,7 @@ public class UebTopicPropertyBuilder extends TopicPropertyBuilder {
}
/**
- * Adds a topic and configures it's properties with default values.
+ * Adds a topic and configures its properties with default values.
*
* @param topic the topic to be added
* @return this builder
@@ -83,9 +78,6 @@ public class UebTopicPropertyBuilder extends TopicPropertyBuilder {
setTopicProperty(PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX, MY_CONS_INST);
setTopicProperty(PROPERTY_MANAGED_SUFFIX, "true");
setTopicProperty(PROPERTY_HTTP_HTTPS_SUFFIX, "true");
- setTopicProperty(PROPERTY_TOPIC_AAF_MECHID_SUFFIX, MY_AAF_MECHID);
- setTopicProperty(PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX, MY_AAF_PASS);
- setTopicProperty(PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX, MY_AFT_ENV);
setTopicProperty(PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX, "true");
setTopicProperty(PROPERTY_TOPIC_API_KEY_SUFFIX, MY_API_KEY);
setTopicProperty(PROPERTY_TOPIC_API_SECRET_SUFFIX, MY_API_SECRET);
@@ -101,8 +93,6 @@ public class UebTopicPropertyBuilder extends TopicPropertyBuilder {
params.setConsumerInstance(MY_CONS_INST);
params.setManaged(true);
params.setUseHttps(true);
- params.setUserName(MY_AAF_MECHID);
- params.setPassword(MY_AAF_PASS);
params.setAftEnvironment(MY_AFT_ENV);
params.setAllowSelfSignedCerts(true);
params.setApiKey(MY_API_KEY);
@@ -110,7 +100,7 @@ public class UebTopicPropertyBuilder extends TopicPropertyBuilder {
params.setFetchLimit(MY_FETCH_LIMIT);
params.setFetchTimeout(MY_FETCH_TIMEOUT);
params.setPartitionId(MY_PARTITION);
- params.setServers(Arrays.asList(SERVER));
+ params.setServers(List.of(SERVER));
return this;
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java
index 0255c100..70fa83c6 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -20,36 +21,121 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.att.nsa.cambria.client.CambriaConsumer;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.CountDownLatch;
import org.apache.commons.collections4.IteratorUtils;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.TopicPartition;
import org.junit.Before;
import org.junit.Test;
-import org.onap.dmaap.mr.client.impl.MRConsumerImpl;
-import org.onap.dmaap.mr.client.response.MRConsumerResponse;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.CambriaConsumerWrapper;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.DmaapAafConsumerWrapper;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.DmaapConsumerWrapper;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.DmaapDmeConsumerWrapper;
-import org.powermock.reflect.Whitebox;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.FetchingBusConsumer;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.KafkaConsumerWrapper;
+import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
+import org.springframework.test.util.ReflectionTestUtils;
public class BusConsumerTest extends TopicTestBase {
+ private static final int SHORT_TIMEOUT_MILLIS = 10;
+ private static final int LONG_TIMEOUT_MILLIS = 3000;
+
+ @Mock
+ KafkaConsumer<String, String> mockedKafkaConsumer;
+
@Before
@Override
public void setUp() {
super.setUp();
+ MockitoAnnotations.initMocks(this);
+ }
+
+
+ @Test
+ public void testFetchingBusConsumer() {
+ // should not be negative
+ var cons = new FetchingBusConsumerImpl(makeBuilder().fetchTimeout(-1).build());
+ assertThat(cons.getSleepTime()).isEqualTo(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH);
+
+ // should not be zero
+ cons = new FetchingBusConsumerImpl(makeBuilder().fetchTimeout(0).build());
+ assertThat(cons.getSleepTime()).isEqualTo(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH);
+
+ // should not be too large
+ cons = new FetchingBusConsumerImpl(
+ makeBuilder().fetchTimeout(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH + 100).build());
+ assertThat(cons.getSleepTime()).isEqualTo(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH);
+
+ // should not be what was specified
+ cons = new FetchingBusConsumerImpl(makeBuilder().fetchTimeout(100).build());
+ assertThat(cons.getSleepTime()).isEqualTo(100);
+ }
+
+ @Test
+ public void testFetchingBusConsumerSleepAfterFetchFailure() throws InterruptedException {
+
+ var cons = new FetchingBusConsumerImpl(makeBuilder().fetchTimeout(SHORT_TIMEOUT_MILLIS).build()) {
+
+ private CountDownLatch started = new CountDownLatch(1);
+
+ @Override
+ protected void sleepAfterFetchFailure() {
+ started.countDown();
+ super.sleepAfterFetchFailure();
+ }
+ };
+
+ // full sleep
+ long tstart = System.currentTimeMillis();
+ cons.sleepAfterFetchFailure();
+ assertThat(System.currentTimeMillis() - tstart).isGreaterThanOrEqualTo(SHORT_TIMEOUT_MILLIS);
+
+ // close while sleeping - sleep should halt prematurely
+ cons.fetchTimeout = LONG_TIMEOUT_MILLIS;
+ cons.started = new CountDownLatch(1);
+ Thread thread = new Thread(cons::sleepAfterFetchFailure);
+ tstart = System.currentTimeMillis();
+ thread.start();
+ cons.started.await();
+ cons.close();
+ thread.join();
+ assertThat(System.currentTimeMillis() - tstart).isLessThan(LONG_TIMEOUT_MILLIS);
+
+ // interrupt while sleeping - sleep should halt prematurely
+ cons.fetchTimeout = LONG_TIMEOUT_MILLIS;
+ cons.started = new CountDownLatch(1);
+ thread = new Thread(cons::sleepAfterFetchFailure);
+ tstart = System.currentTimeMillis();
+ thread.start();
+ cons.started.await();
+ thread.interrupt();
+ thread.join();
+ assertThat(System.currentTimeMillis() - tstart).isLessThan(LONG_TIMEOUT_MILLIS);
}
@Test
@@ -65,7 +151,9 @@ public class BusConsumerTest extends TopicTestBase {
new CambriaConsumerWrapper(makeBuilder().apiKey(null).apiSecret(null).build());
new CambriaConsumerWrapper(makeBuilder().userName(null).build());
new CambriaConsumerWrapper(makeBuilder().password(null).build());
- new CambriaConsumerWrapper(makeBuilder().userName(null).password(null).build());
+
+ assertThatCode(() -> new CambriaConsumerWrapper(makeBuilder().userName(null).password(null).build()))
+ .doesNotThrowAnyException();
}
@Test
@@ -75,7 +163,7 @@ public class BusConsumerTest extends TopicTestBase {
when(inner.fetch()).thenReturn(lst);
CambriaConsumerWrapper cons = new CambriaConsumerWrapper(builder.build());
- Whitebox.setInternalState(cons, "consumer", inner);
+ ReflectionTestUtils.setField(cons, "consumer", inner);
assertEquals(lst, IteratorUtils.toList(cons.fetch().iterator()));
@@ -97,21 +185,7 @@ public class BusConsumerTest extends TopicTestBase {
@Test
public void testCambriaConsumerWrapperClose() {
CambriaConsumerWrapper cons = new CambriaConsumerWrapper(builder.build());
-
- // set filter several times to cause different branches of close() to be executed
- for (int count = 0; count < 3; ++count) {
- cons.close();
- cons.setFilter("close=" + count);
- }
- }
-
- @Test
- public void testCambriaConsumerWrapperSetFilter() {
- // set filter several times to cause different branches to be executed
- CambriaConsumerWrapper cons = new CambriaConsumerWrapper(builder.build());
- for (int count = 0; count < 3; ++count) {
- cons.setFilter("set-filter=" + count);
- }
+ assertThatCode(cons::close).doesNotThrowAnyException();
}
@Test
@@ -120,118 +194,139 @@ public class BusConsumerTest extends TopicTestBase {
}
@Test
- public void testDmaapConsumerWrapper() throws Exception {
+ public void testKafkaConsumerWrapper() {
// verify that different wrappers can be built
- new DmaapAafConsumerWrapper(makeBuilder().build());
+ assertThatCode(() -> new KafkaConsumerWrapper(makeKafkaBuilder().build())).doesNotThrowAnyException();
}
@Test(expected = IllegalArgumentException.class)
- public void testDmaapConsumerWrapper_InvalidTopic() throws Exception {
- new DmaapAafConsumerWrapper(makeBuilder().topic(null).build());
+ public void testKafkaConsumerWrapper_InvalidTopic() {
+ new KafkaConsumerWrapper(makeBuilder().topic(null).build());
}
@Test
- public void testDmaapConsumerWrapperFetch() throws Exception {
- DmaapAafConsumerWrapper dmaap = new DmaapAafConsumerWrapper(makeBuilder().build());
- MRConsumerImpl cons = mock(MRConsumerImpl.class);
-
- dmaap.fetchTimeout = 5;
- dmaap.consumer = cons;
+ public void testKafkaConsumerWrapperFetch() {
+
+ //Setup Properties for consumer
+ Properties kafkaProps = new Properties();
+ kafkaProps.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
+ kafkaProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "test");
+ kafkaProps.setProperty("enable.auto.commit", "true");
+ kafkaProps.setProperty("auto.commit.interval.ms", "1000");
+ kafkaProps.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
+ "org.apache.kafka.common.serialization.StringDeserializer");
+ kafkaProps.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
+ "org.apache.kafka.common.serialization.StringDeserializer");
+ kafkaProps.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+ kafkaProps.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
+
+ KafkaConsumerWrapper kafka = new KafkaConsumerWrapper(makeKafkaBuilder().build());
+ KafkaConsumer<String, String> consumer = new KafkaConsumer<>(kafkaProps);
+ kafka.consumer = consumer;
+
+ assertThrows(java.lang.IllegalStateException.class, () -> kafka.fetch().iterator().hasNext());
+ consumer.close();
+ }
- // null return
- when(cons.fetchWithReturnConsumerResponse()).thenReturn(null);
- assertFalse(dmaap.fetch().iterator().hasNext());
+ @Test
+ public void testFetchNoMessages() throws IOException {
+ KafkaConsumerWrapper kafkaConsumerWrapper = new KafkaConsumerWrapper(makeKafkaBuilder().build());
+ kafkaConsumerWrapper.consumer = mockedKafkaConsumer;
- // with messages, 200
- List<String> lst = Arrays.asList(MY_MESSAGE, MY_MESSAGE2);
- MRConsumerResponse resp = new MRConsumerResponse();
- resp.setResponseCode("200");
- resp.setActualMessages(lst);
- when(cons.fetchWithReturnConsumerResponse()).thenReturn(resp);
+ when(mockedKafkaConsumer.poll(any())).thenReturn(new ConsumerRecords<>(Collections.emptyMap()));
- assertEquals(lst, IteratorUtils.toList(dmaap.fetch().iterator()));
+ Iterable<String> result = kafkaConsumerWrapper.fetch();
- // null messages
- resp.setActualMessages(null);
- when(cons.fetchWithReturnConsumerResponse()).thenReturn(resp);
+ verify(mockedKafkaConsumer, times(1)).poll(any());
- assertFalse(dmaap.fetch().iterator().hasNext());
+ assertThat(result != null);
- // with messages, NOT 200
- resp.setResponseCode("400");
- resp.setActualMessages(lst);
- when(cons.fetchWithReturnConsumerResponse()).thenReturn(resp);
+ assertThat(!result.iterator().hasNext());
- assertEquals(lst, IteratorUtils.toList(dmaap.fetch().iterator()));
+ mockedKafkaConsumer.close();
}
@Test
- public void testDmaapConsumerWrapperClose() throws Exception {
- new DmaapAafConsumerWrapper(makeBuilder().build()).close();
- }
+ public void testFetchWithMessages() {
+ // Setup
+ KafkaConsumerWrapper kafkaConsumerWrapper = new KafkaConsumerWrapper(makeKafkaBuilder().build());
+ kafkaConsumerWrapper.consumer = mockedKafkaConsumer;
- @Test
- public void testDmaapConsumerWrapperToString() throws Exception {
- assertNotNull(new DmaapConsumerWrapper(makeBuilder().build()) {}.toString());
- }
+ ConsumerRecord<String, String> record = new ConsumerRecord<>("my-effective-topic", 0, 0, "key", "value");
+ Map<TopicPartition, List<ConsumerRecord<String, String>>> recordsMap = new HashMap<>();
+ recordsMap.put(new TopicPartition("my-effective-topic", 0), Collections.singletonList(record));
+ ConsumerRecords<String, String> consumerRecords = new ConsumerRecords<>(recordsMap);
- @Test
- public void testDmaapAafConsumerWrapper() throws Exception {
- // verify that different wrappers can be built
- new DmaapAafConsumerWrapper(makeBuilder().useHttps(true).build());
- new DmaapAafConsumerWrapper(makeBuilder().useHttps(false).build());
- }
+ when(mockedKafkaConsumer.poll(any())).thenReturn(consumerRecords);
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapAafConsumerWrapper_InvalidServers() throws Exception {
- /*
- * Unfortunately, the MR code intercepts this and throws an exception before the
- * wrapper gets a chance to check it, thus this test does not improve the coverage
- * for the constructor.
- */
- new DmaapAafConsumerWrapper(makeBuilder().servers(Collections.emptyList()).build());
- }
+ Iterable<String> result = kafkaConsumerWrapper.fetch();
- @Test
- public void testDmaapAafConsumerWrapperToString() throws Exception {
- assertNotNull(new DmaapAafConsumerWrapper(makeBuilder().build()).toString());
+ verify(mockedKafkaConsumer, times(1)).poll(any());
+
+ verify(mockedKafkaConsumer, times(1)).commitSync(any(Map.class));
+
+ assertThat(result != null);
+
+ assertThat(result.iterator().hasNext());
+
+ assertThat(result.iterator().next().equals("value"));
+
+ mockedKafkaConsumer.close();
}
@Test
- public void testDmaapDmeConsumerWrapper() throws Exception {
- // verify that different wrappers can be built
- new DmaapDmeConsumerWrapper(makeBuilder().build());
- new DmaapDmeConsumerWrapper(makeBuilder().useHttps(true).build());
- new DmaapDmeConsumerWrapper(makeBuilder().useHttps(false).build());
- new DmaapDmeConsumerWrapper(makeBuilder().additionalProps(null).build());
+ public void testFetchWithMessagesAndTraceparent() {
+ // Setup
+ KafkaConsumerWrapper kafkaConsumerWrapper = new KafkaConsumerWrapper(makeKafkaBuilder().build());
+ kafkaConsumerWrapper.consumer = mockedKafkaConsumer;
- addProps.put(ROUTE_PROP, MY_ROUTE);
- new DmaapDmeConsumerWrapper(makeBuilder().build());
- new DmaapDmeConsumerWrapper(makeBuilder().partner(null).build());
- }
+ ConsumerRecord<String, String> record = new ConsumerRecord<>("my-effective-topic", 0, 0, "key", "value");
+ record.headers().add(
+ "traceparent",
+ "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01".getBytes(StandardCharsets.UTF_8)
+ );
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmeConsumerWrapper_InvalidEnvironment() throws Exception {
- new DmaapDmeConsumerWrapper(makeBuilder().environment(null).build());
- }
+ Map<TopicPartition, List<ConsumerRecord<String, String>>> recordsMap = new HashMap<>();
+ recordsMap.put(new TopicPartition("my-effective-topic", 0), Collections.singletonList(record));
+ ConsumerRecords<String, String> consumerRecords = new ConsumerRecords<>(recordsMap);
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmeConsumerWrapper_InvalidAft() throws Exception {
- new DmaapDmeConsumerWrapper(makeBuilder().aftEnvironment(null).build());
+ when(mockedKafkaConsumer.poll(any())).thenReturn(consumerRecords);
+
+ Iterable<String> result = kafkaConsumerWrapper.fetch();
+
+ verify(mockedKafkaConsumer, times(1)).poll(any());
+
+ verify(mockedKafkaConsumer, times(1)).commitSync(any(Map.class));
+
+ assertThat(result != null);
+
+ assertThat(result.iterator().hasNext());
+
+ assertThat(result.iterator().next().equals("value"));
+
+ mockedKafkaConsumer.close();
}
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmeConsumerWrapper_InvalidLat() throws Exception {
- new DmaapDmeConsumerWrapper(makeBuilder().latitude(null).build());
+
+ @Test
+ public void testKafkaConsumerWrapperClose() {
+ assertThatCode(() -> new KafkaConsumerWrapper(makeKafkaBuilder().build()).close()).doesNotThrowAnyException();
}
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmeConsumerWrapper_InvalidLong() throws Exception {
- new DmaapDmeConsumerWrapper(makeBuilder().longitude(null).build());
+ @Test
+ public void testKafkaConsumerWrapperToString() {
+ assertNotNull(new KafkaConsumerWrapper(makeKafkaBuilder().build()) {}.toString());
}
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmeConsumerWrapper_InvalidPartner() throws Exception {
- new DmaapDmeConsumerWrapper(makeBuilder().partner(null).build());
+ private static class FetchingBusConsumerImpl extends FetchingBusConsumer {
+
+ protected FetchingBusConsumerImpl(BusTopicParams busTopicParams) {
+ super(busTopicParams);
+ }
+
+ @Override
+ public Iterable<String> fetch() {
+ return null;
+ }
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java
index 5a933e9b..66029b61 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java
@@ -3,6 +3,7 @@
* policy-endpoints
* ================================================================================
* 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.
@@ -20,10 +21,9 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -32,18 +32,11 @@ import static org.mockito.Mockito.when;
import com.att.nsa.cambria.client.CambriaBatchingPublisher;
import java.io.IOException;
-import java.util.Collections;
-import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
-import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher;
-import org.onap.dmaap.mr.client.response.MRPublisherResponse;
-import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.CambriaPublisherWrapper;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.DmaapAafPublisherWrapper;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.DmaapDmePublisherWrapper;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.DmaapPublisherWrapper;
+
public class BusPublisherTest extends TopicTestBase {
@@ -66,7 +59,8 @@ public class BusPublisherTest extends TopicTestBase {
new CambriaPublisherWrapper(makeBuilder().apiKey(null).apiSecret(null).build());
new CambriaPublisherWrapper(makeBuilder().userName(null).build());
new CambriaPublisherWrapper(makeBuilder().password(null).build());
- new CambriaPublisherWrapper(makeBuilder().userName(null).password(null).build());
+ assertThatCode(() -> new CambriaPublisherWrapper(makeBuilder().userName(null).password(null).build()))
+ .doesNotThrowAnyException();
}
@Test
@@ -103,116 +97,4 @@ public class BusPublisherTest extends TopicTestBase {
doThrow(new RuntimeException(EXPECTED)).when(pub).close();
cambria.close();
}
-
- @Test
- public void testDmaapPublisherWrapper() {
- // verify with different constructor arguments
- new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, true);
- new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, false);
- new DmaapPublisherWrapper(ProtocolTypeConstants.DME2, servers, MY_TOPIC, MY_USERNAME, MY_PASS, true) {};
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapPublisherWrapper_InvalidTopic() {
- new DmaapPublisherWrapper(ProtocolTypeConstants.DME2, servers, "", MY_USERNAME, MY_PASS, true) {};
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapPublisherWrapper_Aaf_NullServers() {
- new DmaapAafPublisherWrapper(null, MY_TOPIC, MY_USERNAME, MY_PASS, true);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapPublisherWrapper_Aaf_NoServers() {
- new DmaapAafPublisherWrapper(Collections.emptyList(), MY_TOPIC, MY_USERNAME, MY_PASS, true);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapPublisherWrapper_InvalidProtocol() {
- new DmaapPublisherWrapper(ProtocolTypeConstants.HTTPNOAUTH, servers, MY_TOPIC, MY_USERNAME, MY_PASS, true) {};
- }
-
- @Test
- public void testDmaapPublisherWrapperClose() throws Exception {
- MRSimplerBatchPublisher pub = mock(MRSimplerBatchPublisher.class);
- DmaapPublisherWrapper dmaap = new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, true);
- dmaap.publisher = pub;
-
- dmaap.close();
- verify(pub).close(anyLong(), any(TimeUnit.class));
-
- // close, but with exception from publisher
- doThrow(new IOException(EXPECTED)).when(pub).close(anyLong(), any(TimeUnit.class));
- dmaap.close();
- }
-
- @Test
- public void testDmaapPublisherWrapperSend() {
- MRSimplerBatchPublisher pub = mock(MRSimplerBatchPublisher.class);
- DmaapPublisherWrapper dmaap = new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, true);
- dmaap.publisher = pub;
-
- // null response
- assertTrue(dmaap.send(MY_PARTITION, MY_MESSAGE));
- verify(pub).setPubResponse(any(MRPublisherResponse.class));
- verify(pub).send(MY_PARTITION, MY_MESSAGE);
-
- // with response
- pub = mock(MRSimplerBatchPublisher.class);
- dmaap.publisher = pub;
-
- MRPublisherResponse resp = new MRPublisherResponse();
- when(pub.sendBatchWithResponse()).thenReturn(resp);
- assertTrue(dmaap.send(MY_PARTITION, MY_MESSAGE));
- verify(pub).setPubResponse(any(MRPublisherResponse.class));
- verify(pub).send(MY_PARTITION, MY_MESSAGE);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapPublisherWrapperSend_NullMessage() {
- MRSimplerBatchPublisher pub = mock(MRSimplerBatchPublisher.class);
- DmaapPublisherWrapper dmaap = new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, true);
- dmaap.publisher = pub;
-
- dmaap.send(MY_PARTITION, null);
- }
-
- @Test
- public void testDmaapDmePublisherWrapper() {
- // verify with different parameters
- new DmaapDmePublisherWrapper(makeBuilder().build());
- new DmaapDmePublisherWrapper(makeBuilder().additionalProps(null).build());
-
- addProps.put(ROUTE_PROP, MY_ROUTE);
- new DmaapDmePublisherWrapper(makeBuilder().build());
- new DmaapDmePublisherWrapper(makeBuilder().partner(null).build());
-
- addProps.put("null-value", null);
- new DmaapDmePublisherWrapper(makeBuilder().build());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmePublisherWrapper_InvalidEnv() {
- new DmaapDmePublisherWrapper(makeBuilder().environment(null).build());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmePublisherWrapper_InvalidAft() {
- new DmaapDmePublisherWrapper(makeBuilder().aftEnvironment(null).build());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmePublisherWrapper_InvalidLat() {
- new DmaapDmePublisherWrapper(makeBuilder().latitude(null).build());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmePublisherWrapper_InvalidLong() {
- new DmaapDmePublisherWrapper(makeBuilder().longitude(null).build());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testDmaapDmePublisherWrapper_InvalidPartner() {
- new DmaapDmePublisherWrapper(makeBuilder().partner(null).build());
- }
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java
index 01028045..0a2a5d34 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
@@ -53,7 +54,7 @@ public class BusTopicBaseTest extends TopicTestBase {
@Test
public void testSerialize() {
- new GsonTestUtils().compareGson(base, BusTopicBaseTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(base, BusTopicBaseTest.class)).doesNotThrowAnyException();
}
@Test
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java
index c00f2b56..93e5067e 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -41,7 +41,7 @@ public class BusTopicParamsTest extends TopicTestBase {
}
@Test
- public void test() {
+ public void testGetters() {
BusTopicParams params = makeBuilder().build();
assertEquals(addProps, params.getAdditionalProps());
@@ -69,11 +69,19 @@ public class BusTopicParamsTest extends TopicTestBase {
assertEquals(MY_EFFECTIVE_TOPIC, params.getEffectiveTopic());
assertEquals(true, params.isUseHttps());
assertEquals(MY_USERNAME, params.getUserName());
+ }
+ @Test
+ public void testBooleanGetters() {
// ensure that booleans are independent of each other
testBoolean("true:false:false", (bldr, flag) -> bldr.allowSelfSignedCerts(flag));
testBoolean("false:true:false", (bldr, flag) -> bldr.managed(flag));
testBoolean("false:false:true", (bldr, flag) -> bldr.useHttps(flag));
+ }
+
+ @Test
+ public void testValidators() {
+ BusTopicParams params = makeBuilder().build();
// test validity methods
assertTrue(params.isAdditionalPropsValid());
@@ -94,8 +102,10 @@ public class BusTopicParamsTest extends TopicTestBase {
assertFalse(params.isServersInvalid());
assertFalse(params.isTopicInvalid());
assertTrue(params.isUserNameValid());
+ }
- // test inverted validity
+ @Test
+ public void testInvertedValidators() {
assertFalse(makeBuilder().additionalProps(null).build().isAdditionalPropsValid());
assertTrue(makeBuilder().aftEnvironment("").build().isAftEnvironmentInvalid());
assertFalse(makeBuilder().apiKey("").build().isApiKeyValid());
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java
index 634ee762..e6eec799 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -61,7 +62,8 @@ public class InlineBusTopicSinkTest extends TopicTestBase {
@Test
public void testSerialize() {
- new GsonTestUtils().compareGson(sink, InlineBusTopicSinkTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(sink, InlineBusTopicSinkTest.class))
+ .doesNotThrowAnyException();
}
@Test
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSinkTest.java
index d9bc990b..643025c2 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSinkTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2022-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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -28,10 +29,9 @@ import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase;
-import org.onap.policy.common.utils.gson.GsonTestUtils;
-public class InlineDmaapTopicSinkTest extends TopicTestBase {
- private InlineDmaapTopicSink sink;
+public class InlineKafkaTopicSinkTest extends TopicTestBase {
+ private InlineKafkaTopicSink sink;
/**
* Creates the object to be tested.
@@ -41,7 +41,7 @@ public class InlineDmaapTopicSinkTest extends TopicTestBase {
public void setUp() {
super.setUp();
- sink = new InlineDmaapTopicSink(makeBuilder().build());
+ sink = new InlineKafkaTopicSink(makeKafkaBuilder().build());
}
@After
@@ -50,32 +50,21 @@ public class InlineDmaapTopicSinkTest extends TopicTestBase {
}
@Test
- public void testSerialize() {
- new GsonTestUtils().compareGson(sink, InlineDmaapTopicSinkTest.class);
- }
-
- @Test
public void testToString() {
- assertTrue(sink.toString().startsWith("InlineDmaapTopicSink ["));
+ assertTrue(sink.toString().startsWith("InlineKafkaTopicSink ["));
}
@Test
public void testInit() {
// nothing null
- sink = new InlineDmaapTopicSink(makeBuilder().build());
+ sink = new InlineKafkaTopicSink(makeKafkaBuilder().build());
sink.init();
- sink.shutdown();
-
- // no DME2 info
- sink = new InlineDmaapTopicSink(makeBuilder().environment(null).aftEnvironment(null).latitude(null)
- .longitude(null).partner(null).build());
- sink.init();
- sink.shutdown();
+ assertThatCode(() -> sink.shutdown()).doesNotThrowAnyException();
}
@Test
public void testGetTopicCommInfrastructure() {
- assertEquals(CommInfrastructure.DMAAP, sink.getTopicCommInfrastructure());
+ assertEquals(CommInfrastructure.KAFKA, sink.getTopicCommInfrastructure());
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java
index a45504f2..674f379f 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -51,7 +52,8 @@ public class InlineUebTopicSinkTest extends TopicTestBase {
@Test
public void testSerialize() {
- new GsonTestUtils().compareGson(sink, InlineUebTopicSinkTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(sink, InlineUebTopicSinkTest.class))
+ .doesNotThrowAnyException();
}
@Test
@@ -61,7 +63,7 @@ public class InlineUebTopicSinkTest extends TopicTestBase {
@Test
public void testInit() {
- sink.init();
+ assertThatCode(() -> sink.init()).doesNotThrowAnyException();
}
@Test
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java
index 16d74df2..dbdd8813 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,8 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -42,8 +44,8 @@ import org.mockito.stubbing.Answer;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.TopicListener;
import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase;
-import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.FilterableBusConsumer;
import org.onap.policy.common.utils.gson.GsonTestUtils;
+import org.onap.policy.common.utils.network.NetworkUtil;
public class SingleThreadedBusTopicSourceTest extends TopicTestBase {
private Thread thread;
@@ -72,7 +74,8 @@ public class SingleThreadedBusTopicSourceTest extends TopicTestBase {
@Test
public void testSerialize() {
- new GsonTestUtils().compareGson(source, SingleThreadedBusTopicSourceTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(source, SingleThreadedBusTopicSourceTest.class))
+ .doesNotThrowAnyException();
}
@Test
@@ -159,11 +162,30 @@ public class SingleThreadedBusTopicSourceTest extends TopicTestBase {
@Test
public void testSingleThreadedBusTopicSource() {
+ // Note: if the value contains "-", it's probably a UUID
+
// verify that different wrappers can be built
- new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerGroup(null).build());
- new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerInstance(null).build());
- new SingleThreadedBusTopicSourceImpl(makeBuilder().fetchTimeout(-1).build());
- new SingleThreadedBusTopicSourceImpl(makeBuilder().fetchLimit(-1).build());
+ source = new SingleThreadedBusTopicSourceImpl(makeBuilder().build());
+ assertThat(source.getConsumerGroup()).isEqualTo(MY_CONS_GROUP);
+ assertThat(source.getConsumerInstance()).isEqualTo(MY_CONS_INST);
+
+ // group is null => group is UUID, instance is as provided
+ source = new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerGroup(null).build());
+ assertThat(source.getConsumerGroup()).contains("-").isNotEqualTo(NetworkUtil.getHostname());
+ assertThat(source.getConsumerInstance()).isEqualTo(MY_CONS_INST);
+
+ // instance is null => group is as provided, instance is UUID
+ source = new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerInstance(null).build());
+ assertThat(source.getConsumerGroup()).isEqualTo(MY_CONS_GROUP);
+ assertThat(source.getConsumerInstance()).contains("-").isNotEqualTo(NetworkUtil.getHostname());
+
+ // group & instance are null => group is UUID, instance is hostname
+ source = new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerGroup(null).consumerInstance(null).build());
+ assertThat(source.getConsumerGroup()).contains("-").isNotEqualTo(NetworkUtil.getHostname());
+ assertThat(source.getConsumerInstance()).isEqualTo(NetworkUtil.getHostname());
+
+ assertThatCode(() -> new SingleThreadedBusTopicSourceImpl(
+ makeBuilder().fetchLimit(-1).fetchTimeout(-1).build())).doesNotThrowAnyException();
}
@Test
@@ -284,22 +306,6 @@ public class SingleThreadedBusTopicSourceTest extends TopicTestBase {
}
@Test
- public void testSetFilter() {
- FilterableBusConsumer filt = mock(FilterableBusConsumer.class);
- cons = filt;
-
- source.start();
- source.setFilter("my-filter");
- verify(filt).setFilter("my-filter");
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void testSetFilter_Unsupported() {
- source.start();
- source.setFilter("unsupported-filter");
- }
-
- @Test
public void testGetConsumerGroup() {
assertEquals(MY_CONS_GROUP, source.getConsumerGroup());
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSourceTest.java
index b7faf161..6b63c9f4 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSourceTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -20,10 +20,10 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import java.net.MalformedURLException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -31,9 +31,8 @@ import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase;
import org.onap.policy.common.utils.gson.GsonTestUtils;
-public class SingleThreadedDmaapTopicSourceTest extends TopicTestBase {
- private static final String SOURCE_NAME = "SingleThreadedDmaapTopicSource [";
- private SingleThreadedDmaapTopicSource source;
+public class SingleThreadedKafkaTopicSourceTest extends TopicTestBase {
+ private SingleThreadedKafkaTopicSource source;
/**
* Creates the object to be tested.
@@ -43,7 +42,7 @@ public class SingleThreadedDmaapTopicSourceTest extends TopicTestBase {
public void setUp() {
super.setUp();
- source = new SingleThreadedDmaapTopicSource(makeBuilder().build());
+ source = new SingleThreadedKafkaTopicSource(makeKafkaBuilder().build());
}
@After
@@ -51,48 +50,20 @@ public class SingleThreadedDmaapTopicSourceTest extends TopicTestBase {
source.shutdown();
}
- @Test
public void testSerialize() {
- new GsonTestUtils().compareGson(source, SingleThreadedDmaapTopicSourceTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(source, SingleThreadedKafkaTopicSourceTest.class))
+ .doesNotThrowAnyException();
}
@Test
public void testToString() {
- assertTrue(source.toString().startsWith(SOURCE_NAME));
- source.shutdown();
-
- // try with null password
- source = new SingleThreadedDmaapTopicSource(makeBuilder().password(null).build());
- assertTrue(source.toString().startsWith(SOURCE_NAME));
- source.shutdown();
-
- // try with empty password
- source = new SingleThreadedDmaapTopicSource(makeBuilder().password("").build());
- assertTrue(source.toString().startsWith(SOURCE_NAME));
+ assertTrue(source.toString().startsWith("SingleThreadedKafkaTopicSource ["));
source.shutdown();
}
@Test
- public void testInit() {
- // verify with different parameters
- new SingleThreadedDmaapTopicSource(makeBuilder().userName(null).build()).shutdown();
- new SingleThreadedDmaapTopicSource(makeBuilder().environment(null).aftEnvironment(null).latitude(null)
- .longitude(null).partner(null).build()).shutdown();
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testSingleThreadedDmaapTopicSource_Ex() {
- new SingleThreadedDmaapTopicSource(makeBuilder().build()) {
- @Override
- public void init() throws MalformedURLException {
- throw new MalformedURLException(EXPECTED);
- }
- }.shutdown();
- }
-
- @Test
public void testGetTopicCommInfrastructure() {
- assertEquals(CommInfrastructure.DMAAP, source.getTopicCommInfrastructure());
+ assertEquals(CommInfrastructure.KAFKA, source.getTopicCommInfrastructure());
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.java
index 2ff353b8..6536d0e8 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -51,7 +52,8 @@ public class SingleThreadedUebTopicSourceTest extends TopicTestBase {
@Test
public void testSerialize() {
- new GsonTestUtils().compareGson(source, SingleThreadedUebTopicSourceTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(source, SingleThreadedUebTopicSourceTest.class))
+ .doesNotThrowAnyException();
}
@Test
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBaseTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBaseTest.java
index 0cf1486f..0f09b12e 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBaseTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBaseTest.java
@@ -20,6 +20,7 @@
package org.onap.policy.common.endpoints.event.comm.bus.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -97,7 +98,7 @@ public class TopicBaseTest extends TopicTestBase {
@Test
public void testSerialize() {
- new GsonTestUtils().compareGson(base, TopicBaseTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(base, TopicBaseTest.class)).doesNotThrowAnyException();
}
@Test
@@ -193,9 +194,15 @@ public class TopicBaseTest extends TopicTestBase {
assertTrue(base.unlock());
assertEquals(1, base.startCount);
assertEquals(1, base.stopCount);
+ }
+
+ /**
+ * Tests lock/unlock when the stop/start methods return false.
+ */
+ @Test
+ public void testLock_testUnlock_FalseReturns() {
// lock, but stop returns false
- base = new TopicBaseImpl(servers, MY_TOPIC);
base.stopReturn = false;
assertFalse(base.lock());
assertTrue(base.isLocked());
@@ -206,9 +213,15 @@ public class TopicBaseTest extends TopicTestBase {
assertFalse(base.unlock());
assertFalse(base.isLocked());
assertTrue(base.unlock());
+ }
+
+ /**
+ * Tests lock/unlock when the start method throws an exception.
+ */
+ @Test
+ public void testLock_testUnlock_Exception() {
// lock & re-lock, but start throws an exception
- base = new TopicBaseImpl(servers, MY_TOPIC);
base.startEx = true;
assertTrue(base.lock());
assertFalse(base.unlock());
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientTest.java
new file mode 100644
index 00000000..2605c14b
--- /dev/null
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientTest.java
@@ -0,0 +1,452 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.endpoints.event.comm.client;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Arrays;
+import java.util.Properties;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
+import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
+import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
+import org.onap.policy.common.endpoints.event.comm.TopicListener;
+import org.onap.policy.common.endpoints.event.comm.TopicSink;
+import org.onap.policy.common.endpoints.event.comm.TopicSource;
+import org.onap.policy.common.utils.coder.Coder;
+import org.onap.policy.common.utils.coder.CoderException;
+import org.onap.policy.common.utils.coder.StandardCoder;
+
+@RunWith(MockitoJUnitRunner.class)
+public class BidirectionalTopicClientTest {
+ private static final Coder coder = new StandardCoder();
+ private static final long MAX_WAIT_MS = 5000;
+ private static final long SHORT_WAIT_MS = 1;
+ private static final String SINK_TOPIC = "my-sink-topic";
+ private static final String SOURCE_TOPIC = "my-source-topic";
+ private static final String MY_TEXT = "my-text";
+
+ private static final CommInfrastructure SINK_INFRA = CommInfrastructure.UEB;
+ private static final CommInfrastructure SOURCE_INFRA = CommInfrastructure.NOOP;
+
+ @Mock
+ private TopicSink sink;
+ @Mock
+ private TopicSource source;
+ @Mock
+ private TopicEndpoint endpoint;
+ @Mock
+ private TopicListener listener;
+
+ private MyMessage theMessage;
+
+ private BidirectionalTopicClient client;
+ private Context context;
+
+ /**
+ * Configures the endpoints.
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ Properties props = new Properties();
+ props.setProperty("noop.sink.topics", SINK_TOPIC);
+ props.setProperty("noop.source.topics", SOURCE_TOPIC);
+
+ // clear all topics and then configure one sink and one source
+ TopicEndpointManager.getManager().shutdown();
+ TopicEndpointManager.getManager().addTopicSinks(props);
+ TopicEndpointManager.getManager().addTopicSources(props);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ // clear all topics after the tests
+ TopicEndpointManager.getManager().shutdown();
+ }
+
+ /**
+ * Creates mocks and an initial client object.
+ */
+ @Before
+ public void setUp() throws Exception {
+ when(sink.send(anyString())).thenReturn(true);
+ when(sink.getTopicCommInfrastructure()).thenReturn(SINK_INFRA);
+
+ when(source.offer(anyString())).thenReturn(true);
+ when(source.getTopicCommInfrastructure()).thenReturn(SOURCE_INFRA);
+
+ when(endpoint.getTopicSinks(anyString())).thenReturn(Arrays.asList());
+ when(endpoint.getTopicSinks(SINK_TOPIC)).thenReturn(Arrays.asList(sink));
+
+ when(endpoint.getTopicSources(any())).thenReturn(Arrays.asList());
+ when(endpoint.getTopicSources(Arrays.asList(SOURCE_TOPIC))).thenReturn(Arrays.asList(source));
+
+ theMessage = new MyMessage(MY_TEXT);
+
+ client = new BidirectionalTopicClient2(SINK_TOPIC, SOURCE_TOPIC);
+
+ context = new Context();
+ }
+
+ @After
+ public void tearDown() {
+ context.stop();
+ }
+
+ @Test
+ public void testBidirectionalTopicClient_testGetters() {
+ assertSame(sink, client.getSink());
+ assertSame(source, client.getSource());
+ assertEquals(SINK_TOPIC, client.getSinkTopic());
+ assertEquals(SOURCE_TOPIC, client.getSourceTopic());
+ assertEquals(SINK_INFRA, client.getSinkTopicCommInfrastructure());
+ assertEquals(SOURCE_INFRA, client.getSourceTopicCommInfrastructure());
+ }
+
+ /**
+ * Tests the constructor when the sink or source cannot be found.
+ */
+ @Test
+ public void testBidirectionalTopicClientExceptions() {
+ assertThatThrownBy(() -> new BidirectionalTopicClient2("unknown-sink", SOURCE_TOPIC))
+ .isInstanceOf(BidirectionalTopicClientException.class)
+ .hasMessage("no sinks for topic: unknown-sink");
+
+ assertThatThrownBy(() -> new BidirectionalTopicClient2(SINK_TOPIC, "unknown-source"))
+ .isInstanceOf(BidirectionalTopicClientException.class)
+ .hasMessage("no sources for topic: unknown-source");
+
+ // too many sources
+ when(endpoint.getTopicSources(Arrays.asList(SOURCE_TOPIC))).thenReturn(Arrays.asList(source, source));
+
+ assertThatThrownBy(() -> new BidirectionalTopicClient2(SINK_TOPIC, SOURCE_TOPIC))
+ .isInstanceOf(BidirectionalTopicClientException.class)
+ .hasMessage("too many sources for topic: my-source-topic");
+ }
+
+ /**
+ * Tests the "delegate" methods.
+ */
+ @Test
+ public void testDelegates() {
+ assertTrue(client.send("hello"));
+ verify(sink).send("hello");
+
+ assertTrue(client.offer("incoming"));
+ verify(source).offer("incoming");
+
+ client.register(listener);
+ verify(source).register(listener);
+
+ client.unregister(listener);
+ verify(source).unregister(listener);
+ }
+
+ @Test
+ public void testGetTopicEndpointManager() throws BidirectionalTopicClientException {
+ // use a real manager
+ client = new BidirectionalTopicClient(SINK_TOPIC, SOURCE_TOPIC);
+ assertNotNull(client.getTopicEndpointManager());
+
+ assertNotNull(client.getSink());
+ assertNotNull(client.getSource());
+
+ assertNotSame(sink, client.getSink());
+ assertNotSame(source, client.getSource());
+ }
+
+ @Test
+ public void testAwaitReceipt() throws Exception {
+ context.start(theMessage);
+ assertThat(context.awaitSend(1)).isTrue();
+
+ verify(source).register(any());
+ verify(sink, atLeast(1)).send(any());
+ assertThat(context.checker.isReady()).isFalse();
+
+ inject(theMessage);
+
+ verifyReceipt();
+ }
+
+ @Test
+ public void testAwaitReceipt_AlreadyDone() throws Exception {
+ context.start(theMessage);
+ assertThat(context.awaitSend(1)).isTrue();
+
+ inject(theMessage);
+
+ verifyReceipt();
+
+ // calling again should result in "true" again, without injecting message
+ context.start(theMessage);
+ verifyReceipt();
+ }
+
+ @Test
+ public void testAwaitReceipt_MessageDoesNotMatch() throws Exception {
+ context.start(theMessage);
+ assertThat(context.awaitSend(1)).isTrue();
+
+ // non-matching message
+ inject("{}");
+
+ // wait for a few more calls to "send" and then inject a matching message
+ assertThat(context.awaitSend(3)).isTrue();
+ inject(theMessage);
+
+ verifyReceipt();
+ }
+
+ @Test
+ public void testAwaitReceipt_DecodeFails() throws Exception {
+ context.start(theMessage);
+ assertThat(context.awaitSend(1)).isTrue();
+
+ // force a failure and inject the message
+ context.forceDecodeFailure = true;
+ inject(theMessage);
+
+ assertThat(context.awaitDecodeFailure()).isTrue();
+
+ // no more failures
+ context.forceDecodeFailure = false;
+ inject(theMessage);
+
+ verifyReceipt();
+ }
+
+ @Test
+ public void testAwaitReceipt_Interrupted() throws InterruptedException {
+ context.start(theMessage);
+ assertThat(context.awaitSend(1)).isTrue();
+
+ context.interrupt();
+
+ verifyNoReceipt();
+ }
+
+ @Test
+ public void testAwaitReceipt_MultipleLoops() throws Exception {
+ context.start(theMessage);
+
+ // wait for multiple "send" calls
+ assertThat(context.awaitSend(3)).isTrue();
+
+ inject(theMessage);
+
+ verifyReceipt();
+ }
+
+ @Test
+ public void testStop() throws InterruptedException {
+ context.start(theMessage);
+ assertThat(context.awaitSend(1)).isTrue();
+
+ context.stop();
+
+ verifyNoReceipt();
+ }
+
+ /**
+ * Verifies that awaitReceipt() returns {@code true}.
+ *
+ * @throws InterruptedException if interrupted while waiting for the thread to
+ * terminate
+ */
+ private void verifyReceipt() throws InterruptedException {
+ assertThat(context.join()).isTrue();
+ assertThat(context.result).isTrue();
+ assertThat(context.exception).isNull();
+ assertThat(context.checker.isReady()).isTrue();
+
+ verify(source).unregister(any());
+ }
+
+ /**
+ * Verifies that awaitReceipt() returns {@code false}.
+ *
+ * @throws InterruptedException if interrupted while waiting for the thread to
+ * terminate
+ */
+ private void verifyNoReceipt() throws InterruptedException {
+ assertThat(context.join()).isTrue();
+ assertThat(context.result).isFalse();
+ assertThat(context.exception).isNull();
+ assertThat(context.checker.isReady()).isFalse();
+
+ verify(source).unregister(any());
+ }
+
+ /**
+ * Injects a message into the source topic.
+ *
+ * @param message message to be injected
+ * @throws CoderException if the message cannot be encoded
+ */
+ private void inject(MyMessage message) throws CoderException {
+ inject(coder.encode(message));
+ }
+
+ /**
+ * Injects a message into the source topic.
+ *
+ * @param message message to be injected
+ */
+ private void inject(String message) {
+ ArgumentCaptor<TopicListener> cap = ArgumentCaptor.forClass(TopicListener.class);
+ verify(source).register(cap.capture());
+
+ cap.getValue().onTopicEvent(SOURCE_INFRA, SOURCE_TOPIC, message);
+ }
+
+
+ /**
+ * BidirectionalTopicClient with some overrides.
+ */
+ private class BidirectionalTopicClient2 extends BidirectionalTopicClient {
+
+ public BidirectionalTopicClient2(String sinkTopic, String sourceTopic)
+ throws BidirectionalTopicClientException {
+ super(sinkTopic, sourceTopic);
+ }
+
+ @Override
+ protected TopicEndpoint getTopicEndpointManager() {
+ return endpoint;
+ }
+ }
+
+ private class Context {
+ private Thread thread;
+ private boolean result;
+ private Exception exception;
+ private boolean forceDecodeFailure;
+
+ // released every time the checker publishes a message
+ private final Semaphore sendSem = new Semaphore(0);
+
+ // released every time a message-decode fails
+ private final Semaphore decodeFailedSem = new Semaphore(0);
+
+ private final BidirectionalTopicClient2 checker;
+
+ public Context() throws BidirectionalTopicClientException {
+
+ checker = new BidirectionalTopicClient2(SINK_TOPIC, SOURCE_TOPIC) {
+
+ @Override
+ public boolean send(String messageText) {
+ boolean result = super.send(messageText);
+ sendSem.release();
+ return result;
+ }
+
+ @Override
+ protected <T> T decode(String msg, Class<? extends T> clazz) throws CoderException {
+ if (forceDecodeFailure) {
+ throw new CoderException("expected exception");
+ }
+
+ return super.decode(msg, clazz);
+ }
+
+ @Override
+ protected void decodeFailed() {
+ super.decodeFailed();
+ decodeFailedSem.release();
+ }
+ };
+ }
+
+ /**
+ * Starts the thread.
+ *
+ * @param message message to be sent to the sink topic
+ */
+ public void start(MyMessage message) {
+ thread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ result = checker.awaitReady(message, SHORT_WAIT_MS);
+ } catch (Exception e) {
+ exception = e;
+ }
+ }
+ };
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ public void stop() {
+ checker.stopWaiting();
+ }
+
+ public boolean join() throws InterruptedException {
+ thread.join(MAX_WAIT_MS);
+ return !thread.isAlive();
+ }
+
+ public void interrupt() {
+ thread.interrupt();
+ }
+
+ public boolean awaitSend(int npermits) throws InterruptedException {
+ return sendSem.tryAcquire(npermits, MAX_WAIT_MS, TimeUnit.MILLISECONDS);
+ }
+
+ public boolean awaitDecodeFailure() throws InterruptedException {
+ return decodeFailedSem.tryAcquire(MAX_WAIT_MS, TimeUnit.MILLISECONDS);
+ }
+ }
+
+ @Data
+ @NoArgsConstructor
+ @AllArgsConstructor
+ public static class MyMessage {
+ private String text;
+ }
+}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientExceptionTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicClientExceptionTest.java
index c0814703..7b64a20f 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientExceptionTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicClientExceptionTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP PAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,10 +26,11 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class TopicSinkClientExceptionTest {
+public class TopicClientExceptionTest {
@Test
public void test() {
assertEquals(5, new ExceptionsTester().test(TopicSinkClientException.class));
+ assertEquals(5, new ExceptionsTester().test(BidirectionalTopicClientException.class));
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java
index 2aaf1367..11067974 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java
@@ -2,8 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright 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.
@@ -23,15 +24,23 @@ package org.onap.policy.common.endpoints.http.server.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
+import io.prometheus.client.servlet.jakarta.exporter.MetricsServlet;
+import jakarta.ws.rs.client.Entity;
+import jakarta.ws.rs.client.InvocationCallback;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
+import java.util.TreeMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import lombok.Getter;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -56,8 +65,6 @@ public class HttpClientTest {
private static final String FALSE_STRING = "false";
private static final String ALPHA123 = "alpha123";
private static final String PUT_HELLO = "PUT:hello:{myParameter=myValue}";
- private static final String DOT_GSON = "." + "GSON";
- private static final String DOT_JACKSON = "." + "JACKSON";
private static final String DOT_PDP = "." + "PDP";
private static final String DOT_PAP = "." + "PAP";
@@ -114,13 +121,11 @@ public class HttpClientTest {
/* echo server - https + basic auth */
final HttpServletServer echoServerAuth = HttpServletServerFactoryInstance.getServerFactory()
- .build("echo", true, LOCALHOST, 6667, "/", false, true);
+ .build("echo", true, LOCALHOST, 6667, false, "/", false, true);
echoServerAuth.setBasicAuthentication("x", "y", null);
echoServerAuth.addServletPackage("/*", HttpClientTest.class.getPackage().getName());
echoServerAuth.addFilterClass("/*", TestFilter.class.getName());
echoServerAuth.addFilterClass("/*", TestAuthorizationFilter.class.getName());
- echoServerAuth.addFilterClass("/*", TestAafAuthFilter.class.getName());
- echoServerAuth.addFilterClass("/*", TestAafGranularAuthFilter.class.getName());
echoServerAuth.waitedStart(5000);
if (!NetworkUtil.isTcpPortOpen(LOCALHOST, echoServerAuth.getPort(), 5, 10000L)) {
@@ -136,7 +141,6 @@ public class HttpClientTest {
HttpClientFactoryInstance.getClientFactory().destroy();
MyGsonProvider.resetSome();
- MyJacksonProvider.resetSome();
}
/**
@@ -194,6 +198,28 @@ public class HttpClientTest {
}
@Test
+ public void testHttpGetNoAuthClientAsync() throws Exception {
+ final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false,
+ 6666);
+ MyCallback callback = new MyCallback();
+ final Response response = client.get(callback, HELLO, new TreeMap<>()).get();
+
+ verifyCallback("testHttpGetNoAuthClientAsync", callback, response);
+
+ final String body = HttpClient.getBody(response, String.class);
+
+ assertEquals(200, response.getStatus());
+ assertEquals(HELLO, body);
+ }
+
+ private void verifyCallback(String testName, MyCallback callback, final Response response)
+ throws InterruptedException {
+ assertTrue(testName, callback.await());
+ assertNull(testName, callback.getThrowable());
+ assertSame(testName, response, callback.getResponse());
+ }
+
+ @Test
public void testHttpPutNoAuthClient() throws Exception {
final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666);
@@ -206,6 +232,22 @@ public class HttpClientTest {
}
@Test
+ public void testHttpPutNoAuthClientAsync() throws Exception {
+ final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666);
+
+ Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
+ MyCallback callback = new MyCallback();
+ final Response response = client.put(callback, HELLO, entity, Collections.emptyMap()).get();
+
+ verifyCallback("testHttpPutNoAuthClientAsync", callback, response);
+
+ final String body = HttpClient.getBody(response, String.class);
+
+ assertEquals(200, response.getStatus());
+ assertEquals(PUT_HELLO, body);
+ }
+
+ @Test
public void testHttpPostNoAuthClient() throws Exception {
final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false,
6666);
@@ -219,6 +261,23 @@ public class HttpClientTest {
}
@Test
+ public void testHttpPostNoAuthClientAsync() throws Exception {
+ final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false,
+ 6666);
+
+ Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
+ MyCallback callback = new MyCallback();
+ final Response response = client.post(callback, HELLO, entity, Collections.emptyMap()).get();
+
+ verifyCallback("testHttpPostNoAuthClientAsync", callback, response);
+
+ final String body = HttpClient.getBody(response, String.class);
+
+ assertEquals(200, response.getStatus());
+ assertEquals("POST:hello:{myParameter=myValue}", body);
+ }
+
+ @Test
public void testHttpDeletetNoAuthClient() throws Exception {
final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false,
6666);
@@ -231,10 +290,34 @@ public class HttpClientTest {
}
@Test
- public void testHttpGetAuthClient() throws Exception {
+ public void testHttpDeletetNoAuthClientAsync() throws Exception {
+ final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false,
+ 6666);
+
+ MyCallback callback = new MyCallback();
+ final Response response = client.delete(callback, HELLO, Collections.emptyMap()).get();
+
+ verifyCallback("testHttpDeletetNoAuthClientAsync", callback, response);
+
+ final String body = HttpClient.getBody(response, String.class);
+
+ assertEquals(200, response.getStatus());
+ assertEquals("DELETE:hello", body);
+ }
+
+ /**
+ * Perform one asynchronous test with auth client; don't need to test every method.
+ * @throws Exception if an error occurs
+ */
+ @Test
+ public void testHttpAsyncAuthClient() throws Exception {
final HttpClient client = getAuthHttpClient();
- final Response response = client.get(HELLO);
+ MyCallback callback = new MyCallback();
+ final Response response = client.get(callback, HELLO, null).get();
+
+ verifyCallback("testHttpAsyncAuthClient", callback, response);
+
final String body = HttpClient.getBody(response, String.class);
assertEquals(200, response.getStatus());
@@ -242,24 +325,19 @@ public class HttpClientTest {
}
@Test
- public void testHttpPutAuthClient() throws Exception {
+ public void testHttpGetAuthClient() throws Exception {
final HttpClient client = getAuthHttpClient();
- Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
- final Response response = client.put(HELLO, entity, Collections.emptyMap());
+ final Response response = client.get(HELLO);
final String body = HttpClient.getBody(response, String.class);
assertEquals(200, response.getStatus());
- assertEquals(PUT_HELLO, body);
+ assertEquals(HELLO, body);
}
@Test
- public void testHttpPutAuthClient_JacksonProvider() throws Exception {
- final HttpClient client = HttpClientFactoryInstance.getClientFactory()
- .build(BusTopicParams.builder().clientName(TEST_HTTP_AUTH_CLIENT).useHttps(true)
- .allowSelfSignedCerts(true).hostname(LOCALHOST).port(6667).basePath(JUNIT_ECHO)
- .userName("x").password("y").managed(true)
- .serializationProvider(MyJacksonProvider.class.getName()).build());
+ public void testHttpPutAuthClient() throws Exception {
+ final HttpClient client = getAuthHttpClient();
Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
final Response response = client.put(HELLO, entity, Collections.emptyMap());
@@ -267,10 +345,6 @@ public class HttpClientTest {
assertEquals(200, response.getStatus());
assertEquals(PUT_HELLO, body);
-
- assertTrue(MyJacksonProvider.hasWrittenSome());
-
- assertFalse(MyGsonProvider.hasWrittenSome());
}
@Test
@@ -289,8 +363,6 @@ public class HttpClientTest {
assertEquals(PUT_HELLO, body);
assertTrue(MyGsonProvider.hasWrittenSome());
-
- assertFalse(MyJacksonProvider.hasWrittenSome());
}
@Test
@@ -305,7 +377,12 @@ public class HttpClientTest {
public void testHttpAuthClientProps() throws Exception {
final Properties httpProperties = new Properties();
+ /* PAP and PDP services */
+
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, "PAP,PDP");
+
+ /* PAP server service configuration */
+
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+ PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
@@ -322,8 +399,15 @@ public class HttpClientTest {
PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+ PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX,
TestFilter.class.getName());
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+ httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+ PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+ httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+ + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_CLASS_SUFFIX, MetricsServlet.class.getName());
+ httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+ + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX,
+ "/pap/test/random/metrics");
+
+ /* PDP server service configuration */
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+ PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
@@ -337,10 +421,19 @@ public class HttpClientTest {
PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+ PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
RestMockHealthCheck.class.getName());
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+ httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+ PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+ httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+ + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "true");
+ httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+ + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX, "true");
+
+ /* PDP and PAP client services */
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES, "PAP,PDP");
+
+ /* PAP client service configuration */
+
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+ PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
@@ -356,13 +449,13 @@ public class HttpClientTest {
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+ PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+ /* PDP client service configuration */
+
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+ PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+ PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7778");
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
- + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "pdp");
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+ PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, FALSE_STRING);
httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+ PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpdp");
@@ -382,85 +475,45 @@ public class HttpClientTest {
server.waitedStart(10000);
}
+ Response response;
final HttpClient clientPap = HttpClientFactoryInstance.getClientFactory().get("PAP");
- final Response response = clientPap.get();
+ response = clientPap.get();
assertEquals(200, response.getStatus());
final HttpClient clientPdp = HttpClientFactoryInstance.getClientFactory().get("PDP");
- final Response response2 = clientPdp.get("test");
- assertEquals(500, response2.getStatus());
- assertFalse(MyJacksonProvider.hasWrittenSome());
- assertFalse(MyGsonProvider.hasWrittenSome());
- }
-
- @Test
- public void testHttpAuthClientProps_MixedProviders() throws Exception {
- final Properties httpProperties = new Properties();
+ response = clientPdp.get("pdp/test");
+ assertEquals(500, response.getStatus());
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES, "GSON,JACKSON");
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
- + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
- + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "6666");
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
- + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, JUNIT_ECHO);
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
- + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, FALSE_STRING);
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
- + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
- httpProperties.setProperty(
- PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
- + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
- MyGsonProvider.class.getName());
-
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
- + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
- + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "6666");
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
- + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, JUNIT_ECHO);
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
- + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, FALSE_STRING);
- httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
- + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
- httpProperties.setProperty(
- PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
- + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
- MyJacksonProvider.class.getName());
-
- final List<HttpClient> clients = HttpClientFactoryInstance.getClientFactory().build(httpProperties);
- assertEquals(2, clients.size());
-
- Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
+ response = clientPdp.get("metrics");
+ assertEquals(200, response.getStatus());
- // use gson client
- MyGsonProvider.resetSome();
- MyJacksonProvider.resetSome();
- HttpClient client = HttpClientFactoryInstance.getClientFactory().get("GSON");
+ response = clientPdp.get("openapi.json");
+ assertEquals(200, response.getStatus());
- Response response = client.put(HELLO, entity, Collections.emptyMap());
- String body = HttpClient.getBody(response, String.class);
+ assertFalse(MyGsonProvider.hasWrittenSome());
+ // try with empty path
+ response = clientPap.get("");
assertEquals(200, response.getStatus());
- assertEquals(PUT_HELLO, body);
- assertTrue(MyGsonProvider.hasWrittenSome());
- assertFalse(MyJacksonProvider.hasWrittenSome());
-
- // use jackson client
- MyGsonProvider.resetSome();
- MyJacksonProvider.resetSome();
- client = HttpClientFactoryInstance.getClientFactory().get("JACKSON");
+ response = clientPap.get("random/metrics");
+ assertEquals(200, response.getStatus());
- response = client.put(HELLO, entity, Collections.emptyMap());
- body = HttpClient.getBody(response, String.class);
+ response = clientPap.get("metrics");
+ assertEquals(404, response.getStatus());
+ // try it asynchronously, too
+ MyCallback callback = new MyCallback();
+ response = clientPap.get(callback, null).get();
+ verifyCallback("testHttpAuthClientProps", callback, response);
assertEquals(200, response.getStatus());
- assertEquals(PUT_HELLO, body);
- assertTrue(MyJacksonProvider.hasWrittenSome());
- assertFalse(MyGsonProvider.hasWrittenSome());
+ // try it asynchronously, with empty path
+ callback = new MyCallback();
+ response = clientPap.get(callback, "", null).get();
+ verifyCallback("testHttpAuthClientProps - empty path", callback, response);
+ assertEquals(200, response.getStatus());
}
private HttpClient getAuthHttpClient() throws HttpClientConfigException {
@@ -479,7 +532,7 @@ public class HttpClientTest {
}
- class MyEntity {
+ static class MyEntity {
private String myParameter;
@@ -497,4 +550,29 @@ public class HttpClientTest {
}
+ static class MyCallback implements InvocationCallback<Response> {
+ @Getter
+ private Response response;
+
+ @Getter
+ private Throwable throwable;
+
+ private CountDownLatch latch = new CountDownLatch(1);
+
+ @Override
+ public void completed(Response response) {
+ this.response = response;
+ latch.countDown();
+ }
+
+ @Override
+ public void failed(Throwable throwable) {
+ this.throwable = throwable;
+ latch.countDown();
+ }
+
+ public boolean await() throws InterruptedException {
+ return latch.await(5, TimeUnit.SECONDS);
+ }
+ }
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java
index 82faa052..8a2574e1 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java
@@ -2,7 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020, 2023-2024 Nordix Foundation.
+ * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,18 +22,25 @@
package org.onap.policy.common.endpoints.http.server.test;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson;
+import io.prometheus.client.servlet.jakarta.exporter.MetricsServlet;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
+import java.nio.charset.StandardCharsets;
+import java.util.Objects;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
import org.junit.AfterClass;
@@ -50,10 +59,13 @@ import org.slf4j.LoggerFactory;
* HttpServletServer JUNIT tests.
*/
public class HttpServerTest {
+ private static final String JVM_MEMORY_BYTES_USED = "jvm_memory_bytes_used";
+ private static final String METRICS_URI = "/metrics";
+ private static final String PROMETHEUS = "prometheus";
private static final String LOCALHOST = "localhost";
private static final String JSON_MEDIA = "application/json";
private static final String YAML_MEDIA = YamlMessageBodyHandler.APPLICATION_YAML;
- private static final String SWAGGER_JSON = "/swagger.json";
+ private static final String SWAGGER_JSON = "/openapi.json";
private static final String JUNIT_ECHO_HELLO = "/junit/echo/hello";
private static final String JUNIT_ECHO_FULL_REQUEST = "/junit/echo/full/request";
private static final String SOME_TEXT = "some text";
@@ -62,7 +74,7 @@ public class HttpServerTest {
/**
* Logger.
*/
- private static Logger logger = LoggerFactory.getLogger(HttpServerTest.class);
+ private static final Logger logger = LoggerFactory.getLogger(HttpServerTest.class);
private static final String LOCALHOST_PREFIX = "http://localhost:";
@@ -85,7 +97,6 @@ public class HttpServerTest {
HttpServletServerFactoryInstance.getServerFactory().destroy();
- MyJacksonProvider.resetSome();
MyGsonProvider.resetSome();
MyYamlProvider.resetSome();
}
@@ -94,9 +105,14 @@ public class HttpServerTest {
port += 10;
}
+ /**
+ * To delete temporary properties cadi_longitude,and cadi_latitude.
+ */
@AfterClass
public static void tearDownAfterClass() {
HttpServletServerFactoryInstance.getServerFactory().destroy();
+ System.clearProperty("cadi_longitude");
+ System.clearProperty("cadi_latitude");
}
@Test
@@ -121,38 +137,6 @@ public class HttpServerTest {
}
@Test
- public void testJacksonPackageServer() throws Exception {
- logger.info("-- testJacksonPackageServer() --");
-
- HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory()
- .build("echo", LOCALHOST, port, "/", false, true);
-
- server.setSerializationProvider(MyJacksonProvider.class.getName());
- server.addServletPackage("/*", this.getClass().getPackage().getName());
- server.addFilterClass("/*", TestFilter.class.getName());
- server.waitedStart(5000);
-
- assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
-
- RestEchoReqResp request = new RestEchoReqResp();
- request.setRequestId(100);
- request.setText(SOME_TEXT);
- String reqText = gson.toJson(request);
-
- String response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, JSON_MEDIA, reqText);
- assertEquals(reqText, response);
-
- assertTrue(MyJacksonProvider.hasReadSome());
- assertTrue(MyJacksonProvider.hasWrittenSome());
-
- assertFalse(MyGsonProvider.hasReadSome());
- assertFalse(MyGsonProvider.hasWrittenSome());
-
- assertFalse(MyYamlProvider.hasReadSome());
- assertFalse(MyYamlProvider.hasWrittenSome());
- }
-
- @Test
public void testGsonPackageServer() throws Exception {
logger.info("-- testGsonPackageServer() --");
@@ -177,9 +161,6 @@ public class HttpServerTest {
assertTrue(MyGsonProvider.hasReadSome());
assertTrue(MyGsonProvider.hasWrittenSome());
- assertFalse(MyJacksonProvider.hasReadSome());
- assertFalse(MyJacksonProvider.hasWrittenSome());
-
assertFalse(MyYamlProvider.hasReadSome());
assertFalse(MyYamlProvider.hasWrittenSome());
}
@@ -213,9 +194,6 @@ public class HttpServerTest {
assertFalse(MyGsonProvider.hasReadSome());
assertFalse(MyGsonProvider.hasWrittenSome());
-
- assertFalse(MyJacksonProvider.hasReadSome());
- assertFalse(MyJacksonProvider.hasWrittenSome());
}
@Test
@@ -239,13 +217,85 @@ public class HttpServerTest {
assertEquals(reqText, response);
}
+ /**
+ * This test checks a server from a plain java servlet (note it uses prometheus as the sample server).
+ */
+ @Test
+ public void testStdServletServer() throws Exception {
+ logger.info("-- testStdServletServer() --");
+
+ HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory()
+ .build(PROMETHEUS, LOCALHOST, port, "/", false, true);
+
+ server.addStdServletClass("/prom-generic-servlet/metrics", MetricsServlet.class.getName());
+ server.waitedStart(5000);
+
+ assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
+ assertTrue(server.isPrometheus());
+
+ String response = http(portUrl + "/prom-generic-servlet/metrics");
+ assertThat(response).contains(JVM_MEMORY_BYTES_USED);
+ }
+
+ /**
+ * This test explicitly creates a prometheus server.
+ */
+ @Test
+ public void testExplicitPrometheusServer() throws Exception {
+ logger.info("-- testPrometheusServer() --");
+
+ HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory()
+ .build(PROMETHEUS, LOCALHOST, port, "/", false, true);
+ server.setPrometheus(METRICS_URI);
+ server.waitedStart(5000);
+
+ assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
+ assertTrue(server.isPrometheus());
+
+ String response = http(portUrl + METRICS_URI);
+ assertThat(response).contains(JVM_MEMORY_BYTES_USED);
+ }
+
+ /**
+ * This test is an all-in-one for a single server: prometheus, jax-rs, servlet, swagger, and filters.
+ */
+ @Test
+ public void testPrometheusJaxRsFilterSwaggerServer() throws Exception {
+ logger.info("-- testPrometheusServer() --");
+
+ HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory()
+ .build(PROMETHEUS, LOCALHOST, port, "/", true, true);
+
+ server.addServletClass("/*", RestEchoService.class.getName());
+ server.addFilterClass("/*", TestFilter.class.getName());
+ server.setPrometheus(METRICS_URI);
+
+ server.waitedStart(5000);
+
+ assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
+ assertTrue(server.isPrometheus());
+
+ String response = http(portUrl + METRICS_URI);
+ assertThat(response).contains(JVM_MEMORY_BYTES_USED);
+
+ RestEchoReqResp request = new RestEchoReqResp();
+ request.setRequestId(100);
+ request.setText(SOME_TEXT);
+ String reqText = gson.toJson(request);
+
+ response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, JSON_MEDIA, reqText);
+ assertEquals(reqText, response);
+
+ response = http(portUrl + SWAGGER_JSON);
+ assertThat(response).contains("openapi");
+ }
+
@Test
public void testJacksonClassServer() throws Exception {
logger.info("-- testJacksonClassServer() --");
HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory()
.build("echo", LOCALHOST, port, "/", false, true);
- server.setSerializationProvider(MyJacksonProvider.class.getName());
server.addServletClass("/*", RestEchoService.class.getName());
server.addFilterClass("/*", TestFilter.class.getName());
server.waitedStart(5000);
@@ -260,9 +310,6 @@ public class HttpServerTest {
String response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, JSON_MEDIA, reqText);
assertEquals(reqText, response);
- assertTrue(MyJacksonProvider.hasReadSome());
- assertTrue(MyJacksonProvider.hasWrittenSome());
-
assertFalse(MyGsonProvider.hasReadSome());
assertFalse(MyGsonProvider.hasWrittenSome());
@@ -294,9 +341,6 @@ public class HttpServerTest {
assertTrue(MyGsonProvider.hasReadSome());
assertTrue(MyGsonProvider.hasWrittenSome());
- assertFalse(MyJacksonProvider.hasReadSome());
- assertFalse(MyJacksonProvider.hasWrittenSome());
-
assertFalse(MyYamlProvider.hasReadSome());
assertFalse(MyYamlProvider.hasWrittenSome());
}
@@ -329,9 +373,6 @@ public class HttpServerTest {
assertFalse(MyGsonProvider.hasReadSome());
assertFalse(MyGsonProvider.hasWrittenSome());
-
- assertFalse(MyJacksonProvider.hasReadSome());
- assertFalse(MyJacksonProvider.hasWrittenSome());
}
@Test
@@ -343,6 +384,7 @@ public class HttpServerTest {
// ensure we can serialize the server
new GsonTestUtils().compareGson(server, HttpServerTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(server, HttpServerTest.class)).doesNotThrowAnyException();
}
@Test
@@ -356,7 +398,6 @@ public class HttpServerTest {
server.waitedStart(5000);
assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
- assertFalse(HttpServletServerFactoryInstance.getServerFactory().get(port).isAaf());
String response = http(portUrl + JUNIT_ECHO_HELLO);
assertEquals(HELLO, response);
@@ -369,9 +410,6 @@ public class HttpServerTest {
assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
assertEquals(1, HttpServletServerFactoryInstance.getServerFactory().inventory().size());
- server.setAafAuthentication("/*");
- assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAaf());
-
HttpServletServerFactoryInstance.getServerFactory().destroy(port);
assertEquals(0, HttpServletServerFactoryInstance.getServerFactory().inventory().size());
}
@@ -381,7 +419,7 @@ public class HttpServerTest {
logger.info("-- testMultipleServers() --");
HttpServletServer server1 = HttpServletServerFactoryInstance.getServerFactory()
- .build("echo-1", false,LOCALHOST, port, "/", true, true);
+ .build("echo-1", false, LOCALHOST, port, false, "/", true, true);
server1.addServletPackage("/*", this.getClass().getPackage().getName());
server1.waitedStart(5000);
@@ -396,13 +434,13 @@ public class HttpServerTest {
assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port2).isAlive());
String response = http(portUrl + JUNIT_ECHO_HELLO);
- assertTrue(HELLO.equals(response));
+ assertEquals(HELLO, response);
response = http(portUrl + SWAGGER_JSON);
- assertTrue(response != null);
+ assertNotNull(response);
response = http(LOCALHOST_PREFIX + port2 + JUNIT_ECHO_HELLO);
- assertTrue(HELLO.equals(response));
+ assertEquals(HELLO, response);
assertThatThrownBy(() -> http(LOCALHOST_PREFIX + port2 + SWAGGER_JSON)).isInstanceOf(IOException.class);
@@ -424,7 +462,7 @@ public class HttpServerTest {
assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
String response = http(portUrl + JUNIT_ECHO_HELLO);
- assertTrue(HELLO.equals(response));
+ assertEquals(HELLO, response);
response = http(portUrl + "/junit/endpoints/http/servers");
assertTrue(response.contains(randomName));
@@ -446,7 +484,7 @@ public class HttpServerTest {
assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
String response = http(portUrl + JUNIT_ECHO_HELLO);
- assertTrue(HELLO.equals(response));
+ assertEquals(HELLO, response);
HttpServletServerFactoryInstance.getServerFactory().destroy();
assertTrue(HttpServletServerFactoryInstance.getServerFactory().inventory().isEmpty());
@@ -467,7 +505,7 @@ public class HttpServerTest {
assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
String response = http(portUrl + JUNIT_ECHO_HELLO);
- assertTrue(HELLO.equals(response));
+ assertEquals(HELLO, response);
response = http(portUrl + "/junit/endpoints/http/servers");
assertTrue(response.contains(randomName));
@@ -476,6 +514,108 @@ public class HttpServerTest {
assertTrue(HttpServletServerFactoryInstance.getServerFactory().inventory().isEmpty());
}
+ @Test
+ public void testSingleStaticResourceServer() throws Exception {
+ logger.info("-- testSingleStaticResourceServer() --");
+
+ HttpServletServer staticServer = HttpServletServerFactoryInstance.getServerFactory()
+ .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, false, "/", true);
+ Throwable thrown = catchThrowable(() -> staticServer.addServletResource("/*", null));
+ assertThat(thrown).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("No resourceBase provided");
+
+ staticServer.addServletResource(null,
+ Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/root"))
+ .toExternalForm());
+
+ thrown = catchThrowable(() -> staticServer.addServletClass("/*", RestEchoService.class.getName()));
+ assertThat(thrown).isInstanceOf(UnsupportedOperationException.class)
+ .hasMessageContaining("is not supported on this type of jetty server");
+
+ thrown = catchThrowable(() -> staticServer.addServletPackage("/api/*", this.getClass().getPackage().getName()));
+ assertThat(thrown).isInstanceOf(UnsupportedOperationException.class)
+ .hasMessageContaining("is not supported on this type of jetty server");
+
+ thrown = catchThrowable(() -> staticServer.setSerializationProvider(MyGsonProvider.class.getName()));
+ assertThat(thrown).isInstanceOf(UnsupportedOperationException.class)
+ .hasMessageContaining("is not supported on this type of jetty server");
+
+ staticServer.waitedStart(5000);
+
+ assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
+ assertEquals(1, HttpServletServerFactoryInstance.getServerFactory().inventory().size());
+
+ String response = http(portUrl);
+ assertThat(response).contains("Test Jetty Static Resources Root");
+
+ HttpServletServerFactoryInstance.getServerFactory().destroy(port);
+ assertEquals(0, HttpServletServerFactoryInstance.getServerFactory().inventory().size());
+ }
+
+ @Test
+ public void testMultiStaticResourceServer() throws Exception {
+ logger.info("-- testMultiStaticResourceServer() --");
+
+ HttpServletServer staticResourceServer = HttpServletServerFactoryInstance.getServerFactory()
+ .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, false, "/", true);
+ staticResourceServer.addServletResource("/root/*",
+ Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/root"))
+ .toExternalForm());
+ staticResourceServer.addServletResource("/alt-root/*",
+ Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/alt-root"))
+ .toExternalForm());
+ staticResourceServer.waitedStart(5000);
+
+ assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
+ assertEquals(1, HttpServletServerFactoryInstance.getServerFactory().inventory().size());
+
+ String response = http(portUrl + "/root/");
+ assertThat(response).contains("Test Jetty Static Resources Root");
+
+ response = http(portUrl + "/alt-root/");
+ assertThat(response).contains("Test Jetty Static Resources Alt-Root");
+
+ HttpServletServerFactoryInstance.getServerFactory().destroy(port);
+ assertEquals(0, HttpServletServerFactoryInstance.getServerFactory().inventory().size());
+ }
+
+ @Test
+ public void testMultiTypesServer() throws Exception {
+ logger.info("-- testMultiTypesServer() --");
+
+ HttpServletServer staticResourceServer = HttpServletServerFactoryInstance.getServerFactory()
+ .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, false, "/", true);
+ staticResourceServer.addServletResource("/root/*",
+ Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/root"))
+ .toExternalForm());
+ staticResourceServer.waitedStart(5000);
+
+ int port2 = port + 1;
+ HttpServletServer jerseyServer =
+ HttpServletServerFactoryInstance.getServerFactory().build("echo", LOCALHOST, port2, "/", false, true);
+ jerseyServer.addServletPackage("/api/*", this.getClass().getPackage().getName());
+
+ Throwable thrown = catchThrowable(() -> jerseyServer.addServletResource("/root/*",
+ Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/root"))
+ .toExternalForm()));
+ assertThat(thrown).isInstanceOf(UnsupportedOperationException.class)
+ .hasMessageContaining("is not supported on this type of jetty server");
+
+ jerseyServer.waitedStart(5000);
+
+ assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive());
+ assertEquals(2, HttpServletServerFactoryInstance.getServerFactory().inventory().size());
+
+ String response = http(portUrl + "/root/");
+ assertThat(response).contains("Test Jetty Static Resources Root");
+
+ response = http(LOCALHOST_PREFIX + port2 + "/api" + JUNIT_ECHO_HELLO);
+ assertEquals(HELLO, response);
+
+ HttpServletServerFactoryInstance.getServerFactory().destroy();
+ assertEquals(0, HttpServletServerFactoryInstance.getServerFactory().inventory().size());
+ }
+
/**
* performs an http request.
*
@@ -486,14 +626,14 @@ public class HttpServerTest {
private String http(String urlString)
throws IOException, InterruptedException {
URL url = new URL(urlString);
- if (!NetworkUtil.isTcpPortOpen(url.getHost(), url.getPort(), 25, 2)) {
+ if (!NetworkUtil.isTcpPortOpen(url.getHost(), url.getPort(), 25, 100)) {
throw new IllegalStateException("port never opened: " + url);
}
return response(url.openConnection());
}
/**
- * Performs an http request.
+ * Performs a http request.
*
* @throws MalformedURLException make sure URL is good
* @throws IOException thrown is IO exception occurs
@@ -502,7 +642,7 @@ public class HttpServerTest {
private String http(String urlString, String mediaType, String post)
throws IOException, InterruptedException {
URL url = new URL(urlString);
- if (!NetworkUtil.isTcpPortOpen(url.getHost(), url.getPort(), 25, 2)) {
+ if (!NetworkUtil.isTcpPortOpen(url.getHost(), url.getPort(), 25, 100)) {
throw new IllegalStateException("port never opened: " + url);
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
@@ -510,7 +650,7 @@ public class HttpServerTest {
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", mediaType);
conn.setRequestProperty("Accept", mediaType);
- IOUtils.write(post, conn.getOutputStream());
+ IOUtils.write(post, conn.getOutputStream(), StandardCharsets.UTF_8);
return response(conn);
}
@@ -523,7 +663,7 @@ public class HttpServerTest {
*/
private String response(URLConnection conn) throws IOException {
try (InputStream inpstr = conn.getInputStream()) {
- return String.join("", IOUtils.readLines(inpstr));
+ return String.join("", IOUtils.readLines(inpstr, StandardCharsets.UTF_8));
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java
index 59ce0c1c..27e98670 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 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.
@@ -23,7 +24,7 @@ package org.onap.policy.common.endpoints.http.server.test;
import static org.junit.Assert.assertEquals;
import com.google.gson.JsonSyntaxException;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.endpoints.http.server.JsonExceptionMapper;
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java
index 8343d02d..78c41cc2 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 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.
@@ -20,13 +21,13 @@
package org.onap.policy.common.endpoints.http.server.test;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
import lombok.AccessLevel;
import lombok.Setter;
import org.onap.policy.common.gson.GsonMessageBodyHandler;
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyJacksonProvider.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyJacksonProvider.java
deleted file mode 100644
index 8c4eea5a..00000000
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyJacksonProvider.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 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.endpoints.http.server.test;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-
-import lombok.AccessLevel;
-import lombok.Setter;
-
-import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
-
-/**
- * JacksonJsonProvider that tracks activities.
- */
-public class MyJacksonProvider extends JacksonJsonProvider {
-
- @Setter(AccessLevel.PRIVATE)
- private static boolean readSome = false;
-
- @Setter(AccessLevel.PRIVATE)
- private static boolean wroteSome = false;
-
- /**
- * Constructs the object and resets the variables to indicate that no activity has
- * occurred yet.
- */
- public MyJacksonProvider() {
- super();
- }
-
- @Override
- public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
- MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
-
- setReadSome(true);
- return super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
- }
-
- @Override
- public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
- MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
-
- setWroteSome(true);
- super.writeTo(object, type, genericType, annotations, mediaType, httpHeaders, entityStream);
- }
-
- public static boolean hasReadSome() {
- return readSome;
- }
-
- public static boolean hasWrittenSome() {
- return wroteSome;
- }
-
- public static void resetSome() {
- MyJacksonProvider.readSome = false;
- MyJacksonProvider.wroteSome = false;
- }
-
-}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java
index 098ecb44..624d7686 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 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.
@@ -20,13 +21,13 @@
package org.onap.policy.common.endpoints.http.server.test;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
import lombok.AccessLevel;
import lombok.Setter;
import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java
index c211881f..2748fadd 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,21 +20,20 @@
package org.onap.policy.common.endpoints.http.server.test;
-import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.annotations.SerializedName;
+import lombok.ToString;
import org.onap.policy.common.gson.annotation.GsonJsonProperty;
/**
* "ECHO" request and response supporting serialization and de-serialization via
* both jackson and gson.
*/
+@ToString
public class RestEchoReqResp {
- @JsonProperty("reqId")
@GsonJsonProperty("reqId")
@SerializedName("reqId")
private int requestId;
- @JsonProperty("textValue")
@GsonJsonProperty("textValue")
@SerializedName("textValue")
private String text;
@@ -54,9 +53,4 @@ public class RestEchoReqResp {
public void setText(String text) {
this.text = text;
}
-
- @Override
- public String toString() {
- return "RestEchoReqResp [requestId=" + requestId + ", text=" + text + "]";
- }
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java
index 373950b2..b4a652aa 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2017-2019 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.
@@ -20,29 +21,30 @@
package org.onap.policy.common.endpoints.http.server.test;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.PUT;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response.Status;
import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
-@Api(value = "echo")
@Path("/junit/echo")
public class RestEchoService {
@GET
@Path("{word}")
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "echoes back whatever received")
+ @Operation(summary = "echoes back whatever received")
public String echo(@PathParam("word") String word) {
return word;
}
@@ -50,7 +52,7 @@ public class RestEchoService {
@PUT
@Path("{word}")
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "echoes back whatever received")
+ @Operation(summary = "echoes back whatever received")
public String echoPut(@PathParam("word") String word, Object entity) {
return "PUT:" + word + ":" + entity.toString();
}
@@ -58,7 +60,8 @@ public class RestEchoService {
@POST
@Path("/full/request")
@Produces({MediaType.APPLICATION_JSON, YamlMessageBodyHandler.APPLICATION_YAML})
- @ApiOperation(value = "echoes back the request structure", response = RestEchoReqResp.class)
+ @Operation(summary = "echoes back the request structure")
+ @ApiResponse(content = {@Content(schema = @Schema(implementation = RestEchoReqResp.class))})
public Response echoFullyPost(RestEchoReqResp reqResp) {
return Response.status(Status.OK).entity(reqResp).build();
}
@@ -66,7 +69,7 @@ public class RestEchoService {
@POST
@Path("{word}")
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "echoes back whatever received")
+ @Operation(summary = "echoes back whatever received")
public String echoPost(@PathParam("word") String word, Object entity) {
return "POST:" + word + ":" + entity.toString();
}
@@ -74,7 +77,7 @@ public class RestEchoService {
@DELETE
@Path("{word}")
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "echoes back whatever received")
+ @Operation(summary = "echoes back whatever received")
public String echoDelete(@PathParam("word") String word) {
return "DELETE:" + word;
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java
index 6ada15c5..cbcf4c9a 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019-2020 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.
@@ -20,13 +21,11 @@
package org.onap.policy.common.endpoints.http.server.test;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
import java.util.List;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java
index f0d68c0c..f476dbaf 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java
@@ -3,6 +3,7 @@
* policy-endpoints
* ================================================================================
* Copyright (C) 2017 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.
@@ -20,12 +21,12 @@
package org.onap.policy.common.endpoints.http.server.test;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response.Status;
@Path("/")
public class RestMockHealthCheck {
@@ -40,7 +41,7 @@ public class RestMockHealthCheck {
@GET
@Path("pdp/test")
@Produces(MediaType.APPLICATION_JSON)
- public Response pdpHealthCheck() {
+ public Response pdpHealthCheck() {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("At least some Dead").build();
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java
index 16f17652..a789a66f 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java
@@ -2,7 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2021 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.
@@ -31,6 +33,16 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import io.prometheus.client.servlet.jakarta.exporter.MetricsServlet;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
@@ -38,14 +50,8 @@ import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
+import java.util.List;
import java.util.Properties;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
import lombok.Getter;
import org.apache.commons.io.IOUtils;
import org.junit.AfterClass;
@@ -60,15 +66,15 @@ import org.onap.policy.common.endpoints.http.server.RestServer;
import org.onap.policy.common.endpoints.http.server.RestServer.Factory;
import org.onap.policy.common.endpoints.http.server.YamlExceptionMapper;
import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
-import org.onap.policy.common.endpoints.http.server.aaf.AafAuthFilter;
import org.onap.policy.common.endpoints.parameters.RestServerParameters;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.onap.policy.common.gson.GsonMessageBodyHandler;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.network.NetworkUtil;
-import org.powermock.reflect.Whitebox;
+import org.springframework.test.util.ReflectionTestUtils;
public class RestServerTest {
+ private static final String METRICS_URI = "/metrics";
private static final String SERVER1 = "my-server-A";
private static final String SERVER2 = "my-server-B";
private static final String FACTORY_FIELD = "factory";
@@ -96,13 +102,13 @@ public class RestServerTest {
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
- saveFactory = Whitebox.getInternalState(RestServer.class, FACTORY_FIELD);
+ saveFactory = (Factory) ReflectionTestUtils.getField(RestServer.class, FACTORY_FIELD);
realPort = NetworkUtil.allocPort();
initRealParams();
- realRest = new RestServer(params, null, RealProvider.class) {
+ realRest = new RestServer(params, RealProvider.class) {
@Override
protected Properties getServerProperties(RestServerParameters restServerParameters, String names) {
Properties props = super.getServerProperties(restServerParameters, names);
@@ -124,7 +130,7 @@ public class RestServerTest {
*/
@AfterClass
public static void tearDownAfterClass() {
- Whitebox.setInternalState(RestServer.class, FACTORY_FIELD, saveFactory);
+ ReflectionTestUtils.setField(RestServer.class, FACTORY_FIELD, saveFactory);
realRest.stop();
}
@@ -147,12 +153,12 @@ public class RestServerTest {
when(server1.getName()).thenReturn(SERVER1);
when(server2.getName()).thenReturn(SERVER2);
- Whitebox.setInternalState(RestServer.class, FACTORY_FIELD, factory);
+ ReflectionTestUtils.setField(RestServer.class, FACTORY_FIELD, factory);
}
@Test
public void testRestServer() {
- rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class);
+ rest = new RestServer(params, Filter2.class, Provider1.class, Provider2.class);
rest.start();
verify(server1).start();
@@ -164,52 +170,26 @@ public class RestServerTest {
}
@Test
- public void testRestServer_NoAaf() {
- rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class);
- verify(server1, never()).addFilterClass(any(), any());
- verify(server2, never()).addFilterClass(any(), any());
- }
-
- @Test
- public void testRestServer_OnlyOneAaf() {
- when(server2.isAaf()).thenReturn(true);
-
- rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class);
-
- verify(server1, never()).addFilterClass(any(), any());
- verify(server2).addFilterClass(null, Filter.class.getName());
- }
-
- @Test
- public void testRestServer_BothAaf() {
- when(server1.isAaf()).thenReturn(true);
- when(server2.isAaf()).thenReturn(true);
-
- rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class);
-
- verify(server1).addFilterClass(null, Filter.class.getName());
- verify(server2).addFilterClass(null, Filter.class.getName());
- }
+ public void testRestServerListList() {
+ rest = new RestServer(params, List.of(Filter2.class), List.of(Provider1.class, Provider2.class));
- @Test
- public void testRestServer_BothAaf_NoFilter() {
- when(server1.isAaf()).thenReturn(true);
- when(server2.isAaf()).thenReturn(true);
-
- rest = new RestServer(params, null, Provider1.class, Provider2.class);
+ rest.start();
+ verify(server1).start();
+ verify(server2).start();
- verify(server1, never()).addFilterClass(any(), any());
- verify(server2, never()).addFilterClass(any(), any());
+ rest.stop();
+ verify(server1).stop();
+ verify(server2).stop();
}
@Test
public void testRestServer_MissingProviders() {
- assertThatIllegalArgumentException().isThrownBy(() -> new RestServer(params, Filter.class));
+ assertThatIllegalArgumentException().isThrownBy(() -> new RestServer(params, List.of(Filter2.class), null));
}
@Test
public void testGetServerProperties_testGetProviderNames() {
- rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class);
+ rest = new RestServer(params, Provider1.class, Provider2.class);
ArgumentCaptor<Properties> cap = ArgumentCaptor.forClass(Properties.class);
verify(serverFactory).build(cap.capture());
@@ -227,10 +207,43 @@ public class RestServerTest {
assertEquals(USER, props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX));
assertEquals(PASS, props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX));
assertEquals("true", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX));
- assertEquals("true", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX));
assertEquals(String.join(",", GsonMessageBodyHandler.class.getName(), YamlMessageBodyHandler.class.getName(),
JsonExceptionMapper.class.getName(), YamlExceptionMapper.class.getName()),
props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER));
+ assertEquals("false", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX));
+ }
+
+ @Test
+ public void testExplicitPrometheusAddedToProperty() {
+ when(params.isPrometheus()).thenReturn(true);
+ rest = new RestServer(params, Filter2.class, Provider1.class, Provider2.class);
+ ArgumentCaptor<Properties> cap = ArgumentCaptor.forClass(Properties.class);
+ verify(serverFactory).build(cap.capture());
+
+ Properties props = cap.getValue();
+ String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + PARAM_NAME;
+
+ assertEquals("true", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX));
+ assertThat(props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX)).isBlank();
+ assertThat(props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_CLASS_SUFFIX)).isBlank();
+ }
+
+ @Test
+ public void testStandardServletAddedToProperty() {
+ when(params.getServletUriPath()).thenReturn("/metrics");
+ when(params.getServletClass()).thenReturn(MetricsServlet.class.getName());
+ rest = new RestServer(params, Filter2.class, Provider1.class, Provider2.class);
+ ArgumentCaptor<Properties> cap = ArgumentCaptor.forClass(Properties.class);
+ verify(serverFactory).build(cap.capture());
+
+ Properties props = cap.getValue();
+ String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + PARAM_NAME;
+
+ assertEquals("false", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX));
+ assertEquals(METRICS_URI,
+ props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX));
+ assertEquals(MetricsServlet.class.getName(),
+ props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_CLASS_SUFFIX));
}
@Test
@@ -285,7 +298,7 @@ public class RestServerTest {
@Test
public void testToString() {
- rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class);
+ rest = new RestServer(params, Filter2.class, Provider1.class, Provider2.class);
assertNotNull(rest.toString());
}
@@ -316,15 +329,10 @@ public class RestServerTest {
when(params.isHttps()).thenReturn(true);
}
- private static class Filter extends AafAuthFilter {
+ private static class Filter2 implements jakarta.servlet.Filter {
@Override
- protected String getPermissionType(HttpServletRequest request) {
- return "";
- }
-
- @Override
- protected String getPermissionInstance(HttpServletRequest request) {
- return "";
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
+ // do nothing
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java
index f3cd7424..59ec6f13 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2018 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.
@@ -20,7 +21,7 @@
package org.onap.policy.common.endpoints.http.server.test;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
import org.onap.policy.common.endpoints.http.server.AuthorizationFilter;
public class TestAuthorizationFilter extends AuthorizationFilter {
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java
index 44b37656..155e12bb 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2018 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.
@@ -20,12 +21,12 @@
package org.onap.policy.common.endpoints.http.server.test;
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
import java.io.IOException;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
public class TestFilter implements Filter {
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java
index 96c23ed3..5317eadb 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 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.
@@ -22,7 +23,7 @@ package org.onap.policy.common.endpoints.http.server.test;
import static org.junit.Assert.assertEquals;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.endpoints.http.server.YamlExceptionMapper;
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java
index 7ca131ec..b2b81c26 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 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.
@@ -25,12 +26,14 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.google.gson.JsonObject;
+import jakarta.ws.rs.core.MediaType;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
-import javax.ws.rs.core.MediaType;
+import lombok.ToString;
import org.junit.Test;
import org.onap.policy.common.endpoints.http.server.YamlJacksonHandler;
import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
@@ -65,7 +68,7 @@ public class YamlJacksonHandlerTest {
ByteArrayOutputStream outstr = new ByteArrayOutputStream();
hdlr.writeTo(data, Data.class, Data.class, null, null, null, outstr);
- assertEquals("abc: def\nhello: world\nmyId: 100\nvalue: a value\n", outstr.toString("UTF-8"));
+ assertEquals("abc: def\nhello: world\nmyId: 100\nvalue: a value\n", outstr.toString(StandardCharsets.UTF_8));
/*
* Ensure everything deserializes as expected.
@@ -106,6 +109,7 @@ public class YamlJacksonHandlerTest {
/**
* This class includes all policy-specific gson annotations.
*/
+ @ToString
public static class Data {
protected int id;
@@ -144,11 +148,6 @@ public class YamlJacksonHandlerTest {
props.put(name, value);
}
-
- @Override
- public String toString() {
- return "Data [id=" + id + ", value=" + value + ", props=" + props + "]";
- }
}
private static class MyMap {
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java
index 70b620c0..962c09db 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -25,6 +26,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import jakarta.ws.rs.core.MediaType;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -32,7 +34,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
-import javax.ws.rs.core.MediaType;
+import lombok.ToString;
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
@@ -115,8 +117,7 @@ public class YamlMessageBodyHandlerTest {
};
MyObject obj1 = new MyObject(10);
-
- assertThatThrownBy(() -> hdlr.writeTo(obj1, obj1.getClass(), CLASS_OBJ, null, null, null, outstr))
+ assertThatThrownBy(() -> hdlr.writeTo(obj1, MyObject.class, CLASS_OBJ, null, null, null, outstr))
.isInstanceOf(YAMLException.class);
outstr.close();
@@ -213,6 +214,7 @@ public class YamlMessageBodyHandlerTest {
}
}
+ @ToString
public static class MyObject {
private int id;
@@ -223,11 +225,6 @@ public class YamlMessageBodyHandlerTest {
public MyObject(int id) {
this.id = id;
}
-
- @Override
- public String toString() {
- return "MyObject [id=" + id + "]";
- }
}
private static class MyMap {
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java
index 1c5a175d..e4c84f3a 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java
@@ -1,4 +1,4 @@
-/*
+/*--
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
@@ -37,8 +37,6 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
-import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
-import org.onap.policy.common.endpoints.listeners.ScoListener;
import org.onap.policy.common.utils.coder.StandardCoderObject;
import org.onap.policy.common.utils.test.log.logback.ExtractAppender;
import org.slf4j.LoggerFactory;
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java
index 94717e53..d71d413e 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,7 +23,6 @@ package org.onap.policy.common.endpoints.listeners;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -119,16 +118,16 @@ public class RequestIdDispatcherTest {
// should process message that does not have a request id
status = new MyMessage();
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1).onTopicEvent(INFRA, TOPIC, status);
// should process again
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1, times(2)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1, times(2)).onTopicEvent(INFRA, TOPIC, status);
// should NOT process a message that has a request id
status = new MyMessage(REQID1);
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1, never()).onTopicEvent(INFRA, TOPIC, status);
}
@Test
@@ -138,21 +137,21 @@ public class RequestIdDispatcherTest {
// should NOT process message that does not have a request id
status = new MyMessage();
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1, never()).onTopicEvent(INFRA, TOPIC, status);
// should process a message that has the desired request id
status = new MyMessage(REQID1);
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1).onTopicEvent(INFRA, TOPIC, status);
// should process again
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1, times(2)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1, times(2)).onTopicEvent(INFRA, TOPIC, status);
// should NOT process a message that does NOT have the desired request id
status = new MyMessage(REQID2);
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1, never()).onTopicEvent(INFRA, TOPIC, status);
// null request id => exception
assertThatIllegalArgumentException().isThrownBy(() -> primary.register(null, secondary1));
@@ -169,17 +168,17 @@ public class RequestIdDispatcherTest {
// should process message
status = new MyMessage();
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
- verify(secondary2).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1).onTopicEvent(INFRA, TOPIC, status);
+ verify(secondary2).onTopicEvent(INFRA, TOPIC, status);
primary.unregister(secondary1);
// should NOT process again
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1, times(1)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1, times(1)).onTopicEvent(INFRA, TOPIC, status);
// other listener should still have processed it
- verify(secondary2, times(2)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary2, times(2)).onTopicEvent(INFRA, TOPIC, status);
}
@Test
@@ -190,18 +189,18 @@ public class RequestIdDispatcherTest {
// should process a message that has the desired request id
status = new MyMessage(REQID1);
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1).onTopicEvent(INFRA, TOPIC, status);
primary.unregister(REQID1);
// should NOT re-process
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1, times(1)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1, times(1)).onTopicEvent(INFRA, TOPIC, status);
// secondary should still be able to process
status = new MyMessage(REQID2);
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary2).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary2).onTopicEvent(INFRA, TOPIC, status);
}
@Test
@@ -214,18 +213,18 @@ public class RequestIdDispatcherTest {
// without request id
status = new MyMessage();
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
- verify(secondary2, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
- verify(secondary3).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
- verify(secondary4).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1, never()).onTopicEvent(INFRA, TOPIC, status);
+ verify(secondary2, never()).onTopicEvent(INFRA, TOPIC, status);
+ verify(secondary3).onTopicEvent(INFRA, TOPIC, status);
+ verify(secondary4).onTopicEvent(INFRA, TOPIC, status);
// with request id
status = new MyMessage(REQID1);
primary.onTopicEvent(INFRA, TOPIC, makeSco(status));
- verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
- verify(secondary2, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
- verify(secondary3, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
- verify(secondary4, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status));
+ verify(secondary1).onTopicEvent(INFRA, TOPIC, status);
+ verify(secondary2, never()).onTopicEvent(INFRA, TOPIC, status);
+ verify(secondary3, never()).onTopicEvent(INFRA, TOPIC, status);
+ verify(secondary4, never()).onTopicEvent(INFRA, TOPIC, status);
}
@Test
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java
index 8543b73e..a782e4b2 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,7 +22,6 @@ package org.onap.policy.common.endpoints.listeners;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -111,14 +110,14 @@ public class ScoListenerTest {
status = new MyMessage(NAME);
sco = makeSco(status);
primary.onTopicEvent(INFRA, TOPIC, sco);
- verify(primary).onTopicEvent(eq(INFRA), eq(TOPIC), eq(sco), eq(status));
+ verify(primary).onTopicEvent(INFRA, TOPIC, sco, status);
assertFalse(appender.getExtracted().toString().contains("unable to decode"));
// undecodable message
logger.addAppender(appender);
primary.onTopicEvent(INFRA, TOPIC, makeSco("[]"));
- verify(primary, times(1)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(sco), eq(status));
+ verify(primary, times(1)).onTopicEvent(INFRA, TOPIC, sco, status);
assertTrue(appender.getExtracted().toString().contains("unable to decode"));
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/CommonTestData.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/CommonTestData.java
index e3f0878f..ce0f58de 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/CommonTestData.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/CommonTestData.java
@@ -1,6 +1,6 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
+ * Copyright (C) 2019, 2024 Nordix Foundation.
* Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
@@ -49,9 +49,9 @@ public class CommonTestData {
public static final boolean REST_SERVER_HTTPS = true;
public static final boolean REST_SERVER_AAF = false;
- public static final String TOPIC_NAME = "POLICY-PDP-PAP";
- public static final String TOPIC_INFRA = "dmaap";
- public static final String TOPIC_SERVER = "message-router";
+ public static final String TOPIC_NAME = "policy-pdp-pap";
+ public static final String TOPIC_INFRA = "kafka";
+ public static final String TOPIC_SERVER = "kafka:9092";
public static final List<TopicParameters> TOPIC_PARAMS =
Arrays.asList(getTopicParameters(TOPIC_NAME, TOPIC_INFRA, TOPIC_SERVER));
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestServerParametersTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestServerParametersTest.java
index 58bf98b3..9f03150e 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestServerParametersTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestServerParametersTest.java
@@ -1,8 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
-
+ * Modifications 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.
@@ -22,13 +21,14 @@
package org.onap.policy.common.endpoints.parameters;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
-import org.onap.policy.common.parameters.GroupValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.common.utils.coder.Coder;
import org.onap.policy.common.utils.coder.StandardCoder;
@@ -46,7 +46,7 @@ public class RestServerParametersTest {
public void test() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
- final GroupValidationResult validationResult = restServerParameters.validate();
+ final ValidationResult validationResult = restServerParameters.validate();
assertTrue(validationResult.isValid());
assertEquals(CommonTestData.REST_SERVER_HOST, restServerParameters.getHost());
assertEquals(CommonTestData.REST_SERVER_PORT, restServerParameters.getPort());
@@ -60,7 +60,7 @@ public class RestServerParametersTest {
public void testValidate() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
- final GroupValidationResult result = restServerParameters.validate();
+ final ValidationResult result = restServerParameters.validate();
assertNull(result.getResult());
assertTrue(result.isValid());
}
@@ -70,7 +70,7 @@ public class RestServerParametersTest {
String json = testData.getParameterGroupAsString(
"src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_valid.json");
RestServerParameters restServerParameters = coder.decode(json, RestServerParameters.class);
- final GroupValidationResult result = restServerParameters.validate();
+ final ValidationResult result = restServerParameters.validate();
assertNull(result.getResult());
assertTrue(result.isValid());
}
@@ -80,8 +80,8 @@ public class RestServerParametersTest {
String json = testData.getParameterGroupAsString(
"src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_invalid.json");
RestServerParameters restServerParameters = coder.decode(json, RestServerParameters.class);
- final GroupValidationResult result = restServerParameters.validate();
+ final ValidationResult result = restServerParameters.validate();
assertFalse(result.isValid());
- assertTrue(result.getResult().contains("parameter group has status INVALID"));
+ assertThat(result.getResult()).contains("item has status INVALID");
}
}
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroupTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroupTest.java
index 98b3d84a..62f86d41 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroupTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroupTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications 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.
@@ -33,7 +33,7 @@ import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
-import org.onap.policy.common.parameters.GroupValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.common.utils.coder.Coder;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
@@ -51,7 +51,7 @@ public class TopicParameterGroupTest {
public void test() throws CoderException {
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParameterGroupMap(false), TopicParameterGroup.class);
- final GroupValidationResult validationResult = topicParameterGroup.validate();
+ final ValidationResult validationResult = topicParameterGroup.validate();
assertTrue(validationResult.isValid());
assertEquals(CommonTestData.TOPIC_PARAMS, topicParameterGroup.getTopicSinks());
assertEquals(CommonTestData.TOPIC_PARAMS, topicParameterGroup.getTopicSources());
@@ -68,7 +68,7 @@ public class TopicParameterGroupTest {
public void testValidate() {
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParameterGroupMap(false), TopicParameterGroup.class);
- final GroupValidationResult result = topicParameterGroup.validate();
+ final ValidationResult result = topicParameterGroup.validate();
assertNull(result.getResult());
assertTrue(result.isValid());
}
@@ -78,7 +78,7 @@ public class TopicParameterGroupTest {
String json = testData.getParameterGroupAsString(
"src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_valid.json");
TopicParameterGroup topicParameterGroup = coder.decode(json, TopicParameterGroup.class);
- final GroupValidationResult result = topicParameterGroup.validate();
+ final ValidationResult result = topicParameterGroup.validate();
assertNull(result.getResult());
assertTrue(result.isValid());
}
@@ -88,7 +88,7 @@ public class TopicParameterGroupTest {
String json = testData.getParameterGroupAsString(
"src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_invalid.json");
TopicParameterGroup topicParameterGroup = coder.decode(json, TopicParameterGroup.class);
- final GroupValidationResult result = topicParameterGroup.validate();
+ final ValidationResult result = topicParameterGroup.validate();
assertFalse(result.isValid());
assertTrue(result.getResult().contains("INVALID"));
}
@@ -98,7 +98,7 @@ public class TopicParameterGroupTest {
String json = testData.getParameterGroupAsString(
"src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_missing_mandatory.json");
TopicParameterGroup topicParameterGroup = coder.decode(json, TopicParameterGroup.class);
- final GroupValidationResult result = topicParameterGroup.validate();
+ final ValidationResult result = topicParameterGroup.validate();
assertTrue(result.getResult().contains("Mandatory parameters are missing"));
assertFalse(result.isValid());
}
@@ -108,7 +108,7 @@ public class TopicParameterGroupTest {
String json = testData.getParameterGroupAsString(
"src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_all_params.json");
TopicParameterGroup topicParameterGroup = coder.decode(json, TopicParameterGroup.class);
- final GroupValidationResult result = topicParameterGroup.validate();
+ final ValidationResult result = topicParameterGroup.validate();
assertNull(result.getResult());
assertTrue(result.isValid());
assertTrue(checkIfAllParamsNotEmpty(topicParameterGroup.getTopicSinks()));
@@ -120,7 +120,7 @@ public class TopicParameterGroupTest {
* Any parameters added to @link TopicParameters or @link BusTopicParams must be added to
* TopicParameters_all_params.json.
*
- * @param topicParameters topic parameters
+ * @param topicParametersList list of topic parameters
* @return true if all parameters are not empty (if string) or true (if boolean)
* @throws Exception the exception
*/
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/report/TestHealthCheckReport.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/report/TestHealthCheckReport.java
index ebab616a..36970d74 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/report/TestHealthCheckReport.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/report/TestHealthCheckReport.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -27,7 +28,6 @@ import com.openpojo.validation.rule.impl.GetterMustExistRule;
import com.openpojo.validation.rule.impl.SetterMustExistRule;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
-
import org.junit.Test;
import org.onap.policy.common.utils.test.ToStringTester;
diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/PropertyUtilsTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/PropertyUtilsTest.java
index 048a3902..f8665a90 100644
--- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/PropertyUtilsTest.java
+++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/PropertyUtilsTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 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.
@@ -21,6 +22,7 @@
package org.onap.policy.common.endpoints.utils;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -76,11 +78,11 @@ public class PropertyUtilsTest {
@Test
public void testGetBoolean() {
- assertEquals(true, utils.getBoolean(".my-bool", false));
- assertEquals(false, utils.getBoolean(".my-bool2", true));
- assertEquals(true, utils.getBoolean(".empty-bool", true));
- assertEquals(false, utils.getBoolean(".invalid-bool", true));
- assertEquals(true, utils.getBoolean(".missing-bool", true));
+ assertTrue(utils.getBoolean(".my-bool", false));
+ assertFalse(utils.getBoolean(".my-bool2", true));
+ assertTrue(utils.getBoolean(".empty-bool", true));
+ assertFalse(utils.getBoolean(".invalid-bool", true));
+ assertTrue(utils.getBoolean(".missing-bool", true));
assertNull(invalidName);
assertNull(invalidValue);
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.json
index 9c8d78e5..48380426 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.json
@@ -11,29 +11,15 @@
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"useHttps" : true,
+ "allowTracing": false,
"allowSelfSignedCerts" : true,
"consumerGroup" : "${obj.topicSources[0].consumerGroup}",
"consumerInstance" : "${obj.topicSources[0].consumerInstance}",
"fetchTimeout" : 101,
"fetchLimit" : 100,
"topicCommInfrastructure" : "UEB"
- }, {
- "servers" : [ "my-server" ],
- "topic" : "dmaap-source",
- "effectiveTopic" : "my-effective-topic",
- "recentEvents" : [ ],
- "alive" : false,
- "locked" : false,
- "apiKey" : "my-api-key",
- "apiSecret" : "my-api-secret",
- "useHttps" : true,
- "allowSelfSignedCerts" : true,
- "consumerGroup" : "my-cons-group",
- "consumerInstance" : "my-cons-inst",
- "fetchTimeout" : 101,
- "fetchLimit" : 100,
- "topicCommInfrastructure" : "DMAAP"
- }, {
+ },
+ {
"servers" : [ "my-server" ],
"topic" : "noop-source",
"effectiveTopic" : "noop-source",
@@ -52,23 +38,12 @@
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"useHttps" : true,
+ "allowTracing": false,
"allowSelfSignedCerts" : true,
"topicCommInfrastructure" : "UEB",
"partitionKey" : "${obj.topicSinks[0].partitionKey}"
- }, {
- "servers" : [ "my-server" ],
- "topic" : "dmaap-sink",
- "effectiveTopic" : "my-effective-topic",
- "recentEvents" : [ ],
- "alive" : false,
- "locked" : false,
- "apiKey" : "my-api-key",
- "apiSecret" : "my-api-secret",
- "useHttps" : true,
- "allowSelfSignedCerts" : true,
- "topicCommInfrastructure" : "DMAAP",
- "partitionKey" : "my-partition"
- }, {
+ },
+ {
"servers" : [ "my-server" ],
"topic" : "noop-sink",
"effectiveTopic" : "noop-sink",
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.json
index dd0b8924..462278a4 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.json
@@ -8,6 +8,7 @@
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"useHttps" : true,
+ "allowTracing": true,
"allowSelfSignedCerts" : true,
"topicCommInfrastructure" : "NOOP"
}
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.json
index 8e39fddf..1f2fb55f 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.json
@@ -8,6 +8,7 @@
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"useHttps" : true,
+ "allowTracing": true,
"allowSelfSignedCerts" : true,
"topicCommInfrastructure" : "NOOP",
"partitionKey" : "my-partition"
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.json
deleted file mode 100644
index 2bed3347..00000000
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "servers" : [ "svra", "svrb" ],
- "topic" : "my-topic",
- "effectiveTopic" : "my-effective-topic",
- "recentEvents" : [ ],
- "alive" : false,
- "locked" : false,
- "apiKey" : "my-api-key",
- "apiSecret" : "my-api-secret",
- "useHttps" : true,
- "allowSelfSignedCerts" : true,
- "topicCommInfrastructure" : "DMAAP",
- "partitionKey" : "my-partition"
-}
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSinkTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSinkTest.json
new file mode 100644
index 00000000..dc1f1f75
--- /dev/null
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineKafkaTopicSinkTest.json
@@ -0,0 +1,20 @@
+{
+ "servers": [
+ "svra",
+ "svrb"
+ ],
+ "topic": "my-topic",
+ "effectiveTopic": "my-effective-topic",
+ "recentEvents": [],
+ "alive": false,
+ "locked": false,
+ "useHttps": false,
+ "allowTracing": false,
+ "topicCommInfrastructure": "KAFKA",
+ "partitionKey": "my-partition",
+ "additionalProps": {
+ "security.protocol": "SASL_PLAINTEXT",
+ "sasl.mechanism": "SCRAM-SHA-512",
+ "sasl.jaas.config": "org.apache.kafka.common.security.plain.PlainLoginModule required username=abc password=abc serviceName=kafka;"
+ }
+}
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.json
index e7419d88..6dda9b9e 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.json
@@ -8,6 +8,7 @@
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"useHttps" : true,
+ "allowTracing": true,
"allowSelfSignedCerts" : true,
"topicCommInfrastructure" : "UEB",
"partitionKey" : "my-partition"
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.json
index aeb233bc..305620c8 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.json
@@ -8,6 +8,7 @@
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"useHttps" : true,
+ "allowTracing": true,
"allowSelfSignedCerts" : true,
"consumerGroup" : "my-cons-group",
"consumerInstance" : "my-cons-inst",
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.json
deleted file mode 100644
index 07aa916a..00000000
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "servers" : [ "svra", "svrb" ],
- "topic" : "my-topic",
- "effectiveTopic" : "my-effective-topic",
- "recentEvents" : [ ],
- "alive" : false,
- "locked" : false,
- "apiKey" : "my-api-key",
- "apiSecret" : "my-api-secret",
- "useHttps" : true,
- "allowSelfSignedCerts" : true,
- "consumerGroup" : "my-cons-group",
- "consumerInstance" : "my-cons-inst",
- "fetchTimeout" : 101,
- "fetchLimit" : 100,
- "topicCommInfrastructure" : "DMAAP"
-}
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSourceTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSourceTest.json
new file mode 100644
index 00000000..a101d235
--- /dev/null
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedKafkaTopicSourceTest.json
@@ -0,0 +1,19 @@
+{
+ "servers": [
+ "localhost:9092",
+ "10.1.2.3:9092"
+ ],
+ "topic": "my-topic",
+ "effectiveTopic": "my-effective-topic",
+ "recentEvents": [],
+ "alive": false,
+ "locked": false,
+ "useHttps": false,
+ "allowTracing": false,
+ "topicCommInfrastructure": "KAFKA",
+ "additionalProps": {
+ "security.protocol": "SASL_PLAINTEXT",
+ "sasl.mechanism": "SCRAM-SHA-512",
+ "sasl.jaas.config": "org.apache.kafka.common.security.plain.PlainLoginModule required username=abc password=abc serviceName=kafka;"
+ }
+}
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.json
index 6a6e8f52..13ee6bc6 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.json
@@ -8,6 +8,7 @@
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"useHttps" : true,
+ "allowTracing": true,
"allowSelfSignedCerts" : true,
"consumerGroup" : "my-cons-group",
"consumerInstance" : "my-cons-inst",
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/http/server/internal/HttpServerTest.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/http/server/internal/HttpServerTest.json
index 5f4a7a90..aba9d682 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/http/server/internal/HttpServerTest.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/http/server/internal/HttpServerTest.json
@@ -1,7 +1,8 @@
{
- "aaf": false,
"alive": false,
"host": "localhost",
"name": "echo",
- "port": ${obj.port}
+ "port": ${obj.port},
+ "sniHostCheck":false,
+ "prometheus":false
}
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_invalid.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_invalid.json
index b106d721..a7455525 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_invalid.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_invalid.json
@@ -2,6 +2,5 @@
"port": 6969,
"userName": "username",
"password": "password",
- "https": true,
- "aaf": false
+ "https": true
} \ No newline at end of file
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_valid.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_valid.json
index 6c113056..61d793a8 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_valid.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_valid.json
@@ -3,6 +3,5 @@
"port": 6969,
"userName": "username",
"password": "password",
- "https": true,
- "aaf": false
+ "https": true
} \ No newline at end of file
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_all_params.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_all_params.json
index 7d9cce7b..89e464dd 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_all_params.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_all_params.json
@@ -1,13 +1,14 @@
{
"topicSources" : [ {
- "topic" : "POLICY-PDP-PAP1",
- "servers" : [ "message-router2, message-router3" ],
- "topicCommInfrastructure" : "dmaap",
+ "topic" : "policy-pdp-pap1",
+ "servers" : [ "kafka2, kafka3" ],
+ "topicCommInfrastructure" : "kafka",
"effectiveTopic" : "my-effective-topic",
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"port": 123,
"useHttps" : true,
+ "allowTracing": true,
"allowSelfSignedCerts" : true,
"consumerGroup" : "consumer group",
"consumerInstance" : "consumer instance",
@@ -29,14 +30,15 @@
"serializationProvider": "serializationProvider1"
}],
"topicSinks" : [ {
- "topic" : "POLICY-PDP-PAP1",
- "servers" : [ "message-router2, message-router3" ],
- "topicCommInfrastructure" : "dmaap",
+ "topic" : "policy-pdp-pap1",
+ "servers" : [ "kafka2, kafka3" ],
+ "topicCommInfrastructure" : "kafka",
"effectiveTopic" : "my-effective-topic",
"apiKey" : "my-api-key",
"apiSecret" : "my-api-secret",
"port": 123,
"useHttps" : true,
+ "allowTracing": true,
"allowSelfSignedCerts" : true,
"consumerGroup" : "consumer group",
"consumerInstance" : "consumer instance",
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_missing_mandatory.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_missing_mandatory.json
index 157d6086..216c11ec 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_missing_mandatory.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_missing_mandatory.json
@@ -1,12 +1,12 @@
{
"topicSources" : [ {
- "topic" : "POLICY-PDP-PAP1",
+ "topic" : "policy-pdp-pap1",
"servers" : [],
- "topicCommInfrastructure" : "dmaap"
+ "topicCommInfrastructure" : "kafka"
}],
"topicSinks" : [ {
- "topic" : "POLICY-PDP-PAP2",
- "servers" : [ "message-router1, message-router2" ],
- "topicCommInfrastructure" : "dmaap"
+ "topic" : "policy-pdp-pap2",
+ "servers" : [ "kafka1, kafka2" ],
+ "topicCommInfrastructure" : "kafka"
}]
} \ No newline at end of file
diff --git a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_valid.json b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_valid.json
index b89f1525..2603bfdc 100644
--- a/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_valid.json
+++ b/policy-endpoints/src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_valid.json
@@ -4,26 +4,26 @@
"servers" : [ "my-server" ],
"topicCommInfrastructure" : "ueb"
},{
- "topic" : "POLICY-PDP-PAP1",
- "servers" : [ "message-router1, message-router2" ],
- "topicCommInfrastructure" : "dmaap"
+ "topic" : "policy-pdp-pap1",
+ "servers" : [ "kafka1, kafka2" ],
+ "topicCommInfrastructure" : "kafka"
},{
- "topic" : "POLICY-PDP-PAP2",
- "servers" : [ "message-router2, message-router3" ],
- "topicCommInfrastructure" : "dmaap"
+ "topic" : "policy-pdp-pap2",
+ "servers" : [ "kafka2, kafka3" ],
+ "topicCommInfrastructure" : "kafka"
}],
"topicSinks" : [ {
"topic" : "ueb-sink",
"servers" : [ "my-server" ],
"topicCommInfrastructure" : "ueb"
},{
- "topic" : "POLICY-PDP-PAP2",
- "servers" : [ "message-router1, message-router2" ],
- "topicCommInfrastructure" : "dmaap"
+ "topic" : "policy-pdp-pap2",
+ "servers" : [ "kafka1, kafka2" ],
+ "topicCommInfrastructure" : "kafka"
},{
- "topic" : "POLICY-PDP-PAP3",
- "servers" : [ "message-router2, message-router3" ],
- "topicCommInfrastructure" : "dmaap",
+ "topic" : "policy-pdp-pap3",
+ "servers" : [ "kafka2, kafka3" ],
+ "topicCommInfrastructure" : "kafka",
"effectiveTopic":"effectiveTopic1",
"allowSelfSignedCerts":true
}]
diff --git a/policy-endpoints/src/test/resources/webapps/alt-root/index.html b/policy-endpoints/src/test/resources/webapps/alt-root/index.html
new file mode 100644
index 00000000..8ef757e6
--- /dev/null
+++ b/policy-endpoints/src/test/resources/webapps/alt-root/index.html
@@ -0,0 +1,30 @@
+<!--
+ ============LICENSE_START=======================================================
+ Copyright (C) 2020 Nordix Foundation.
+ Modifications Copyright (C) 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.
+
+ SPDX-License-Identifier: Apache-2.0
+ ============LICENSE_END=========================================================
+-->
+
+<?xml !DOCTYPE html>
+<html>
+ <head>
+ <title>Hello World</title>
+ </head>
+ <body>
+ <h4>Test Jetty Static Resources Alt-Root</h4>
+ </body>
+</html>
diff --git a/policy-endpoints/src/test/resources/webapps/root/index.html b/policy-endpoints/src/test/resources/webapps/root/index.html
new file mode 100644
index 00000000..35f61013
--- /dev/null
+++ b/policy-endpoints/src/test/resources/webapps/root/index.html
@@ -0,0 +1,30 @@
+<!--
+ ============LICENSE_START=======================================================
+ Copyright (C) 2020 Nordix Foundation.
+ Modifications Copyright (C) 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.
+
+ SPDX-License-Identifier: Apache-2.0
+ ============LICENSE_END=========================================================
+-->
+
+<?xml !DOCTYPE html>
+<html>
+ <head>
+ <title>Hello World</title>
+ </head>
+ <body>
+ <h4>Test Jetty Static Resources Root</h4>
+ </body>
+</html>
diff --git a/pom.xml b/pom.xml
index 8abf2acd..91766c34 100644
--- a/pom.xml
+++ b/pom.xml
@@ -2,8 +2,8 @@
============LICENSE_START=======================================================
ONAP policy
================================================================================
- Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2019 Nordix Foundation.
+ Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ Modifications Copyright (C) 2019-2020, 2022-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.
@@ -25,13 +25,13 @@
<parent>
<groupId>org.onap.policy.parent</groupId>
<artifactId>integration</artifactId>
- <version>3.1.1-SNAPSHOT</version>
+ <version>4.1.2-SNAPSHOT</version>
<relativePath />
</parent>
<groupId>org.onap.policy.common</groupId>
<artifactId>common-modules</artifactId>
- <version>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
<packaging>pom</packaging>
@@ -39,17 +39,12 @@
<description>Common Modules for Policy-Engine in both XACML and Drools flavor</description>
<properties>
- <!-- Project common build settings -->
-
<!-- Project path properties -->
<nexusproxy>https://nexus.onap.org</nexusproxy>
<sitePath>/content/sites/site/${project.groupId}/${project.artifactId}/${project.version}</sitePath>
<releases.path>content/repositories/releases/</releases.path>
<snapshots.path>content/repositories/snapshots/</snapshots.path>
<staging.path>content/repositories/staging/</staging.path>
-
- <!-- Project common dependency versions -->
- <commons-lang3.version>3.4</commons-lang3.version>
</properties>
<modules>
@@ -62,47 +57,110 @@
<module>integrity-audit</module>
<module>integrity-monitor</module>
<module>policy-endpoints</module>
+ <module>spring-utils</module>
</modules>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>${commons-lang3.version}</version>
- </dependency>
- </dependencies>
- </dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ </dependency>
+
+ <!-- Prometheus Client Libraries -->
+ <dependency>
+ <groupId>io.prometheus</groupId>
+ <artifactId>simpleclient</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.prometheus</groupId>
+ <artifactId>simpleclient_hotspot</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.prometheus</groupId>
+ <artifactId>simpleclient_servlet_jakarta</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.prometheus</groupId>
+ <artifactId>simpleclient_logback</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.google.re2j</groupId>
+ <artifactId>re2j</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>jakarta.xml.bind</groupId>
+ <artifactId>jakarta.xml.bind-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>jakarta.servlet</groupId>
+ <artifactId>jakarta.servlet-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>jakarta.validation</groupId>
+ <artifactId>jakarta.validation-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.swagger.core.v3</groupId>
+ <artifactId>swagger-jaxrs2-jakarta</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.swagger.core.v3</groupId>
+ <artifactId>swagger-jaxrs2-servlet-initializer-v2-jakarta</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate.orm</groupId>
+ <artifactId>hibernate-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core-jakarta</artifactId>
+ </dependency>
+
+ <!-- Test -->
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <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>
+ </dependencies>
<build>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <versionRange>2.17,)</versionRange>
- <goals>
- <goal>check</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -118,43 +176,7 @@
<dependency>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-webdav-jackrabbit</artifactId>
- <version>2.10</version>
- </dependency>
- </dependencies>
- </plugin>
- <plugin>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>onap-java-style</id>
- <goals>
- <goal>check</goal>
- </goals>
- <phase>process-sources</phase>
- <configuration>
- <!-- Use Google Java Style Guide:
- https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml
- with minor changes -->
- <configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
- <!-- <sourceDirectory> is needed so that checkstyle ignores the generated sources directory -->
- <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
- <includeResources>true</includeResources>
- <includeTestSourceDirectory>true</includeTestSourceDirectory>
- <includeTestResources>true</includeTestResources>
- <excludes>
- </excludes>
- <consoleOutput>true</consoleOutput>
- <failsOnViolation>true</failsOnViolation>
- <violationSeverity>warning</violationSeverity>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.onap.oparent</groupId>
- <artifactId>checkstyle</artifactId>
- <version>${oparent.version}</version>
- <scope>compile</scope>
+ <version>3.5.3</version>
</dependency>
</dependencies>
</plugin>
@@ -165,16 +187,14 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
- <version>2.10.4</version>
<configuration>
<failOnError>false</failOnError>
<doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
<docletArtifact>
<groupId>org.umlgraph</groupId>
<artifactId>umlgraph</artifactId>
- <version>5.6</version>
+ <version>5.6.6</version>
</docletArtifact>
- <additionalparam>-views</additionalparam>
<useStandardDocletOptions>true</useStandardDocletOptions>
</configuration>
</plugin>
diff --git a/releases/1.10.0.yaml b/releases/1.10.0.yaml
new file mode 100644
index 00000000..02096e1a
--- /dev/null
+++ b/releases/1.10.0.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.10.0'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/901/'
diff --git a/releases/1.10.1.yaml b/releases/1.10.1.yaml
new file mode 100644
index 00000000..bd5cdfb2
--- /dev/null
+++ b/releases/1.10.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.10.1'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1007/'
diff --git a/releases/1.10.2.yaml b/releases/1.10.2.yaml
new file mode 100644
index 00000000..51690dd6
--- /dev/null
+++ b/releases/1.10.2.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.10.2'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1042/'
diff --git a/releases/1.10.3.yaml b/releases/1.10.3.yaml
new file mode 100644
index 00000000..129d7f48
--- /dev/null
+++ b/releases/1.10.3.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.10.3'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1057/'
diff --git a/releases/1.11.0.yaml b/releases/1.11.0.yaml
new file mode 100644
index 00000000..e3bbef2b
--- /dev/null
+++ b/releases/1.11.0.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.11.0'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1205/'
diff --git a/releases/1.11.1.yaml b/releases/1.11.1.yaml
new file mode 100644
index 00000000..98aee0e0
--- /dev/null
+++ b/releases/1.11.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.11.1'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1234/'
diff --git a/releases/1.12.0.yaml b/releases/1.12.0.yaml
new file mode 100644
index 00000000..78f11adb
--- /dev/null
+++ b/releases/1.12.0.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.12.0'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1291/'
diff --git a/releases/1.12.1.yaml b/releases/1.12.1.yaml
new file mode 100644
index 00000000..2dc7b49e
--- /dev/null
+++ b/releases/1.12.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.12.1'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1367/'
diff --git a/releases/1.12.2.yaml b/releases/1.12.2.yaml
new file mode 100644
index 00000000..d98029d9
--- /dev/null
+++ b/releases/1.12.2.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.12.2'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1412/'
diff --git a/releases/1.6.2.yaml b/releases/1.6.2.yaml
new file mode 100644
index 00000000..9c967e8e
--- /dev/null
+++ b/releases/1.6.2.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.6.2'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/279/'
diff --git a/releases/1.6.3.yaml b/releases/1.6.3.yaml
new file mode 100644
index 00000000..54193bfe
--- /dev/null
+++ b/releases/1.6.3.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.6.3'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/301/'
diff --git a/releases/1.6.4.yaml b/releases/1.6.4.yaml
new file mode 100644
index 00000000..4a370640
--- /dev/null
+++ b/releases/1.6.4.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.6.4'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/306/'
diff --git a/releases/1.6.5.yaml b/releases/1.6.5.yaml
new file mode 100644
index 00000000..21b9bbbf
--- /dev/null
+++ b/releases/1.6.5.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.6.5'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/328/'
diff --git a/releases/1.7.0.yaml b/releases/1.7.0.yaml
new file mode 100644
index 00000000..4a9b4488
--- /dev/null
+++ b/releases/1.7.0.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.7.0'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/393/'
diff --git a/releases/1.7.1.yaml b/releases/1.7.1.yaml
new file mode 100644
index 00000000..663f2859
--- /dev/null
+++ b/releases/1.7.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.7.1'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/455/'
diff --git a/releases/1.8.0.yaml b/releases/1.8.0.yaml
new file mode 100644
index 00000000..30d882a8
--- /dev/null
+++ b/releases/1.8.0.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.8.0'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/624/'
diff --git a/releases/1.9.0.yaml b/releases/1.9.0.yaml
new file mode 100644
index 00000000..77c9e32a
--- /dev/null
+++ b/releases/1.9.0.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.9.0'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/831/'
diff --git a/releases/1.9.1.yaml b/releases/1.9.1.yaml
new file mode 100644
index 00000000..f7ee83e7
--- /dev/null
+++ b/releases/1.9.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.9.1'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/861/'
diff --git a/releases/2.0.1.yaml b/releases/2.0.1.yaml
new file mode 100644
index 00000000..96992133
--- /dev/null
+++ b/releases/2.0.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '2.0.1'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1414/'
diff --git a/releases/2.0.2.yaml b/releases/2.0.2.yaml
new file mode 100644
index 00000000..3d06fdd1
--- /dev/null
+++ b/releases/2.0.2.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '2.0.2'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1415/'
diff --git a/releases/2.1.0.yaml b/releases/2.1.0.yaml
new file mode 100644
index 00000000..af847d7e
--- /dev/null
+++ b/releases/2.1.0.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '2.1.0'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1416/'
diff --git a/releases/2.1.1.yaml b/releases/2.1.1.yaml
new file mode 100644
index 00000000..d53a2eee
--- /dev/null
+++ b/releases/2.1.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '2.1.1'
+project: 'policy-common'
+log_dir: 'policy-common-maven-stage-master/1417/'
diff --git a/spring-utils/pom.xml b/spring-utils/pom.xml
new file mode 100644
index 00000000..9728d65c
--- /dev/null
+++ b/spring-utils/pom.xml
@@ -0,0 +1,50 @@
+<!--
+ ============LICENSE_START=======================================================
+ ONAP policy
+ ================================================================================
+ Copyright (C) 2022 Bell Canada. 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=========================================================
+-->
+
+<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>2.1.2-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>spring-utils</artifactId>
+ <name>spring-utils</name>
+ <description>This artifact contains the common spring related utility classes to be used by multiple policy framework components.</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.onap.policy.common</groupId>
+ <artifactId>utils</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-web</artifactId>
+ </dependency>
+ </dependencies>
+
+</project> \ No newline at end of file
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java b/spring-utils/src/main/java/org/onap/policy/common/spring/utils/CustomImplicitNamingStrategy.java
index b568d7fb..d9a7e97c 100644
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java
+++ b/spring-utils/src/main/java/org/onap/policy/common/spring/utils/CustomImplicitNamingStrategy.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
+ * Copyright (C) 2022 Bell Canada. 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.
@@ -18,18 +19,21 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.common.parameters;
+package org.onap.policy.common.spring.utils;
-import static org.junit.Assert.assertTrue;
+import java.io.Serial;
+import org.hibernate.boot.model.naming.Identifier;
+import org.hibernate.boot.model.naming.ImplicitJoinColumnNameSource;
+import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
-import org.junit.Test;
-import org.onap.policy.common.parameters.testclasses.EmptyParameterGroup;
+public class CustomImplicitNamingStrategy extends ImplicitNamingStrategyJpaCompliantImpl {
-public class TestAbstractParameters {
+ @Serial
+ private static final long serialVersionUID = 8666774028328486896L;
- @Test
- public void testAbstractParameters() {
- final EmptyParameterGroup parameters = new EmptyParameterGroup("Empty Group");
- assertTrue(parameters.isValid());
+ @Override
+ public Identifier determineJoinColumnName(ImplicitJoinColumnNameSource source) {
+ String name = source.getReferencedColumnName().getText();
+ return toIdentifier(name, source.getBuildingContext());
}
}
diff --git a/spring-utils/src/main/java/org/onap/policy/common/spring/utils/YamlHttpMessageConverter.java b/spring-utils/src/main/java/org/onap/policy/common/spring/utils/YamlHttpMessageConverter.java
new file mode 100644
index 00000000..5fa02608
--- /dev/null
+++ b/spring-utils/src/main/java/org/onap/policy/common/spring/utils/YamlHttpMessageConverter.java
@@ -0,0 +1,108 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2022-2023 Bell Canada. 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.spring.utils;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.Writer;
+import java.lang.reflect.Type;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import org.onap.policy.common.utils.coder.YamlJsonTranslator;
+import org.springframework.core.GenericTypeResolver;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpInputMessage;
+import org.springframework.http.HttpOutputMessage;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.http.converter.HttpMessageNotWritableException;
+import org.springframework.lang.Nullable;
+
+/**
+ * Custom converter to marshal/unmarshall data structured with YAML media type.
+ */
+public class YamlHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
+
+ public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
+
+ private static final YamlJsonTranslator TRANSLATOR = new YamlJsonTranslator();
+
+ public YamlHttpMessageConverter() {
+ super(new MediaType("application", "yaml"));
+ setDefaultCharset(DEFAULT_CHARSET);
+ }
+
+ @Override
+ public final Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage)
+ throws IOException {
+ return readResolved(GenericTypeResolver.resolveType(type, contextClass), inputMessage);
+ }
+
+ @Override
+ protected final Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException {
+ return readResolved(clazz, inputMessage);
+ }
+
+ private Object readInternal(Type resolvedType, Reader reader) {
+ Class<?> clazz = (Class<?>) resolvedType;
+ return TRANSLATOR.fromYaml(reader, clazz);
+ }
+
+ @Override
+ protected final void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
+ throws IOException {
+ try (var writer = getWriter(outputMessage)) {
+ writeInternal(object, writer);
+ writer.flush();
+ } catch (Exception ex) {
+ throw new HttpMessageNotWritableException("Could not write YAML: " + ex.getMessage(), ex);
+ }
+ }
+
+ private void writeInternal(Object object, Writer writer) {
+ TRANSLATOR.toYaml(writer, object);
+ }
+
+ private Object readResolved(Type resolvedType, HttpInputMessage inputMessage) throws IOException {
+ try (var reader = getReader(inputMessage)) {
+ return readInternal(resolvedType, reader);
+ } catch (Exception ex) {
+ throw new HttpMessageNotReadableException("Could not read YAML: " + ex.getMessage(), ex, inputMessage);
+ }
+ }
+
+ private static Reader getReader(HttpInputMessage inputMessage) throws IOException {
+ return new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));
+ }
+
+ private static Writer getWriter(HttpOutputMessage outputMessage) throws IOException {
+ return new OutputStreamWriter(outputMessage.getBody(), getCharset(outputMessage.getHeaders()));
+ }
+
+ private static Charset getCharset(HttpHeaders headers) {
+ MediaType contentType = headers.getContentType();
+ Charset charset = (contentType == null ? null : contentType.getCharset());
+ return (charset != null ? charset : DEFAULT_CHARSET);
+ }
+}
diff --git a/utils-test/pom.xml b/utils-test/pom.xml
index 028a6f8d..6f72ec6b 100644
--- a/utils-test/pom.xml
+++ b/utils-test/pom.xml
@@ -2,7 +2,8 @@
============LICENSE_START=======================================================
ONAP Policy Engine - Common Modules
================================================================================
- Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2018-2021 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.
@@ -24,7 +25,7 @@
<parent>
<groupId>org.onap.policy.common</groupId>
<artifactId>common-modules</artifactId>
- <version>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
<artifactId>utils-test</artifactId>
@@ -33,47 +34,29 @@
<properties>
<powermock.version>2.0.4</powermock.version>
+ <!-- this whole module is testing code -->
+ <sonar.skip>true</sonar.skip>
</properties>
<dependencies>
<dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <scope>provided</scope>
+ <groupId>org.bouncycastle</groupId>
+ <artifactId>bcpkix-fips</artifactId>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-jexl3</artifactId>
</dependency>
<dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>utils</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>gson</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito2</artifactId>
- <scope>test</scope>
- </dependency>
+
+ <!-- from parent -->
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
- <version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -81,42 +64,10 @@
<artifactId>openpojo</artifactId>
<scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>compile</scope>
+ </dependency>
</dependencies>
-
- <build>
- <pluginManagement>
- <plugins>
- <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven
- build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.jacoco</groupId>
- <artifactId>
- jacoco-maven-plugin
- </artifactId>
- <versionRange>
- [0.7.1.201405082137,)
- </versionRange>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
</project>
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java b/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java
index f37f32a1..8276ea4c 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* policy-management
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -27,28 +28,28 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
+import com.google.re2j.Pattern;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.script.Bindings;
-import javax.script.ScriptEngine;
-import javax.script.ScriptEngineManager;
-import javax.script.ScriptException;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import org.apache.commons.jexl3.JexlBuilder;
+import org.apache.commons.jexl3.JexlContext;
+import org.apache.commons.jexl3.JexlEngine;
+import org.apache.commons.jexl3.MapContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utilities used to test encoding and decoding of Policy objects.
*/
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class GsonTestUtils {
private static final Logger logger = LoggerFactory.getLogger(GsonTestUtils.class);
@@ -61,11 +62,12 @@ public class GsonTestUtils {
/**
* Engine used to interpolate strings before they're compared.
*/
- private static ScriptEngine engineInstance = null;
+ private static JexlEngine engineInstance = null;
/**
* Used to encode and decode an object via gson.
*/
+ @Getter
private Gson gson;
/**
@@ -78,19 +80,6 @@ public class GsonTestUtils {
}
/**
- * Constructs the object.
- *
- * @param gson used to encode via gson
- */
- protected GsonTestUtils(Gson gson) {
- this.gson = gson;
- }
-
- public Gson getGson() {
- return gson;
- }
-
- /**
* Serializes and then deserializes an object using gson.
*
* @param object the object to be serialized
@@ -109,7 +98,6 @@ public class GsonTestUtils {
*
* @param object the object to be encoded
* @param expected the expected value
- * @throws Exception if the file cannot be read
*/
public void compareGson(Object object, Class<?> expected) {
compareGson(object, new File(expected.getSimpleName() + ".json"));
@@ -122,11 +110,10 @@ public class GsonTestUtils {
*
* @param object the object to be encoded
* @param expected the expected value
- * @throws Exception if the file cannot be read
*/
public void compareGson(Object object, File expected) {
// file is not required to have a full path - find it via getResource()
- URL url = object.getClass().getResource(expected.getName());
+ var url = object.getClass().getResource(expected.getName());
if (url == null) {
throw new JsonParseException(new FileNotFoundException(expected.getName()));
}
@@ -168,7 +155,11 @@ public class GsonTestUtils {
JsonElement gsonjo = reorder(gson.fromJson(sgson, JsonElement.class));
JsonElement expjo = reorder(expected);
- assertEquals(expjo.toString(), gsonjo.toString());
+ /*
+ * As this method is only used within junit tests, it is OK to use assert calls,
+ * thus sonar is disabled.
+ */
+ assertEquals(expjo.toString(), gsonjo.toString()); // NOSONAR
}
/**
@@ -178,7 +169,7 @@ public class GsonTestUtils {
* @throws IOException if an error occurs
*/
protected String readFile(File file) throws IOException {
- return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
+ return Files.readString(file.toPath());
}
@@ -192,42 +183,37 @@ public class GsonTestUtils {
* @return the text, after interpolating the script elements
*/
public String applyScripts(String text, Object object) {
- Matcher mat = SCRIPT_PAT.matcher(text);
+ var mat = SCRIPT_PAT.matcher(text);
if (!mat.find()) {
// contains no script elements - just return it as is
return text;
}
// bind the object to the variable, "obj"
- ScriptEngine eng = getEngine();
- Bindings bindings = eng.createBindings();
- bindings.put("obj", object);
+ JexlEngine eng = getEngine();
+ JexlContext context = new MapContext();
+ context.set("obj", object);
// work our way through the text, interpolating script elements as we go
- StringBuilder bldr = new StringBuilder();
- int ilast = 0;
+ var bldr = new StringBuilder();
+ var ilast = 0;
mat.reset();
while (mat.find(ilast)) {
// append segment that appears between last match and this
int inext = mat.start();
- bldr.append(text.substring(ilast, inext));
+ bldr.append(text, ilast, inext);
// next match begins after the current match
ilast = mat.end();
// interpolate the script
String script = mat.group(1);
- try {
- /*
- * Note: must use "eng" instead of "engineInstance" to ensure that we use
- * the same engine that's associated with the bindings.
- */
- Object result = eng.eval(script, bindings);
- bldr.append(result == null ? "null" : result.toString());
-
- } catch (ScriptException e) {
- throw new JsonParseException("cannot expand element: " + mat.group(), e);
- }
+ /*
+ * Note: must use "eng" instead of "engineInstance" to ensure that we use
+ * the same engine that's associated with the bindings.
+ */
+ Object result = eng.createExpression(script).evaluate(context);
+ bldr.append(result == null ? "null" : result.toString());
}
// append final segment
@@ -241,10 +227,10 @@ public class GsonTestUtils {
*
* @return the script engine
*/
- private static ScriptEngine getEngine() {
+ private static JexlEngine getEngine() {
if (engineInstance == null) {
// race condition here, but it's ok to overwrite with a new engine
- engineInstance = new ScriptEngineManager().getEngineByName("javascript");
+ engineInstance = new JexlBuilder().create();
}
return engineInstance;
@@ -270,11 +256,11 @@ public class GsonTestUtils {
* @return a new object, without the null items
*/
public JsonObject reorder(JsonObject jsonObj) {
- JsonObject newjo = new JsonObject();
+ var newjo = new JsonObject();
// sort the keys before copying to the new object
List<Entry<String, JsonElement>> sortedSet = new ArrayList<>(jsonObj.entrySet());
- Collections.sort(sortedSet, (left, right) -> left.getKey().compareTo(right.getKey()));
+ sortedSet.sort(Entry.comparingByKey());
for (Entry<String, JsonElement> ent : sortedSet) {
JsonElement val = ent.getValue();
@@ -296,7 +282,7 @@ public class GsonTestUtils {
* @return a new array, with null items removed from all elements
*/
public JsonArray reorder(JsonArray jsonArray) {
- JsonArray newarr = new JsonArray();
+ var newarr = new JsonArray();
for (JsonElement ent : jsonArray) {
newarr.add(reorder(ent));
}
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java b/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java
index 9ab26d32..f3e1418a 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -25,10 +25,13 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
/**
* Utilities for testing serialization and de-serialization of objects.
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Serializer {
/**
@@ -37,13 +40,6 @@ public class Serializer {
private static Factory factory = new Factory();
/**
- * The constructor.
- */
- private Serializer() {
-
- }
-
- /**
* Serializes an object into a byte array.
*
* @param object the object to be serialized
@@ -51,8 +47,8 @@ public class Serializer {
* @throws IOException if an error occurs
*/
public static <T> byte[] serialize(T object) throws IOException {
- try (ByteArrayOutputStream out = factory.makeByteArrayOutputStream()) {
- try (ObjectOutputStream oos = factory.makeObjectOutputStream(out)) {
+ try (var out = factory.makeByteArrayOutputStream()) {
+ try (var oos = factory.makeObjectOutputStream(out)) {
/*
* writeObject() is final and mockito can't mock final methods. In
* addition, powermock seemed to be having difficulty with the junit test
@@ -73,10 +69,10 @@ public class Serializer {
* @return the object that was de-serialized from the byte array
* @throws IOException if an error occurs
*/
- public static <T> T deserialize(Class<T> clazz, byte[] data) throws IOException {
+ private static <T> T deserialize(Class<T> clazz, byte[] data) throws IOException {
- try (ByteArrayInputStream in = factory.makeByteArrayInputStream(data);
- ObjectInputStream ois = factory.makeObjectInputStream(in)) {
+ try (var in = factory.makeByteArrayInputStream(data);
+ var ois = factory.makeObjectInputStream(in)) {
/*
* readObject() is final and mockito can't mock final methods. In addition,
* powermock seemed to be having difficulty with the junit test class as well,
@@ -133,7 +129,11 @@ public class Serializer {
*/
public Object readObject(ObjectInputStream ois) throws IOException {
try {
- return ois.readObject();
+ /*
+ * This class is only used by junit tests. In addition, it is only used by
+ * deserialize(), which has been made "private", thus disabling sonar.
+ */
+ return ois.readObject(); // NOSONAR
} catch (ClassNotFoundException e) {
throw new IOException(e);
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
new file mode 100644
index 00000000..0787872c
--- /dev/null
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java
@@ -0,0 +1,161 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.utils.security;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.file.Files;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import lombok.Getter;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralNames;
+import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.OperatorCreationException;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.onap.policy.common.utils.resources.ResourceUtils;
+
+/**
+ * Keystore, containing a self-signed certificate, valid for one day (see the argument to
+ * the "-valid" flag below). For use in junit tests.
+ */
+@Getter
+public class SelfSignedKeyStore {
+ public static final String KEYSTORE_PASSWORD = "Pol1cy_0nap";
+ public static final String PRIVATE_KEY_PASSWORD = KEYSTORE_PASSWORD;
+ public static final String RELATIVE_PATH = "target/test-classes/policy-keystore";
+
+ /**
+ * File containing subject-alternative names (i.e., list of servers that may use this
+ * keystore).
+ */
+ private static final String KEYSTORE_SAN = "keystore_san.txt";
+
+ private final String keystoreName;
+
+
+ /**
+ * 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, InterruptedException {
+ this(RELATIVE_PATH);
+ }
+
+ /**
+ * Generates the keystore, if it does not exist or if it's more than a few hours old.
+ *
+ * @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, InterruptedException {
+ keystoreName = System.getProperty("user.dir") + "/" + relativePath;
+
+ // use existing file if it isn't too old
+ var keystoreFile = new File(keystoreName);
+ if (keystoreFile.exists()) {
+ if (System.currentTimeMillis() < keystoreFile.lastModified()
+ + TimeUnit.MILLISECONDS.convert(5, TimeUnit.HOURS)) {
+ return;
+ }
+
+ Files.delete(keystoreFile.toPath());
+ }
+
+ /*
+ * Read the list of subject-alternative names, joining the lines with commas, and
+ * dropping the trailing comma.
+ */
+ String sanFileName = getKeystoreSanName();
+ var sanString = ResourceUtils.getResourceAsString(sanFileName);
+ if (sanString == null) {
+ throw new FileNotFoundException(sanFileName);
+ }
+
+ var sanArray = sanString.replace("DNS:", "").replace("\r", "").split("\n");
+ GeneralName[] nameArray = Arrays.stream(sanArray).map(name -> new GeneralName(GeneralName.dNSName, name))
+ .toList().toArray(new GeneralName[0]);
+ final var names = new GeneralNames(nameArray);
+
+ try (var ostr = new FileOutputStream(keystoreFile)) {
+ var keyPairGenerator = KeyPairGenerator.getInstance("RSA");
+ keyPairGenerator.initialize(2048);
+ final var keyPair = keyPairGenerator.generateKeyPair();
+
+ final long tcur = System.currentTimeMillis();
+
+ final var dn = new X500Name("C=US, O=ONAP, OU=OSAAF, OU=policy@policy.onap.org:DEV, CN=policy");
+ final var serial = BigInteger.valueOf(new SecureRandom().nextInt());
+ final var notBefore = new Date(tcur);
+ final var notAfter = new Date(tcur + TimeUnit.MILLISECONDS.convert(365, TimeUnit.DAYS));
+ final var pubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
+
+ ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA")
+ .setProvider(new BouncyCastleFipsProvider()).build(keyPair.getPrivate());
+
+ X509CertificateHolder holder = new X509v3CertificateBuilder(dn, serial, notBefore, notAfter, dn, pubKeyInfo)
+ .addExtension(Extension.subjectAlternativeName, false, names).build(signer);
+
+ var cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleFipsProvider())
+ .getCertificate(holder);
+ final Certificate[] chain = {cert};
+
+ var keystore = KeyStore.getInstance("PKCS12");
+ keystore.load(null, null);
+ keystore.setKeyEntry("policy@policy.onap.org", keyPair.getPrivate(), PRIVATE_KEY_PASSWORD.toCharArray(),
+ chain);
+
+ keystore.store(ostr, KEYSTORE_PASSWORD.toCharArray());
+
+ } catch (NoSuchAlgorithmException | OperatorCreationException | CertificateException | KeyStoreException e) {
+ throw new IOException("cannot create certificate", e);
+ }
+ }
+
+ // may be overridden by junit tests
+
+ protected String getKeystoreSanName() {
+ return KEYSTORE_SAN;
+ }
+}
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java
index f457dd21..1ab1f285 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java
@@ -2,7 +2,7 @@
* ============LICENSE_START====================================================
* Common Utils-Test
* =============================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -70,7 +70,7 @@ public class ExceptionsTester extends ThrowablesTester {
* if the constructed objects fail to pass various tests
*/
public <T extends Exception> int testAllException(final Class<T> claz) {
- int ncons = 0;
+ var ncons = 0;
ncons += testAllThrowable(claz);
ncons += testException(claz);
@@ -111,8 +111,8 @@ public class ExceptionsTester extends ThrowablesTester {
return 0;
}
- Exception cause = new Exception(EXPECTED_EXCEPTION_MSG);
- T ex = newInstance(cons, cause);
+ var cause = new Exception(EXPECTED_EXCEPTION_MSG);
+ var ex = newInstance(cons, cause);
assertNotNull(ex.toString());
assertEquals(ex.getMessage(), ex.getMessage());
@@ -151,8 +151,8 @@ public class ExceptionsTester extends ThrowablesTester {
return 0;
}
- Exception cause = new Exception(EXPECTED_EXCEPTION_MSG);
- T ex = newInstance(cons, "world", cause);
+ var cause = new Exception(EXPECTED_EXCEPTION_MSG);
+ var ex = newInstance(cons, "world", cause);
assertNotNull(ex.toString());
assertEquals("world", ex.getMessage());
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java
index 0fba944e..06ca8046 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java
@@ -2,7 +2,7 @@
* ============LICENSE_START====================================================
* Common Utils-Test
* =============================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -27,7 +27,6 @@ import static org.junit.Assert.assertTrue;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -40,7 +39,7 @@ public class ThrowablesTester {
private static Logger logger =
LoggerFactory.getLogger(ThrowablesTester.class);
- public static final String EXPECTED_EXCEPTION_MSG =
+ public static final String EXPECTED_EXCEPTION_MSG =
"expected exception";
private static final String EXPECTED_SUPPRESSED_EXCEPTION_MSG =
"expected suppressed exception";
@@ -74,7 +73,7 @@ public class ThrowablesTester {
*/
public final <T extends Throwable> int testAllThrowable(
final Class<T> claz) {
- int ncons = 0;
+ var ncons = 0;
ncons += testDefault(claz);
ncons += testString(claz);
@@ -113,7 +112,7 @@ public class ThrowablesTester {
return 0;
}
- T ex = newInstance(cons);
+ var ex = newInstance(cons);
assertNotNull(ex.toString());
assertNull(ex.getMessage());
@@ -152,7 +151,7 @@ public class ThrowablesTester {
return 0;
}
- T ex = newInstance(cons, "hello");
+ var ex = newInstance(cons, "hello");
assertNotNull(ex.toString());
assertEquals("hello", ex.getMessage());
@@ -192,7 +191,7 @@ public class ThrowablesTester {
return 0;
}
- T ex = newInstance(cons, CAUSE);
+ var ex = newInstance(cons, CAUSE);
assertEquals(ex.getMessage(), ex.getMessage());
assertNotNull(ex.toString());
@@ -232,7 +231,7 @@ public class ThrowablesTester {
return 0;
}
- T ex = newInstance(cons, "world", CAUSE);
+ var ex = newInstance(cons, "world", CAUSE);
assertNotNull(ex.toString());
assertEquals("world", ex.getMessage());
@@ -383,7 +382,7 @@ public class ThrowablesTester {
*/
public final <T extends Throwable> void testSuppressStack(
final Constructor<T> cons) {
- T ex = newInstance(cons, "yes,yes", CAUSE, true, true);
+ var ex = newInstance(cons, "yes,yes", CAUSE, true, true);
ex.addSuppressed(SUPPRESSED);
@@ -421,7 +420,7 @@ public class ThrowablesTester {
*/
public final <T extends Throwable> void testSuppressNoStack(
final Constructor<T> cons) {
- T ex = newInstance(cons, "yes,no", CAUSE, true, false);
+ var ex = newInstance(cons, "yes,no", CAUSE, true, false);
ex.addSuppressed(SUPPRESSED);
@@ -459,7 +458,7 @@ public class ThrowablesTester {
*/
public final <T extends Throwable> void testNoSuppressStack(
final Constructor<T> cons) {
- T ex = newInstance(cons, "no,yes", CAUSE, false, true);
+ var ex = newInstance(cons, "no,yes", CAUSE, false, true);
ex.addSuppressed(SUPPRESSED);
@@ -495,7 +494,7 @@ public class ThrowablesTester {
*/
public final <T extends Throwable> void testNoSuppressNoStack(
final Constructor<T> cons) {
- T ex = newInstance(cons, "no,no", CAUSE, false, false);
+ var ex = newInstance(cons, "no,no", CAUSE, false, false);
ex.addSuppressed(SUPPRESSED);
@@ -530,8 +529,7 @@ public class ThrowablesTester {
} catch (NoSuchMethodException | SecurityException e) {
// this constructor is not defined so nothing to test
- logger.debug("skipped test, no constructor for: "
- + claz + " due to: " + e);
+ logger.debug("skipped test, no constructor for: {}", claz, e);
return null;
}
}
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java
index f9ae39ac..ab09291c 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -29,7 +29,7 @@ import com.openpojo.reflection.PojoClass;
import com.openpojo.validation.affirm.Affirm;
import com.openpojo.validation.test.Tester;
import com.openpojo.validation.utils.ValidationHelper;
-
+import lombok.AllArgsConstructor;
import org.hamcrest.Matcher;
@@ -38,23 +38,19 @@ import org.hamcrest.Matcher;
*
* @author Ram Krishna Verma (ram.krishna.verma@est.tech)
*/
-@SuppressWarnings("rawtypes")
+@AllArgsConstructor
public class ToStringTester implements Tester {
- private final Matcher matcher;
+ private final Matcher<?> matcher;
public ToStringTester() {
matcher = anything();
}
- public ToStringTester(final Matcher matcher) {
- this.matcher = matcher;
- }
-
@SuppressWarnings("unchecked")
@Override
public void run(final PojoClass pojoClass) {
- final Class clazz = pojoClass.getClazz();
+ final Class<?> clazz = pojoClass.getClazz();
if (anyOf(matcher).matches(clazz)) {
final Object classInstance = ValidationHelper.getBasicInstance(pojoClass);
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java
index 19c50968..27d9fcc6 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java
@@ -2,7 +2,7 @@
* ============LICENSE_START====================================================
* Common Utils-Test
* =============================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -22,13 +22,13 @@ package org.onap.policy.common.utils.test.log.logback;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
+import com.google.re2j.Matcher;
+import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
/**
* This is an appender that is intended for use by JUnit tests that wish to
@@ -110,7 +110,7 @@ public class ExtractAppender extends AppenderBase<ILoggingEvent> {
}
for (Pattern p : patterns.values()) {
- Matcher matcher = p.matcher(msg);
+ var matcher = p.matcher(msg);
if (matcher.find()) {
addGroupMatch(matcher);
@@ -129,7 +129,7 @@ public class ExtractAppender extends AppenderBase<ILoggingEvent> {
private void addGroupMatch(final Matcher mat) {
int ngroups = mat.groupCount();
- for (int x = 1; x <= ngroups; ++x) {
+ for (var x = 1; x <= ngroups; ++x) {
String txt = mat.group(x);
if (txt != null) {
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java
index 79d2f226..04a9b3f6 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java
@@ -1,8 +1,8 @@
-/*
+/*--
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -20,8 +20,6 @@
package org.onap.policy.common.utils.time;
-import org.onap.policy.common.utils.time.TestTime;
-
/**
* Work item that runs periodically.
*/
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java
new file mode 100644
index 00000000..b29f7421
--- /dev/null
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java
@@ -0,0 +1,70 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.utils.time;
+
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.Executor;
+import lombok.Getter;
+
+/**
+ * Executor that will run tasks until the queue is empty or a maximum number of tasks have
+ * been executed. Doesn't actually run anything until {@link #runAll()} is invoked.
+ */
+public class PseudoExecutor implements Executor {
+
+ /**
+ * Tasks to be run.
+ */
+ @Getter
+ private final Queue<Runnable> tasks = new LinkedList<>();
+
+
+ /**
+ * Gets the queue length.
+ *
+ * @return the queue length
+ */
+ public int getQueueLength() {
+ return tasks.size();
+ }
+
+ @Override
+ public void execute(Runnable command) {
+ tasks.add(command);
+ }
+
+ /**
+ * Runs all tasks until the queue is empty or the maximum number of tasks have been
+ * reached.
+ *
+ * @param maxTasks maximum number of tasks to run
+ * @return {@code true} if the queue is empty, {@code false} if the maximum number of
+ * tasks have been reached before the queue was emptied
+ */
+ public boolean runAll(int maxTasks) {
+ for (var count = 0; count < maxTasks && !tasks.isEmpty(); ++count) {
+ tasks.remove().run();
+ }
+
+ return tasks.isEmpty();
+ }
+}
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java
index 4f9b32c9..71a24528 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -31,6 +31,7 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
+import lombok.Getter;
/**
* Scheduled executor service that uses {@link TestTimeMulti} to execute its tasks. Note:
@@ -48,6 +49,7 @@ public class PseudoScheduledExecutorService implements ScheduledExecutorService
* {@code True} if {@link #shutdown()} or {@link #shutdownNow()} has been called,
* {@code false} otherwise.
*/
+ @Getter
private boolean shutdown = false;
/**
@@ -80,13 +82,8 @@ public class PseudoScheduledExecutorService implements ScheduledExecutorService
}
@Override
- public boolean isShutdown() {
- return shutdown;
- }
-
- @Override
public boolean isTerminated() {
- return shutdown;
+ return isShutdown();
}
@Override
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java
index 6ce7bc04..34c756bb 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -39,6 +39,7 @@ class PseudoScheduledFuture<T> extends FutureTask<T> implements RunnableSchedule
/**
* {@code True} if this task is periodic, {@code false} otherwise.
*/
+ @Getter
private final boolean periodic;
/**
@@ -82,11 +83,6 @@ class PseudoScheduledFuture<T> extends FutureTask<T> implements RunnableSchedule
}
@Override
- public boolean isPeriodic() {
- return periodic;
- }
-
- @Override
public void run() {
if (isPeriodic()) {
super.runAndReset();
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java
index 54560316..67371bb9 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java
@@ -1,8 +1,8 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -23,7 +23,6 @@ package org.onap.policy.common.utils.time;
import java.util.concurrent.Future;
import lombok.AccessLevel;
import lombok.Getter;
-import org.onap.policy.common.utils.time.TestTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -80,7 +79,7 @@ class RunnableItem extends WorkItem {
try {
action.run();
} catch (RuntimeException e) {
- logger.warn("work item {} threw an exception {}", this, e);
+ logger.warn("work item {} threw an exception", this, e);
}
}
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java
index 420021f3..ace19160 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Common Utils-Test
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -22,12 +22,14 @@ package org.onap.policy.common.utils.time;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;
+import lombok.NoArgsConstructor;
/**
* "Current" time, when running junit tests. This is intended to be injected into classes
* under test, to replace their {@link CurrentTime} objects. When {@link #sleep(long)} is
* invoked, it simply advances the notion of "current" time and returns immediately.
*/
+@NoArgsConstructor
public class TestTime extends CurrentTime {
/**
@@ -35,14 +37,6 @@ public class TestTime extends CurrentTime {
*/
private AtomicLong tcur = new AtomicLong(System.currentTimeMillis());
- /**
- * Constructor.
- *
- */
- public TestTime() {
- super();
- }
-
@Override
public long getMillis() {
return tcur.get();
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java
index f52105ed..9e61eaa3 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -29,7 +29,6 @@ import java.util.PriorityQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
-import org.onap.policy.common.utils.time.TestTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -180,7 +179,7 @@ public class TestTimeMulti extends TestTime {
long realEnd = System.currentTimeMillis() + maxWaitMs;
while (System.currentTimeMillis() < realEnd) {
- if (condition.call()) {
+ if (Boolean.TRUE.equals(condition.call())) {
return;
}
@@ -190,11 +189,13 @@ public class TestTimeMulti extends TestTime {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("interrupted while waiting for condition", e);
- fail("interrupted while waiting for condition: " + e.getMessage());
+ // disabling sonar, as this is only used by junit tests
+ fail("interrupted while waiting for condition: " + e.getMessage()); // NOSONAR
} catch (Exception e) {
logger.error("condition evaluator threw an exception", e);
- fail("condition evaluator threw an exception: " + e.getMessage());
+ // disabling sonar, as this is only used by junit tests
+ fail("condition evaluator threw an exception: " + e.getMessage()); // NOSONAR
}
fail(NEVER_SATISFIED);
@@ -281,7 +282,7 @@ public class TestTimeMulti extends TestTime {
return;
}
- SleepItem item = new SleepItem(this, sleepMs, Thread.currentThread());
+ var item = new SleepItem(this, sleepMs, Thread.currentThread());
enqueue(item);
// wait for the item to fire
@@ -299,7 +300,7 @@ public class TestTimeMulti extends TestTime {
logger.info("enqueue work item {}", item);
synchronized (updateLock) {
queue.add(item);
- updateLock.notify();
+ updateLock.notifyAll();
}
}
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java
index af3d5d7e..cd690602 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java
@@ -1,8 +1,8 @@
-/*
+/*--
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -22,7 +22,6 @@ package org.onap.policy.common.utils.time;
import lombok.AccessLevel;
import lombok.Getter;
-import org.onap.policy.common.utils.time.TestTime;
/**
* Work item to be executed at some time.
diff --git a/utils-test/src/main/resources/keystore_san.txt b/utils-test/src/main/resources/keystore_san.txt
new file mode 100644
index 00000000..38428ea0
--- /dev/null
+++ b/utils-test/src/main/resources/keystore_san.txt
@@ -0,0 +1,15 @@
+DNS:policy
+DNS:drools
+DNS:drools.onap
+DNS:policy-apex-pdp
+DNS:policy-apex-pdp.onap
+DNS:policy-api
+DNS:policy-api.onap
+DNS:policy-distribution
+DNS:policy-distribution.onap
+DNS:policy-pap
+DNS:policy-pap.onap
+DNS:policy-xacml-pdp
+DNS:policy-xacml-pdp.onap
+DNS:policy.api.simpledemo.onap.org
+DNS:policy-sim
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java
index 35fea577..51522ec0 100644
--- a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -34,7 +35,9 @@ import com.google.gson.JsonParseException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
-import javax.script.ScriptException;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
import org.junit.Before;
import org.junit.Test;
@@ -76,10 +79,11 @@ public class GsonTestUtilsTest {
utils.compareGson(data, GsonTestUtilsTest.class);
// file not found
- assertThatThrownBy(() -> utils.compareGson(data,
- new File(GsonTestUtilsTest.class.getSimpleName() + "-NotFound.json")))
- .isInstanceOf(JsonParseException.class)
- .hasCauseInstanceOf(FileNotFoundException.class);
+ File file = new File(GsonTestUtilsTest.class.getSimpleName() + "-NotFound.json");
+
+ assertThatThrownBy(() -> utils.compareGson(data, file))
+ .isInstanceOf(JsonParseException.class)
+ .hasCauseInstanceOf(FileNotFoundException.class);
// force I/O error while reading file
GsonTestUtils utils2 = new GsonTestUtils() {
@@ -136,11 +140,7 @@ public class GsonTestUtilsTest {
data.setText(null);
result = utils.applyScripts("use ${obj.text} this", data);
assertEquals("use null this", result);
-
- assertThatThrownBy(() -> utils.applyScripts("use ${obj.text} this", null))
- .isInstanceOf(JsonParseException.class)
- .hasCauseInstanceOf(ScriptException.class)
- .hasMessage("cannot expand element: ${obj.text}");
+ assertEquals("use null this", utils.applyScripts("use ${obj.text} this", null));
}
@Test
@@ -224,29 +224,12 @@ public class GsonTestUtilsTest {
assertEquals("[300,{'objE':true,'objEStr':'obj-e-string'},false]".replace('\'', '"'), jsonEl.toString());
}
+ @Setter
+ @Getter
+ @ToString
public static class Data {
private int id;
private String text;
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getText() {
- return text;
- }
-
- public void setText(String text) {
- this.text = text;
- }
-
- @Override
- public String toString() {
- return "Data [id=" + id + ", text=" + text + "]";
- }
}
}
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java
index 95abd4db..203c78ec 100644
--- a/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
+ * Modificaitons 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.
@@ -41,7 +42,7 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.common.utils.io.Serializer.Factory;
-import org.powermock.reflect.Whitebox;
+import org.springframework.test.util.ReflectionTestUtils;
public class SerializerTest {
private static final String FACTORY = "factory";
@@ -53,12 +54,12 @@ public class SerializerTest {
@BeforeClass
public static void setUpBeforeClass() {
- saveFactory = Whitebox.getInternalState(Serializer.class, FACTORY);
+ saveFactory = (Factory) ReflectionTestUtils.getField(Serializer.class, FACTORY);
}
@AfterClass
public static void tearDownAfterClass() {
- Whitebox.setInternalState(Serializer.class, FACTORY, saveFactory);
+ ReflectionTestUtils.setField(Serializer.class, FACTORY, saveFactory);
}
@Before
@@ -80,7 +81,7 @@ public class SerializerTest {
byte[] data2 = Serializer.serialize(obj1);
assertEquals(Arrays.toString(data), Arrays.toString(data2));
- MyObject obj2 = Serializer.deserialize(MyObject.class, data);
+ MyObject obj2 = Serializer.roundTrip(obj1);
assertEquals(obj1.value, obj2.value);
}
@@ -210,16 +211,14 @@ public class SerializerTest {
}
});
- assertThatThrownBy(() -> Serializer.serialize(new MyObject(130))).isEqualTo(ex2);
+ assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(130))).isEqualTo(ex2);
}
@Test
public void testDeserialize() throws Exception {
MyObject obj1 = new MyObject(3);
- byte[] data = Serializer.serialize(obj1);
-
- MyObject obj2 = Serializer.deserialize(MyObject.class, data);
+ MyObject obj2 = Serializer.roundTrip(obj1);
assertEquals(obj1.value, obj2.value);
}
@@ -249,8 +248,7 @@ public class SerializerTest {
}
});
- byte[] data = Serializer.serialize(new MyObject(300));
- assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isEqualTo(ex);
+ assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(300))).isEqualTo(ex);
}
@Test
@@ -267,8 +265,7 @@ public class SerializerTest {
}
});
- byte[] data = Serializer.serialize(new MyObject(310));
- assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isEqualTo(ex);
+ assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(310))).isEqualTo(ex);
}
@Test
@@ -287,9 +284,20 @@ public class SerializerTest {
*/
text = text.replace("MyObject", "AnObject");
- byte[] data = text.getBytes(binary);
+ byte[] data2 = text.getBytes(binary);
+
+ /*
+ * Use a factory that returns a byte array for "data2" instead of the real "data".
+ */
+ setFactory(new Factory() {
+ @Override
+ public ByteArrayInputStream makeByteArrayInputStream(byte[] data) {
+ // read from "data2" instead of "data"
+ return super.makeByteArrayInputStream(data2);
+ }
+ });
- assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isInstanceOf(IOException.class)
+ assertThatThrownBy(() -> Serializer.roundTrip(obj1)).isInstanceOf(IOException.class)
.hasCauseInstanceOf(ClassNotFoundException.class);
}
@@ -313,8 +321,7 @@ public class SerializerTest {
}
});
- byte[] data = Serializer.serialize(new MyObject(320));
- assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isEqualTo(ex);
+ assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(320))).isEqualTo(ex);
}
@Test
@@ -348,8 +355,7 @@ public class SerializerTest {
}
});
- byte[] data = Serializer.serialize(new MyObject(330));
- assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isEqualTo(ex2);
+ assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(330))).isEqualTo(ex2);
}
@Test
@@ -371,7 +377,7 @@ public class SerializerTest {
* @param factory new factory to be set
*/
private void setFactory(Factory factory) {
- Whitebox.setInternalState(Serializer.class, FACTORY, factory);
+ ReflectionTestUtils.setField(Serializer.class, FACTORY, factory);
}
/**
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java
new file mode 100644
index 00000000..27bceacf
--- /dev/null
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java
@@ -0,0 +1,151 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.utils.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class SelfSignedKeyStoreTest {
+ private static final String USER_DIR_PROP = "user.dir";
+
+ private static String saveUserDir;
+ private static String defaultName;
+ private static File defaultKeystore;
+
+
+ /**
+ * Saves the user.dir property and initializes static fields.
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ saveUserDir = System.getProperty(USER_DIR_PROP);
+ defaultName = saveUserDir + "/" + SelfSignedKeyStore.RELATIVE_PATH;
+ defaultKeystore = new File(defaultName);
+ }
+
+ @Before
+ public void setUp() {
+ System.setProperty(USER_DIR_PROP, saveUserDir);
+ delete(defaultKeystore);
+ }
+
+ @Test
+ public void testSelfSignedKeyStore() throws Exception {
+ SelfSignedKeyStore ks = new SelfSignedKeyStore();
+
+ assertThat(ks.getKeystoreName()).isEqualTo(defaultName);
+ assertThat(defaultKeystore).exists();
+ }
+
+ @Test
+ public void testSelfSignedKeyStoreString() throws IOException, InterruptedException {
+ String relName = "target/my-keystore";
+ String altName = saveUserDir + "/" + relName;
+ File altFile = new File(altName);
+
+ delete(altFile);
+
+ SelfSignedKeyStore ks = new SelfSignedKeyStore(relName);
+
+ assertThat(ks.getKeystoreName()).isEqualTo(altName);
+ assertThat(altFile).exists();
+ }
+
+ /**
+ * Tests the constructor, when the keystore already exists.
+ */
+ @Test
+ public void testSelfSignedKeyStoreStringExists() throws Exception {
+ new SelfSignedKeyStore();
+ assertThat(defaultKeystore).exists();
+
+ // change the timestamp on the keystore so it's a little old, but not too old
+ defaultKeystore.setLastModified(
+ System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(10, TimeUnit.MINUTES));
+ long tcurrent = defaultKeystore.lastModified();
+
+ // this should not recreate the keystore, thus the timestamp should be unchanged
+ new SelfSignedKeyStore();
+ assertThat(defaultKeystore.lastModified()).isEqualTo(tcurrent);
+
+ // change the timestamp on the keystore so it's too old
+ defaultKeystore.setLastModified(
+ System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(1000, TimeUnit.HOURS));
+ tcurrent = defaultKeystore.lastModified();
+
+ // this should recreate the keystore
+ new SelfSignedKeyStore();
+ assertThat(defaultKeystore.lastModified()).isGreaterThan(tcurrent);
+ }
+
+ /**
+ * Tests the constructor, when the SAN file is not found.
+ */
+ @Test
+ public void testSelfSignedKeyStoreStringNoSanFile() throws Exception {
+ assertThatThrownBy(() -> new SelfSignedKeyStore() {
+ @Override
+ protected String getKeystoreSanName() {
+ return "unknown/san/file.txt";
+ }
+ }).isInstanceOf(FileNotFoundException.class).hasMessageContaining("file.txt");
+ }
+
+ /**
+ * Tests the constructor, when write fails.
+ */
+ @Test
+ public void testSelfSignedKeyStoreStringWriteFailure() throws Exception {
+ assertThatThrownBy(() -> new SelfSignedKeyStore("target/unknown/path/to/keystore"))
+ .isInstanceOf(IOException.class);
+ }
+
+ @Test
+ public void testGetKeystoreName() throws Exception {
+ String relpath = SelfSignedKeyStore.RELATIVE_PATH;
+
+ // append the first part of the relative path to user.dir
+ System.setProperty(USER_DIR_PROP, saveUserDir + "/" + relpath.substring(0, relpath.indexOf('/')));
+
+ // create a keystore using the remaining components of the relative path
+ SelfSignedKeyStore ks = new SelfSignedKeyStore(relpath.substring(relpath.indexOf('/') + 1));
+
+ assertThat(ks.getKeystoreName()).isEqualTo(defaultName);
+ assertThat(defaultKeystore).exists();
+
+ // try again using the original relative path - should fail, as it's now deeper
+ assertThatThrownBy(() -> new SelfSignedKeyStore(relpath)).isInstanceOf(IOException.class);
+ }
+
+ private static void delete(File file) {
+ if (file.exists()) {
+ assertThat(file.delete()).isTrue();
+ }
+ }
+}
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java
index cd6edf76..4c2237fc 100644
--- a/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Common Utils-Test
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -26,13 +26,11 @@ import static org.junit.Assert.assertFalse;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
-
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -376,21 +374,6 @@ public class ExtractAppenderTest {
// create some threads to get extractions
addThread(tend, err, xtxt -> app.getExtracted());
- // create some threads to clear extractions
- addThread(tend, err, xtxt -> {
- app.clearExtractions();
-
- // don't want to clear the list too frequently
- // so sleep a bit in between
- try {
- Thread.sleep(10L + Integer.valueOf(xtxt));
-
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw e;
- }
- });
-
/*
* Finally ready to start.
*/
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java
new file mode 100644
index 00000000..0046f791
--- /dev/null
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java
@@ -0,0 +1,60 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.utils.time;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class PseudoExecutorTest {
+ private int invoked;
+ private PseudoExecutor executor;
+
+ @Before
+ public void setUp() {
+ invoked = 0;
+ executor = new PseudoExecutor();
+ }
+
+ @Test
+ public void test() {
+ assertEquals(0, executor.getQueueLength());
+ assertEquals(0, executor.getTasks().size());
+ assertTrue(executor.runAll(0));
+
+ executor.execute(() -> invoked++);
+ executor.execute(() -> invoked++);
+ executor.execute(() -> invoked++);
+ assertEquals(3, executor.getTasks().size());
+ assertEquals(3, executor.getQueueLength());
+
+ assertFalse(executor.runAll(2));
+ assertEquals(2, invoked);
+ assertEquals(1, executor.getQueueLength());
+
+ assertTrue(executor.runAll(2));
+ assertEquals(3, invoked);
+ assertEquals(0, executor.getQueueLength());
+ }
+}
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java
index 70820c44..745e989f 100644
--- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -27,6 +27,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Collections;
+import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
@@ -37,6 +38,7 @@ import org.junit.Test;
public class PseudoScheduledExecutorServiceTest {
private static final long DELAY_MS = 100L;
private static final long PERIOD_MS = 200L;
+ private static final List<Callable<Object>> EMPTY_CALLABLES = Collections.emptyList();
private int ran;
private int called;
@@ -135,25 +137,25 @@ public class PseudoScheduledExecutorServiceTest {
@Test
public void testInvokeAllCollectionOfQextendsCallableOfT() {
- assertThatThrownBy(() -> svc.invokeAll(Collections.emptyList()))
+ assertThatThrownBy(() -> svc.invokeAll(EMPTY_CALLABLES))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void testInvokeAllCollectionOfQextendsCallableOfTLongTimeUnit() {
- assertThatThrownBy(() -> svc.invokeAll(Collections.emptyList(), 1, TimeUnit.MILLISECONDS))
+ assertThatThrownBy(() -> svc.invokeAll(EMPTY_CALLABLES, 1, TimeUnit.MILLISECONDS))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void testInvokeAnyCollectionOfQextendsCallableOfT() {
- assertThatThrownBy(() -> svc.invokeAny(Collections.emptyList()))
+ assertThatThrownBy(() -> svc.invokeAny(EMPTY_CALLABLES))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void testInvokeAnyCollectionOfQextendsCallableOfTLongTimeUnit() {
- assertThatThrownBy(() -> svc.invokeAny(Collections.emptyList(), 1, TimeUnit.MILLISECONDS))
+ assertThatThrownBy(() -> svc.invokeAny(EMPTY_CALLABLES, 1, TimeUnit.MILLISECONDS))
.isInstanceOf(UnsupportedOperationException.class);
}
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java
index e23bbd29..248edf61 100644
--- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -31,9 +31,11 @@ import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
+import org.mockito.junit.MockitoJUnitRunner;
+@RunWith(MockitoJUnitRunner.class)
public class PseudoScheduledFutureTest {
private static final long DELAY_MS = 1000L;
@@ -49,8 +51,6 @@ public class PseudoScheduledFutureTest {
*/
@Before
public void setUp() {
- MockitoAnnotations.initMocks(this);
-
when(work.getDelay()).thenReturn(DELAY_MS);
count = 0;
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java
index 49710538..d7316c1f 100644
--- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -83,8 +83,9 @@ public class PseudoTimerTest {
@Test
public void testScheduleTimerTaskDate() {
- assertThatThrownBy(() -> timer.schedule(new MyTask(), new Date()))
- .isInstanceOf(UnsupportedOperationException.class);
+ MyTask task = new MyTask();
+ Date curdate = new Date();
+ assertThatThrownBy(() -> timer.schedule(task, curdate)).isInstanceOf(UnsupportedOperationException.class);
}
@Test
@@ -105,8 +106,9 @@ public class PseudoTimerTest {
@Test
public void testScheduleTimerTaskDateLong() {
- assertThatThrownBy(() -> timer.schedule(new MyTask(), new Date(), 1L))
- .isInstanceOf(UnsupportedOperationException.class);
+ MyTask task = new MyTask();
+ Date curdate = new Date();
+ assertThatThrownBy(() -> timer.schedule(task, curdate, 1L)).isInstanceOf(UnsupportedOperationException.class);
}
@Test
@@ -127,7 +129,9 @@ public class PseudoTimerTest {
@Test
public void testScheduleAtFixedRateTimerTaskDateLong() {
- assertThatThrownBy(() -> timer.scheduleAtFixedRate(new MyTask(), new Date(), 1L))
+ MyTask task = new MyTask();
+ Date curdate = new Date();
+ assertThatThrownBy(() -> timer.scheduleAtFixedRate(task, curdate, 1L))
.isInstanceOf(UnsupportedOperationException.class);
}
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java
index 4e6f92b5..d2fc8d58 100644
--- a/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java
+++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.utils.time;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -88,7 +89,7 @@ public class WorkItemTest {
@Test
public void testFire() {
// ensure no exception is thrown
- item.fire();
+ assertThatCode(() -> item.fire()).doesNotThrowAnyException();
}
@Test
diff --git a/utils/pom.xml b/utils/pom.xml
index ef059147..338d5235 100644
--- a/utils/pom.xml
+++ b/utils/pom.xml
@@ -2,14 +2,15 @@
============LICENSE_START=======================================================
ONAP Policy Engine - Common Modules
================================================================================
- Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2018-2021 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.
@@ -19,13 +20,13 @@
-->
<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">
+ 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>1.6.2-SNAPSHOT</version>
+ <version>2.1.2-SNAPSHOT</version>
</parent>
<artifactId>utils</artifactId>
@@ -34,19 +35,6 @@
<dependencies>
<dependency>
- <groupId>javax.xml.bind</groupId>
- <artifactId>jaxb-api</artifactId>
- <version>${version.javax.bind}</version>
- </dependency>
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
- <dependency>
<groupId>org.onap.policy.common</groupId>
<artifactId>capabilities</artifactId>
<version>${project.version}</version>
@@ -57,98 +45,27 @@
<version>${project.version}</version>
</dependency>
<dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <groupId>com.worldturner.medeia</groupId>
+ <artifactId>medeia-validator-gson</artifactId>
</dependency>
<dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>javax.persistence</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <scope>provided</scope>
+ <groupId>commons-net</groupId>
+ <artifactId>commons-net</artifactId>
</dependency>
+
+ <!-- from parent -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito2</artifactId>
- <scope>test</scope>
+ <groupId>commons-cli</groupId>
+ <artifactId>commons-cli</artifactId>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.openpojo</groupId>
- <artifactId>openpojo</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-core</artifactId>
- <version>1.3</version>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
</dependency>
</dependencies>
-
- <build>
- <pluginManagement>
- <plugins>
- <!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.jacoco</groupId>
- <artifactId>
- jacoco-maven-plugin
- </artifactId>
- <versionRange>
- [0.7.1.201405082137,)
- </versionRange>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
</project>
diff --git a/utils/src/main/java/org/onap/policy/common/utils/cmd/CommandLineArgumentsHandler.java b/utils/src/main/java/org/onap/policy/common/utils/cmd/CommandLineArgumentsHandler.java
new file mode 100644
index 00000000..970cebfe
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/cmd/CommandLineArgumentsHandler.java
@@ -0,0 +1,273 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.utils.cmd;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import lombok.Getter;
+import lombok.Setter;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.lang3.StringUtils;
+import org.onap.policy.common.utils.resources.ResourceUtils;
+
+/**
+ * Class for command line common processing.
+ *
+ * @author Adheli Tavares (adheli.tavares@est.tech)
+ *
+ */
+public class CommandLineArgumentsHandler {
+ private static final String FILE_MESSAGE_PREAMBLE = " file \"";
+ private static final int HELP_LINE_LENGTH = 120;
+
+ private final Options options;
+
+ private final String helpClassName;
+ private final String component;
+
+ @Getter
+ @Setter
+ private String configurationFilePath = null;
+
+ @Getter
+ @Setter
+ private String propertyFilePath = null;
+
+ @Getter
+ private CommandLine commandLine = null;
+
+ /**
+ * Construct the options with default values for the CLI editor.
+ */
+ protected CommandLineArgumentsHandler(String helpClassName, String component) {
+ this.helpClassName = helpClassName;
+ this.component = component;
+ //@formatter:off
+ options = new Options();
+ options.addOption(Option.builder("h")
+ .longOpt("help")
+ .desc("outputs the usage of this command")
+ .required(false)
+ .type(Boolean.class)
+ .build());
+ options.addOption(Option.builder("v")
+ .longOpt("version")
+ .desc("outputs the version of " + this.component)
+ .required(false)
+ .type(Boolean.class)
+ .build());
+ options.addOption(Option.builder("c")
+ .longOpt("config-file")
+ .desc(String.format("the full path to the configuration file to use, "
+ + "the configuration file must be a Json file containing the %s parameters", this.component))
+ .hasArg().argName("CONFIG_FILE")
+ .required(false)
+ .type(String.class)
+ .build());
+ //@formatter:on
+ }
+
+ /**
+ * Construct the options for the CLI editor with extra options.
+ */
+ public CommandLineArgumentsHandler(String helpClassName, String component, Option... customOptions) {
+ this(helpClassName, component);
+ if (customOptions != null) {
+ for (Option option : customOptions) {
+ options.addOption(option);
+ }
+ }
+ }
+
+ /**
+ * Construct the options with brand-new options for the CLI editor.
+ */
+ public CommandLineArgumentsHandler(String helpClassName, String component, Options options) {
+ this.options = options;
+ this.helpClassName = helpClassName;
+ this.component = component;
+ }
+
+ /**
+ * Parse the command line options.
+ *
+ * @param args The command line arguments
+ * @return a string with a message for help and version, or null if there is no message
+ * @throws CommandLineException on command argument errors
+ */
+ public String parse(final String[] args) throws CommandLineException {
+ // Clear all our arguments
+ setConfigurationFilePath(null);
+ setPropertyFilePath(null);
+
+ try {
+ commandLine = new DefaultParser().parse(options, args);
+ } catch (final ParseException | NullPointerException e) {
+ throw new CommandLineException("invalid command line arguments specified", e);
+ }
+
+ // Arguments left over after Commons CLI does its stuff
+ final String[] remainingArgs = removeEmptyValues(commandLine.getArgs());
+
+ if (remainingArgs.length > 0) {
+ throw new CommandLineException("too many command line arguments specified: " + Arrays.toString(args));
+ }
+
+ if (commandLine.hasOption('h')) {
+ return help();
+ }
+
+ if (commandLine.hasOption('v')) {
+ return version();
+ }
+
+ if (commandLine.hasOption('c')) {
+ setConfigurationFilePath(commandLine.getOptionValue('c'));
+ }
+
+ if (commandLine.hasOption('p')) {
+ setPropertyFilePath(commandLine.getOptionValue('p'));
+ }
+
+ return null;
+ }
+
+ /**
+ * Validate the command line options.
+ *
+ * @throws CommandLineException on command argument validation errors
+ */
+ public void validate() throws CommandLineException {
+ validateReadableFile(this.component + " configuration", configurationFilePath);
+ }
+
+ /**
+ * Print version information for policy distribution.
+ *
+ * @return the version string
+ */
+ public String version() {
+ return ResourceUtils.getResourceAsString("version.txt");
+ }
+
+ /**
+ * Print help information for policy distribution.
+ *
+ * @return the help string
+ */
+ public String help() {
+ final var helpFormatter = new HelpFormatter();
+ final var stringWriter = new StringWriter();
+ final var printWriter = new PrintWriter(stringWriter);
+ final String cmdLineSyntax = this.helpClassName + " [options...]";
+
+ helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, cmdLineSyntax, "options", options, 0, 0, "");
+
+ return stringWriter.toString();
+ }
+
+ /**
+ * Gets the full expanded configuration file path.
+ *
+ * @return the configuration file path
+ */
+ public String getFullConfigurationFilePath() {
+ return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
+ }
+
+ /**
+ * Check set configuration file path.
+ *
+ * @return true, if check set configuration file path
+ */
+ public boolean checkSetConfigurationFilePath() {
+ return StringUtils.isNotBlank(getConfigurationFilePath());
+ }
+
+ /**
+ * Gets the full expanded property file path.
+ *
+ * @return the property file path
+ */
+ public String getFullPropertyFilePath() {
+ return ResourceUtils.getFilePath4Resource(getPropertyFilePath());
+ }
+
+ /**
+ * Check set property file path.
+ *
+ * @return true, if check set property file path
+ */
+ public boolean checkSetPropertyFilePath() {
+ return StringUtils.isNotBlank(getPropertyFilePath());
+ }
+
+ /**
+ * Validate readable file.
+ *
+ * @param fileTag the file tag
+ * @param fileName the file name
+ * @throws CommandLineException on the file name passed as a parameter
+ */
+ protected void validateReadableFile(final String fileTag, final String fileName) throws CommandLineException {
+ if (StringUtils.isBlank(fileName)) {
+ throw new CommandLineException(fileTag + " file was not specified as an argument");
+ }
+
+ // The file name refers to a resource on the local file system
+ final var fileUrl = ResourceUtils.getUrl4Resource(fileName);
+ if (fileUrl == null) {
+ throw new CommandLineException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
+ }
+
+ try {
+ var path = Path.of(fileUrl.toURI());
+ if (!Files.isRegularFile(path)) {
+ throw new CommandLineException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file");
+ }
+ if (!Files.isReadable(path)) {
+ throw new CommandLineException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is unreadable");
+ }
+ } catch (URISyntaxException e) {
+ throw new CommandLineException("Error parsing " + fileUrl.toString(), e);
+ }
+
+ }
+
+ /**
+ * Checks if args has any null or empty value after parsing.
+ *
+ * @param args remaining args from CLI parse.
+ */
+ private String[] removeEmptyValues(String[] args) {
+ return Arrays.stream(args).filter(StringUtils::isNotBlank).toArray(String[]::new);
+ }
+}
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java b/utils/src/main/java/org/onap/policy/common/utils/cmd/CommandLineException.java
index 1a640023..9cdf3d37 100644
--- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/cmd/CommandLineException.java
@@ -1,7 +1,6 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property.
+ * Copyright (C) 2021 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,23 +18,40 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.common.parameters.testclasses;
+package org.onap.policy.common.utils.cmd;
-import java.util.Map;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
+import java.io.Serial;
-public class ParameterGroupWithNullMapValue extends ParameterGroupImpl {
- private Map<String, Integer> nullMap = null;
+/**
+ * Exception used for CommandLineArguments class.
+ *
+ * @author Adheli Tavares (adheli.tavares@est.tech)
+ *
+ */
+public class CommandLineException extends Exception {
+
+ /**
+ * Generated serialVersionUID.
+ */
+ @Serial
+ private static final long serialVersionUID = -1200607308084606425L;
/**
- * Create a test parameter group.
- * @param name the parameter group name
+ * Instantiates a new exception with a message.
+ *
+ * @param message the message
*/
- public ParameterGroupWithNullMapValue(final String name) {
- super(name);
+ public CommandLineException(final String message) {
+ super(message);
}
- public Map<String, Integer> getNullMap() {
- return nullMap;
+ /**
+ * Instantiates a new exception with a message and a caused by exception.
+ *
+ * @param message the message
+ * @param exp the exception that caused this exception to be thrown
+ */
+ public CommandLineException(final String message, final Exception exp) {
+ super(message, exp);
}
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/Coder.java b/utils/src/main/java/org/onap/policy/common/utils/coder/Coder.java
index bb51f2b9..3049a5c2 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/coder/Coder.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/coder/Coder.java
@@ -1,8 +1,8 @@
/*
* ============LICENSE_START=======================================================
- * ONAP PAP
+ * ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -32,6 +32,37 @@ import java.io.Writer;
public interface Coder {
/**
+ * Converts an object/POJO to an object of the given type.
+ *
+ * @param <T> desired type
+ * @param source source object
+ * @param clazz class of the desired object type
+ * @return the converted object
+ * @throws CoderException if an error occurs
+ */
+ default <S, T> T convert(S source, Class<T> clazz) throws CoderException {
+ if (source == null) {
+ return null;
+
+ } else if (clazz == source.getClass()) {
+ // same class - just cast it
+ return clazz.cast(source);
+
+ } else if (clazz == String.class) {
+ // target is a string - just encode the source
+ return (clazz.cast(encode(source)));
+
+ } else if (source.getClass() == String.class) {
+ // source is a string - just decode it
+ return decode(source.toString(), clazz);
+
+ } else {
+ // do it the long way: encode to a string and then decode the string
+ return decode(encode(source), clazz);
+ }
+ }
+
+ /**
* Encodes an object into json.
*
* @param object object to be encoded
@@ -41,6 +72,17 @@ public interface Coder {
String encode(Object object) throws CoderException;
/**
+ * Encodes an object into json, optionally making it "pretty".
+ *
+ * @param object object to be encoded
+ * @param pretty {@code true} if it should be encoded as "pretty" json, {@code false}
+ * otherwise
+ * @return a json string representing the object
+ * @throws CoderException if an error occurs
+ */
+ String encode(Object object, boolean pretty) throws CoderException;
+
+ /**
* Encodes an object into json, writing to the given target.
*
* @param target target to which to write the encoded json
diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/PropertyCoder.java b/utils/src/main/java/org/onap/policy/common/utils/coder/PropertyCoder.java
index 3036d353..daacf479 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/coder/PropertyCoder.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/coder/PropertyCoder.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP PAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -55,12 +55,12 @@ public class PropertyCoder {
* @return a class T object
*/
public <T> T decode(String json, String keyProperty, Class<T> clazz) {
- JsonElement jsonElement = GSON.fromJson(json, JsonElement.class);
+ var jsonElement = GSON.fromJson(json, JsonElement.class);
return new MyDecoder(jsonElement, keyProperty).decrypt(jsonElement, clazz);
}
public <T> T decode(Reader reader, String keyProperty, Class<T> clazz) {
- JsonElement jsonElement = GSON.fromJson(reader, JsonElement.class);
+ var jsonElement = GSON.fromJson(reader, JsonElement.class);
return new MyDecoder(jsonElement, keyProperty).decrypt(jsonElement, clazz);
}
@@ -71,9 +71,9 @@ public class PropertyCoder {
if (!jsonElement.isJsonObject()) {
return;
}
- JsonObject jsonObject = jsonElement.getAsJsonObject();
+ var jsonObject = jsonElement.getAsJsonObject();
// Use keyProperty from input to retrieve secretKey
- String secretKey = jsonObject.get(keyProperty).getAsString();
+ var secretKey = jsonObject.get(keyProperty).getAsString();
if (!StringUtils.isBlank(secretKey)) {
crypto = new CryptoUtils(secretKey);
}
@@ -97,7 +97,7 @@ public class PropertyCoder {
if (!jsonElement.getAsJsonPrimitive().isString()) {
return jsonElement;
}
- String value = jsonElement.getAsString();
+ var value = jsonElement.getAsString();
if (!value.startsWith("enc:")) {
return jsonElement;
}
@@ -111,7 +111,7 @@ public class PropertyCoder {
if (crypto == null) {
return jsonArray;
}
- JsonArray newArray = new JsonArray();
+ var newArray = new JsonArray();
for (JsonElement element: jsonArray) {
newArray.add(decrypt(element));
}
@@ -122,14 +122,14 @@ public class PropertyCoder {
if (crypto == null) {
return jsonObject;
}
- JsonObject newObject = new JsonObject();
+ var newObject = new JsonObject();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
- JsonElement jsonElement = decrypt(entry.getValue());
+ var jsonElement = decrypt(entry.getValue());
newObject.add(key, jsonElement);
}
return newObject;
}
}
-} \ No newline at end of file
+}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java
index e84a92f2..d6135afd 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java
@@ -1,8 +1,8 @@
/*
* ============LICENSE_START=======================================================
- * ONAP PAP
+ * ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -38,35 +38,101 @@ import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
import lombok.AccessLevel;
-import lombok.Getter;
+import lombok.AllArgsConstructor;
import org.onap.policy.common.gson.DoubleConverter;
import org.onap.policy.common.gson.GsonMessageBodyHandler;
/**
* JSON encoder and decoder using the "standard" mechanism, which is currently gson.
*/
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class StandardCoder implements Coder {
/**
* Gson object used to encode and decode messages.
*/
- @Getter(AccessLevel.PROTECTED)
- private static final Gson GSON = GsonMessageBodyHandler.configBuilder(
- new GsonBuilder().registerTypeAdapter(StandardCoderObject.class, new StandardTypeAdapter()))
- .create();
+ private static final Gson GSON_STD;
+
+ /**
+ * Gson object used to encode messages in "pretty" format.
+ */
+ private static final Gson GSON_STD_PRETTY;
+
+ static {
+ GsonBuilder builder = GsonMessageBodyHandler.configBuilder(
+ new GsonBuilder().registerTypeAdapter(StandardCoderObject.class, new StandardTypeAdapter()));
+
+ GSON_STD = builder.create();
+ GSON_STD_PRETTY = builder.setPrettyPrinting().create();
+ }
+
+ /**
+ * Gson object used to encode and decode messages.
+ */
+ protected final Gson gson;
+
+ /**
+ * Gson object used to encode messages in "pretty" format.
+ */
+ protected final Gson gsonPretty;
/**
* Constructs the object.
*/
public StandardCoder() {
- super();
+ this(GSON_STD, GSON_STD_PRETTY);
+ }
+
+ @Override
+ public <S, T> T convert(S source, Class<T> clazz) throws CoderException {
+ if (source == null) {
+ return null;
+
+ } else if (clazz == source.getClass()) {
+ // same class - just cast it
+ return clazz.cast(source);
+
+ } else if (clazz == String.class) {
+ // target is a string - just encode the source
+ return (clazz.cast(encode(source)));
+
+ } else if (source.getClass() == String.class) {
+ // source is a string - just decode it
+ return decode(source.toString(), clazz);
+
+ } else {
+ /*
+ * Do it the long way: encode to a tree and then decode the tree. This entire
+ * method could have been left out and the default Coder.convert() used
+ * instead, but this should perform slightly better as it only uses a
+ * JsonElement as the intermediate data structure, while Coder.convert() goes
+ * all the way to a String as the intermediate data structure.
+ */
+ try {
+ return fromJson(toJsonTree(source), clazz);
+ } catch (RuntimeException e) {
+ throw new CoderException(e);
+ }
+ }
}
@Override
public String encode(Object object) throws CoderException {
+ return encode(object, false);
+ }
+
+ @Override
+ public String encode(Object object, boolean pretty) throws CoderException {
try {
- return toJson(object);
+ if (pretty) {
+ return toPrettyJson(object);
+
+ } else {
+ return toJson(object);
+ }
} catch (RuntimeException e) {
throw new CoderException(e);
@@ -78,7 +144,7 @@ public class StandardCoder implements Coder {
try {
toJson(target, object);
- } catch (RuntimeException | IOException e) {
+ } catch (RuntimeException e) {
throw new CoderException(e);
}
}
@@ -86,7 +152,7 @@ public class StandardCoder implements Coder {
@Override
public void encode(OutputStream target, Object object) throws CoderException {
try {
- Writer wtr = makeWriter(target);
+ var wtr = makeWriter(target);
toJson(wtr, object);
// flush, but don't close
@@ -99,7 +165,7 @@ public class StandardCoder implements Coder {
@Override
public void encode(File target, Object object) throws CoderException {
- try (Writer wtr = makeWriter(target)) {
+ try (var wtr = makeWriter(target)) {
toJson(wtr, object);
// no need to flush or close here
@@ -141,7 +207,7 @@ public class StandardCoder implements Coder {
@Override
public <T> T decode(File source, Class<T> clazz) throws CoderException {
- try (Reader input = makeReader(source)) {
+ try (var input = makeReader(source)) {
return fromJson(input, clazz);
} catch (RuntimeException | IOException e) {
@@ -149,10 +215,20 @@ public class StandardCoder implements Coder {
}
}
+ /**
+ * Encodes the object as "pretty" json.
+ *
+ * @param object object to be encoded
+ * @return the encoded object
+ */
+ protected String toPrettyJson(Object object) {
+ return gsonPretty.toJson(object);
+ }
+
@Override
public StandardCoderObject toStandard(Object object) throws CoderException {
try {
- return new StandardCoderObject(GSON.toJsonTree(object));
+ return new StandardCoderObject(gson.toJsonTree(object));
} catch (RuntimeException e) {
throw new CoderException(e);
@@ -162,7 +238,7 @@ public class StandardCoder implements Coder {
@Override
public <T> T fromStandard(StandardCoderObject sco, Class<T> clazz) throws CoderException {
try {
- return GSON.fromJson(sco.getData(), clazz);
+ return gson.fromJson(sco.getData(), clazz);
} catch (RuntimeException e) {
throw new CoderException(e);
@@ -220,7 +296,7 @@ public class StandardCoder implements Coder {
* @return a json element representing the object
*/
protected JsonElement toJsonTree(Object object) {
- return GSON.toJsonTree(object);
+ return gson.toJsonTree(object);
}
/**
@@ -230,7 +306,7 @@ public class StandardCoder implements Coder {
* @return a json string representing the object
*/
protected String toJson(Object object) {
- return GSON.toJson(object);
+ return gson.toJson(object);
}
/**
@@ -238,10 +314,9 @@ public class StandardCoder implements Coder {
*
* @param target target to which to write the encoded json
* @param object object to be encoded
- * @throws IOException if an I/O error occurs
*/
- protected void toJson(Writer target, Object object) throws IOException {
- GSON.toJson(object, object.getClass(), target);
+ protected void toJson(Writer target, Object object) {
+ gson.toJson(object, object.getClass(), target);
}
/**
@@ -252,7 +327,7 @@ public class StandardCoder implements Coder {
* @return the object represented by the given json element
*/
protected <T> T fromJson(JsonElement json, Class<T> clazz) {
- return convertFromDouble(clazz, GSON.fromJson(json, clazz));
+ return convertFromDouble(clazz, gson.fromJson(json, clazz));
}
/**
@@ -263,7 +338,7 @@ public class StandardCoder implements Coder {
* @return the object represented by the given json string
*/
protected <T> T fromJson(String json, Class<T> clazz) {
- return convertFromDouble(clazz, GSON.fromJson(json, clazz));
+ return convertFromDouble(clazz, gson.fromJson(json, clazz));
}
/**
@@ -274,7 +349,7 @@ public class StandardCoder implements Coder {
* @return the object represented by the given json string
*/
protected <T> T fromJson(Reader source, Class<T> clazz) {
- return convertFromDouble(clazz, GSON.fromJson(source, clazz));
+ return convertFromDouble(clazz, gson.fromJson(source, clazz));
}
/**
@@ -286,8 +361,8 @@ public class StandardCoder implements Coder {
* @param value value to be converted
* @return the converted value
*/
- private <T> T convertFromDouble(Class<T> clazz, T value) {
- if (clazz != Object.class) {
+ protected <T> T convertFromDouble(Class<T> clazz, T value) {
+ if (clazz != Object.class && !Map.class.isAssignableFrom(clazz) && !List.class.isAssignableFrom(clazz)) {
return value;
}
@@ -297,20 +372,14 @@ public class StandardCoder implements Coder {
/**
* Adapter for standard objects.
*/
- private static class StandardTypeAdapter extends TypeAdapter<StandardCoderObject> {
+ @AllArgsConstructor
+ protected static class StandardTypeAdapter extends TypeAdapter<StandardCoderObject> {
/**
* Used to read/write a JsonElement.
*/
private static TypeAdapter<JsonElement> elementAdapter = new Gson().getAdapter(JsonElement.class);
- /**
- * Constructs the object.
- */
- public StandardTypeAdapter() {
- super();
- }
-
@Override
public void write(JsonWriter out, StandardCoderObject value) throws IOException {
elementAdapter.write(out, value.getData());
diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillis.java b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillis.java
new file mode 100644
index 00000000..27b239bb
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillis.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.utils.coder;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import java.time.Instant;
+import org.onap.policy.common.gson.GsonMessageBodyHandler;
+import org.onap.policy.common.gson.InstantAsMillisTypeAdapter;
+
+/**
+ * JSON encoder and decoder using the "standard" mechanism, but encodes Instant fields as
+ * Long milliseconds.
+ */
+public class StandardCoderInstantAsMillis extends StandardCoder {
+
+ /**
+ * Gson object used to encode and decode messages.
+ */
+ private static final Gson GSON_INSTANT;
+
+ /**
+ * Gson object used to encode messages in "pretty" format.
+ */
+ private static final Gson GSON_INSTANT_PRETTY;
+
+ static {
+ GsonBuilder builder = GsonMessageBodyHandler
+ .configBuilder(new GsonBuilder().registerTypeAdapter(StandardCoderObject.class,
+ new StandardTypeAdapter()))
+ .registerTypeAdapter(Instant.class, new InstantAsMillisTypeAdapter());
+
+ GSON_INSTANT = builder.create();
+ GSON_INSTANT_PRETTY = builder.setPrettyPrinting().create();
+ }
+
+ /**
+ * Constructs the object.
+ */
+ public StandardCoderInstantAsMillis() {
+ super(GSON_INSTANT, GSON_INSTANT_PRETTY);
+ }
+}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderObject.java b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderObject.java
index 60c5f4ef..55f7f9d7 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderObject.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderObject.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,18 +21,29 @@
package org.onap.policy.common.utils.coder;
import com.google.gson.JsonElement;
+import java.io.Serializable;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
/**
* Object type used by the {@link StandardCoder}. Different serialization tools have
* different "standard objects". For instance, GSON uses {@link JsonElement}. This class
* wraps that object so that it can be used without exposing the object, itself.
*/
-public class StandardCoderObject {
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
+public class StandardCoderObject implements Serializable {
+ private static final long serialVersionUID = 1L;
/**
* Data wrapped by this.
*/
- private final JsonElement data;
+ /*
+ * this should not be transient, but since it isn't serializable, we're stuck with it
+ * until there's time to address the issue
+ */
+ @Getter(AccessLevel.PROTECTED)
+ private final transient JsonElement data;
/**
* Constructs the object.
@@ -42,52 +53,75 @@ public class StandardCoderObject {
}
/**
- * Constructs the object.
- *
- * @param data data wrapped by this object.
- */
- protected StandardCoderObject(JsonElement data) {
- this.data = data;
- }
-
- /**
- * Gets the data wrapped by this.
- *
- * @return the data wrapped by this
- */
- protected JsonElement getData() {
- return data;
- }
-
- /**
* Gets a field's value from this object, traversing the object hierarchy.
*
- * @param fields field hierarchy
+ * @param fields field hierarchy. These may be strings, identifying fields within the
+ * object, or Integers, identifying an index within an array
* @return the field value or {@code null} if the field does not exist or is not a
* primitive
*/
- public String getString(String... fields) {
-
- /*
- * This could be relatively easily modified to allow Integer arguments, as well,
- * which would be used to specify indices within an array.
- */
+ public String getString(Object... fields) {
JsonElement jel = data;
- for (String field : fields) {
+ for (Object field : fields) {
if (jel == null) {
return null;
}
- if (jel.isJsonObject()) {
- jel = jel.getAsJsonObject().get(field);
+ if (field instanceof String) {
+ jel = getFieldFromObject(jel, field.toString());
+
+ } else if (field instanceof Integer) {
+ jel = getItemFromArray(jel, (int) field);
} else {
- return null;
+ throw new IllegalArgumentException("subscript is not a string or integer: " + field);
}
}
return (jel != null && jel.isJsonPrimitive() ? jel.getAsString() : null);
}
+
+ /**
+ * Gets an item from an object.
+ *
+ * @param element object from which to extract the item
+ * @param field name of the field from which to extract the item
+ * @return the item, or {@code null} if the element is not an object or if the field
+ * does not exist
+ */
+ protected JsonElement getFieldFromObject(JsonElement element, String field) {
+ if (!element.isJsonObject()) {
+ return null;
+ }
+
+ return element.getAsJsonObject().get(field);
+ }
+
+ /**
+ * Gets an item from an array.
+ *
+ * @param element array from which to extract the item
+ * @param index index of the item to extract
+ * @return the item, or {@code null} if the element is not an array or if the index is
+ * out of bounds
+ */
+ protected JsonElement getItemFromArray(JsonElement element, int index) {
+ if (index < 0) {
+ throw new IllegalArgumentException("subscript is invalid: " + index);
+ }
+
+ if (!element.isJsonArray()) {
+ return null;
+ }
+
+ var array = element.getAsJsonArray();
+
+ if (index >= array.size()) {
+ return null;
+ }
+
+ return array.get(index);
+ }
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardValCoder.java b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardValCoder.java
new file mode 100644
index 00000000..4deeba14
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardValCoder.java
@@ -0,0 +1,119 @@
+/*--
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.utils.coder;
+
+import com.worldturner.medeia.api.JsonSchemaVersion;
+import com.worldturner.medeia.api.SchemaSource;
+import com.worldturner.medeia.api.StringSchemaSource;
+import com.worldturner.medeia.api.ValidationFailedException;
+import com.worldturner.medeia.api.gson.MedeiaGsonApi;
+import com.worldturner.medeia.schema.validation.SchemaValidator;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import lombok.NonNull;
+import lombok.ToString;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Extension to the StandardCoder to support streaming validation against a Draft-07 Json schema specification.
+ */
+
+@ToString
+public class StandardValCoder extends StandardCoder {
+
+ // The medeia-validator library integrates better than
+ // other libraries considered with GSON, and therefore
+ // the StandardCoder.
+
+ private static final Logger logger = LoggerFactory.getLogger(StandardValCoder.class);
+
+ private final MedeiaGsonApi validatorApi = new MedeiaGsonApi();
+ private final SchemaValidator validator;
+
+ /**
+ * StandardCoder with validation.
+ */
+ public StandardValCoder(@NonNull String jsonSchema, @NonNull String name) {
+ SchemaSource schemaSource = new StringSchemaSource(jsonSchema, JsonSchemaVersion.DRAFT07, null, name);
+ this.validator = validatorApi.loadSchema(schemaSource);
+ }
+
+ @Override
+ protected String toPrettyJson(Object object) {
+ /*
+ * The validator strips off the "pretty" stuff (i.e., spaces), thus we have to validate and generate the pretty
+ * JSON in separate steps.
+ */
+ gson.toJson(object, object.getClass(), validatorApi.createJsonWriter(validator, new StringWriter()));
+
+ return super.toPrettyJson(object);
+ }
+
+ @Override
+ protected String toJson(@NonNull Object object) {
+ var output = new StringWriter();
+ toJson(output, object);
+ return output.toString();
+ }
+
+ @Override
+ protected void toJson(@NonNull Writer target, @NonNull Object object) {
+ gson.toJson(object, object.getClass(), validatorApi.createJsonWriter(validator, target));
+ }
+
+ @Override
+ protected <T> T fromJson(@NonNull Reader source, @NonNull Class<T> clazz) {
+ return convertFromDouble(clazz, gson.fromJson(validatorApi.createJsonReader(validator, source), clazz));
+ }
+
+ @Override
+ protected <T> T fromJson(String json, Class<T> clazz) {
+ var reader = new StringReader(json);
+ return convertFromDouble(clazz, gson.fromJson(validatorApi.createJsonReader(validator, reader), clazz));
+ }
+
+ /**
+ * Is the json conformant?.
+ */
+ public boolean isConformant(@NonNull String json) {
+ try {
+ conformance(json);
+ } catch (CoderException e) {
+ logger.info("JSON is not conformant to schema", e);
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Check a json string for conformance against its schema definition.
+ */
+ public void conformance(@NonNull String json) throws CoderException {
+ try {
+ validatorApi.parseAll(validatorApi.createJsonReader(validator, new StringReader(json)));
+ } catch (ValidationFailedException e) {
+ throw new CoderException(e);
+ }
+ }
+}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardYamlCoder.java b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardYamlCoder.java
index 36f15b96..d94ddca4 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardYamlCoder.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardYamlCoder.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -34,7 +34,18 @@ public class StandardYamlCoder extends StandardCoder {
* Constructs the object.
*/
public StandardYamlCoder() {
- translator = new YamlJsonTranslator(getGSON());
+ translator = new YamlJsonTranslator(gson) {
+ @Override
+ protected <T> T convertFromDouble(Class<T> clazz, T value) {
+ return StandardYamlCoder.this.convertFromDouble(clazz, value);
+ }
+ };
+ }
+
+ @Override
+ protected String toPrettyJson(Object object) {
+ // YAML is already "pretty"
+ return toJson(object);
}
@Override
diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/YamlJsonTranslator.java b/utils/src/main/java/org/onap/policy/common/utils/coder/YamlJsonTranslator.java
index 906c9fdd..077246bf 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/coder/YamlJsonTranslator.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/coder/YamlJsonTranslator.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,6 +21,7 @@
package org.onap.policy.common.utils.coder;
import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
@@ -31,9 +32,12 @@ import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
+import lombok.AllArgsConstructor;
+import org.onap.policy.common.gson.InstantTypeAdapter;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.emitter.Emitter;
@@ -50,7 +54,13 @@ import org.yaml.snakeyaml.serializer.Serializer;
/**
* YAML-JSON translator. The methods may throw either of the runtime exceptions,
* YAMLException or JsonSyntaxException.
+ * <p/>
+ * Note: if the invoker wishes Double to be converted to Integer/Long when type
+ * Object.class is requested, then a Gson object must be used that will perform the
+ * translation. In addition, the {@link #convertFromDouble(Class, Object)} method should
+ * be overridden with an appropriate conversion method.
*/
+@AllArgsConstructor
public class YamlJsonTranslator {
/**
@@ -62,16 +72,9 @@ public class YamlJsonTranslator {
* Constructs the object.
*/
public YamlJsonTranslator() {
- this(new Gson());
- }
-
- /**
- * Constructs the object.
- *
- * @param gson the Gson object to be used to serialize and de-serialize
- */
- public YamlJsonTranslator(Gson gson) {
- this.gson = gson;
+ GsonBuilder builder = new GsonBuilder();
+ builder.registerTypeAdapter(Instant.class, new InstantTypeAdapter());
+ gson = builder.create();
}
/**
@@ -81,7 +84,7 @@ public class YamlJsonTranslator {
* @return YAML representing the original object
*/
public String toYaml(Object object) {
- StringWriter output = new StringWriter();
+ var output = new StringWriter();
toYaml(output, object);
return output.toString();
}
@@ -93,8 +96,8 @@ public class YamlJsonTranslator {
* @param object POJO to be translated
*/
public void toYaml(Writer target, Object object) {
- DumperOptions dumper = new DumperOptions();
- Serializer serializer = new Serializer(new Emitter(target, dumper), new Resolver(), dumper, null);
+ var dumper = new DumperOptions();
+ var serializer = new Serializer(new Emitter(target, dumper), new Resolver(), dumper, null);
try {
serializer.open();
@@ -135,7 +138,7 @@ public class YamlJsonTranslator {
* @return a POJO representing the YAML read from the reader
*/
public <T> T fromYaml(Reader source, Class<T> clazz) {
- Node node = new Yaml().compose(source);
+ var node = new Yaml().compose(source);
return fromJson(makeJson(node), clazz);
}
@@ -147,7 +150,22 @@ public class YamlJsonTranslator {
* @return a POJO representing the original element
*/
protected <T> T fromJson(JsonElement jel, Class<T> clazz) {
- return gson.fromJson(jel, clazz);
+ return convertFromDouble(clazz, gson.fromJson(jel, clazz));
+ }
+
+ /**
+ * Converts a value from Double to Integer/Long, walking the value's contents if it's
+ * a List/Map. Only applies if the specified class refers to the Object class.
+ * Otherwise, it leaves the value unchanged.
+ * <p/>
+ * The default method simply returns the original value.
+ *
+ * @param clazz class of object to be decoded
+ * @param value value to be converted
+ * @return the converted value
+ */
+ protected <T> T convertFromDouble(Class<T> clazz, T value) {
+ return value;
}
/**
@@ -261,7 +279,7 @@ public class YamlJsonTranslator {
protected JsonArray makeJsonArray(SequenceNode node) {
List<Node> nodes = node.getValue();
- JsonArray array = new JsonArray(nodes.size());
+ var array = new JsonArray(nodes.size());
nodes.forEach(subnode -> array.add(makeJson(subnode)));
return array;
@@ -274,10 +292,10 @@ public class YamlJsonTranslator {
* @return a gson element corresponding to the node
*/
protected JsonObject makeJsonObject(MappingNode node) {
- JsonObject obj = new JsonObject();
+ var obj = new JsonObject();
for (NodeTuple tuple : node.getValue()) {
- Node key = tuple.getKeyNode();
+ var key = tuple.getKeyNode();
String skey = ((ScalarNode) key).getValue();
obj.add(skey, makeJson(tuple.getValueNode()));
@@ -294,7 +312,7 @@ public class YamlJsonTranslator {
*/
protected JsonElement makeJsonPrim(ScalarNode node) {
try {
- Tag tag = node.getTag();
+ var tag = node.getTag();
if (tag == Tag.INT) {
return new JsonPrimitive(Long.valueOf(node.getValue()));
diff --git a/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrCloser.java b/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrCloser.java
index 3532002e..f1798516 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrCloser.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrCloser.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* Common Utils
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 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.
@@ -20,40 +21,26 @@
package org.onap.policy.common.utils.jpa;
-import javax.persistence.EntityManager;
+import jakarta.persistence.EntityManager;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
/**
* Wrapper for an <i>EntityManager</i>, providing auto-close functionality. This is useful in
* try-with-resources statements.
*/
+@AllArgsConstructor
public class EntityMgrCloser implements AutoCloseable {
/**
* The wrapped manager.
*/
- private final EntityManager em;
-
- /**
- * Construct an instance with the EntityManager.
- *
- * @param em manager to be auto-closed
- */
- public EntityMgrCloser(EntityManager em) {
- this.em = em;
- }
-
- /**
- * Gets the EntityManager wrapped within this object.
- *
- * @return the associated EntityManager
- */
- public EntityManager getManager() {
- return em;
- }
+ @Getter
+ private final EntityManager manager;
@Override
public void close() {
- em.close();
+ manager.close();
}
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloser.java b/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloser.java
index b046cc55..5f3a6ea8 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloser.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloser.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* Common Utils
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 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.
@@ -20,40 +21,26 @@
package org.onap.policy.common.utils.jpa;
-import javax.persistence.EntityManagerFactory;
+import jakarta.persistence.EntityManagerFactory;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
/**
* Wrapper for an <i>EntityManagerFactory</i>, providing auto-close functionality. This is useful in
* try-with-resources statements.
*/
+@AllArgsConstructor
public class EntityMgrFactoryCloser implements AutoCloseable {
/**
* The wrapped factory.
*/
- private final EntityManagerFactory emf;
-
- /**
- * Construct an instance with the given EntityManagerFactory.
- *
- * @param emf manager to be auto-closed
- */
- public EntityMgrFactoryCloser(EntityManagerFactory emf) {
- this.emf = emf;
- }
-
- /**
- * Gets the EntityManagerFactory wrapped within this object.
- *
- * @return the associated EntityManagerFactory
- */
- public EntityManagerFactory getFactory() {
- return emf;
- }
+ @Getter
+ private final EntityManagerFactory factory;
@Override
public void close() {
- emf.close();
+ factory.close();
}
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityTransCloser.java b/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityTransCloser.java
index 3552a6fa..131e87a4 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityTransCloser.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/jpa/EntityTransCloser.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* Common Utils
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 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.
@@ -20,7 +21,8 @@
package org.onap.policy.common.utils.jpa;
-import javax.persistence.EntityTransaction;
+import jakarta.persistence.EntityTransaction;
+import lombok.Getter;
/**
* Wrapper for an <i>EntityTransaction</i> that is auto-rolled back when closed. This is useful in
@@ -31,46 +33,37 @@ public class EntityTransCloser implements AutoCloseable {
/**
* Transaction to be rolled back.
*/
- private final EntityTransaction trans;
+ @Getter
+ private final EntityTransaction transaction;
/**
* Begins a transaction.
- *
+ *
* @param et transaction to wrap/begin
*/
public EntityTransCloser(EntityTransaction et) {
- trans = et;
- trans.begin();
- }
-
- /**
- * Gets the wrapped transaction.
- *
- * @return the transaction
- */
- public EntityTransaction getTransation() {
- return trans;
+ transaction = et;
+ transaction.begin();
}
/**
* Commits the transaction.
*/
public void commit() {
- trans.commit();
+ transaction.commit();
}
/**
* Rolls back the transaction.
*/
public void rollback() {
- trans.rollback();
+ transaction.rollback();
}
@Override
public void close() {
- if (trans.isActive()) {
- trans.rollback();
+ if (transaction.isActive()) {
+ transaction.rollback();
}
}
-
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/logging/LoggerMarkerFilter.java b/utils/src/main/java/org/onap/policy/common/utils/logging/LoggerMarkerFilter.java
new file mode 100644
index 00000000..2c9830dc
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/logging/LoggerMarkerFilter.java
@@ -0,0 +1,98 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP POLICY
+ * ================================================================================
+ * Copyright (C) 2021 AT&T Intellectual Property. All right 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.utils.logging;
+
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.filter.AbstractMatcherFilter;
+import ch.qos.logback.core.spi.FilterReply;
+import org.slf4j.Marker;
+
+public abstract class LoggerMarkerFilter extends AbstractMatcherFilter<ILoggingEvent> {
+
+ protected final Marker marker;
+
+ protected LoggerMarkerFilter(Marker marker) {
+ this.marker = marker;
+ }
+
+ @Override
+ public FilterReply decide(ILoggingEvent event) {
+
+ if (this.marker == null || !isStarted()) {
+ return FilterReply.DENY;
+ }
+
+ if (event == null || event.getMarkerList() == null) {
+ return FilterReply.DENY;
+ }
+
+ if (event.getMarkerList().stream().anyMatch(mk -> mk.equals(marker))) {
+ return FilterReply.ACCEPT;
+ } else {
+ return FilterReply.DENY;
+ }
+ }
+
+ /**
+ * Metric Logger Marker Filter.
+ */
+ public static class MetricLoggerMarkerFilter extends LoggerMarkerFilter {
+
+ public MetricLoggerMarkerFilter() {
+ super(LoggerUtils.METRIC_LOG_MARKER);
+ }
+
+ }
+
+ /**
+ * Security Logger Marker Filter.
+ */
+ public static class SecurityLoggerMarkerFilter extends LoggerMarkerFilter {
+
+ public SecurityLoggerMarkerFilter() {
+ super(LoggerUtils.SECURITY_LOG_MARKER);
+ }
+ }
+
+ /**
+ * Audit Logger Marker Filter.
+ */
+ public static class AuditLoggerMarkerFilter extends LoggerMarkerFilter {
+
+ public AuditLoggerMarkerFilter() {
+ super(LoggerUtils.AUDIT_LOG_MARKER);
+ }
+ }
+
+ /**
+ * Transaction Logger Marker Filter.
+ */
+ public static class TransactionLoggerMarkerFilter extends LoggerMarkerFilter {
+
+ public TransactionLoggerMarkerFilter() {
+ super(LoggerUtils.TRANSACTION_LOG_MARKER);
+ }
+ }
+
+}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/logging/LoggerUtils.java b/utils/src/main/java/org/onap/policy/common/utils/logging/LoggerUtils.java
new file mode 100644
index 00000000..89575eb2
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/logging/LoggerUtils.java
@@ -0,0 +1,105 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP POLICY
+ * ================================================================================
+ * Copyright (C) 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.utils.logging;
+
+import ch.qos.logback.classic.LoggerContext;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Marker;
+import org.slf4j.MarkerFactory;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class LoggerUtils {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(LoggerUtils.class);
+
+ /**
+ * ROOT logger.
+ */
+ public static final String ROOT_LOGGER = "ROOT";
+ /**
+ * Metric logger.
+ */
+ public static final String METRIC_LOG_MARKER_NAME = "metric";
+ /**
+ * Audit Log Marker Name.
+ */
+ public static final String AUDIT_LOG_MARKER_NAME = "audit";
+ /**
+ * Security Log Marker Name.
+ */
+ public static final String SECURITY_LOG_MARKER_NAME = "security";
+ /**
+ * Transaction Log Marker Name.
+ */
+ public static final String TRANSACTION_LOG_MARKER_NAME = "transaction";
+ /**
+ * Marks a logging record for metric.
+ */
+ public static final Marker METRIC_LOG_MARKER = MarkerFactory.getMarker(METRIC_LOG_MARKER_NAME);
+ /**
+ * Marks a logging record for security.
+ */
+ public static final Marker SECURITY_LOG_MARKER = MarkerFactory.getMarker(SECURITY_LOG_MARKER_NAME);
+ /**
+ * Marks a logging record for audit.
+ */
+ public static final Marker AUDIT_LOG_MARKER = MarkerFactory.getMarker(AUDIT_LOG_MARKER_NAME);
+ /**
+ * Marks a logging record as an end-to-end transaction.
+ */
+ public static final Marker TRANSACTION_LOG_MARKER = MarkerFactory.getMarker(TRANSACTION_LOG_MARKER_NAME);
+
+
+ /**
+ * Set the log level of a logger.
+ *
+ * @param loggerName logger name
+ * @param loggerLevel logger level
+ */
+ public static String setLevel(String loggerName, String loggerLevel) {
+ if (!(LoggerFactory.getILoggerFactory() instanceof LoggerContext)) {
+ throw new IllegalStateException("The SLF4J logger factory is not configured for logback");
+ }
+
+ final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
+ final var logger = context.getLogger(loggerName);
+ if (logger == null) {
+ throw new IllegalArgumentException("no logger " + loggerName);
+ }
+
+ LOGGER.warn("setting {} logger to level {}", loggerName, loggerLevel);
+
+ // use the current log level if the string provided cannot be converted to a valid Level.
+
+ // NOSONAR: this method is currently used by the telemetry api (which should be authenticated).
+ // It is no more or no less dangerous than an admin changing the logback level on the fly.
+ // This is a controlled admin function that should not cause any risks when the system
+ // is configured properly.
+ logger.setLevel(ch.qos.logback.classic.Level.toLevel(loggerLevel, logger.getLevel())); // NOSONAR
+
+ return logger.getLevel().toString();
+ }
+}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java b/utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java
index 14362627..6698d7cf 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -26,16 +26,19 @@ import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
-import java.security.cert.X509Certificate;
+import java.util.UUID;
import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.commons.net.util.TrustManagerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Network Utilities.
*/
-public class NetworkUtil {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class NetworkUtil {
public static final Logger logger = LoggerFactory.getLogger(NetworkUtil.class.getName());
@@ -48,33 +51,7 @@ public class NetworkUtil {
/**
* A trust manager that always trusts certificates.
*/
- // @formatter:off
- private static final TrustManager[] ALWAYS_TRUST_MANAGER = new TrustManager[] {
- new X509TrustManager() {
-
- @Override
- public X509Certificate[] getAcceptedIssuers() {
- return new X509Certificate[0];
- }
-
- @Override
- public void checkClientTrusted(final java.security.cert.X509Certificate[] certs,
- final String authType) {
- // always trust
- }
-
- @Override
- public void checkServerTrusted(final java.security.cert.X509Certificate[] certs,
- final String authType) {
- // always trust
- }
- }
- };
- // @formatter:on
-
- private NetworkUtil() {
- // Empty constructor
- }
+ private static final TrustManager[] ALWAYS_TRUST_MANAGER = { TrustManagerUtils.getAcceptAllTrustManager() };
/**
* Allocates an available port on which a server may listen.
@@ -105,7 +82,11 @@ public class NetworkUtil {
* @throws IOException if a socket cannot be created
*/
public static int allocPort(InetSocketAddress hostAddr) throws IOException {
- try (ServerSocket socket = new ServerSocket()) {
+ /*
+ * The socket is only used to find an unused address for a new server. As a
+ * result, it poses no security risk, thus the sonar issue can be ignored.
+ */
+ try (ServerSocket socket = new ServerSocket()) { // NOSONAR
socket.bind(hostAddr);
return socket.getLocalPort();
@@ -132,9 +113,13 @@ public class NetworkUtil {
*/
public static boolean isTcpPortOpen(String host, int port, int retries, long interval)
throws InterruptedException {
- int retry = 0;
+ var retry = 0;
while (retry < retries) {
- try (Socket s = new Socket(host, port)) {
+ /*
+ * As with the server socket, this is only used to see if the port is open,
+ * thus the sonar issue can be ignored.
+ */
+ try (Socket s = new Socket(host, port)) { // NOSONAR
logger.debug("{}:{} connected - retries={} interval={}", host, port, retries, interval);
return true;
} catch (final IOException e) {
@@ -186,4 +171,15 @@ public class NetworkUtil {
return "127.0.0.1";
}
+
+ /**
+ * Generates a globally unique name, typically for use in PDP messages, to uniquely
+ * identify a PDP (or PAP), regardless on what cluster it resides.
+ *
+ * @param prefix text to be prepended to the generated value
+ * @return a globally unique name
+ */
+ public static String genUniqueName(String prefix) {
+ return prefix + "-" + UUID.randomUUID();
+ }
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/properties/BeanConfigurator.java b/utils/src/main/java/org/onap/policy/common/utils/properties/BeanConfigurator.java
index 2ef91911..f8c52091 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/properties/BeanConfigurator.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/properties/BeanConfigurator.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP - Common Modules
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.utils.properties;
+import com.google.re2j.Pattern;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -45,6 +46,7 @@ import org.onap.policy.common.utils.properties.exception.PropertyMissingExceptio
* <i>accept</i> includes the "empty" option.
*/
public class BeanConfigurator {
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
/**
* The "empty" option that may appear within the {@link Property}'s <i>accept</i>
@@ -414,7 +416,7 @@ public class BeanConfigurator {
* @return {@code true} if the <i>accept</i> attribute includes "empty"
*/
protected boolean isEmptyOk(Property prop) {
- for (String option : prop.accept().split(",")) {
+ for (String option : COMMA_PAT.split(prop.accept())) {
if (ACCEPT_EMPTY.equals(option)) {
return true;
}
@@ -495,7 +497,7 @@ public class BeanConfigurator {
* @throws PropertyAccessException if a "get" method cannot be identified
*/
private Method getGetter(Field field, Property prop) throws PropertyAccessException {
- String capnm = StringUtils.capitalize(field.getName());
+ var capnm = StringUtils.capitalize(field.getName());
try {
return getGetter(field, "get" + capnm);
diff --git a/utils/src/main/java/org/onap/policy/common/utils/properties/PropertyObjectUtils.java b/utils/src/main/java/org/onap/policy/common/utils/properties/PropertyObjectUtils.java
new file mode 100644
index 00000000..2b6e514f
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/properties/PropertyObjectUtils.java
@@ -0,0 +1,242 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * 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.utils.properties;
+
+import com.google.re2j.Pattern;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utilities for generating POJOs from Properties.
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class PropertyObjectUtils {
+
+ public static final Logger logger = LoggerFactory.getLogger(PropertyObjectUtils.class);
+ private static final Pattern NAME_PAT = Pattern.compile("\\[(\\d{1,3})\\]$");
+ private static final Pattern DOT_PAT = Pattern.compile("[.]");
+
+ /**
+ * Converts a set of properties to a Map. Supports json-path style property names with
+ * "." separating components, where components may have an optional subscript.
+ *
+ * @param properties properties to be converted
+ * @param prefix properties whose names begin with this prefix are included. The
+ * prefix is stripped from the name before adding the value to the map
+ * @return a hierarchical map representing the properties
+ */
+ public static Map<String, Object> toObject(Properties properties, String prefix) {
+ String dottedPrefix = prefix + (prefix.isEmpty() || prefix.endsWith(".") ? "" : ".");
+ int pfxlen = dottedPrefix.length();
+
+ Map<String, Object> map = new LinkedHashMap<>();
+
+ for (String name : properties.stringPropertyNames()) {
+ if (name.startsWith(dottedPrefix)) {
+ String[] components = DOT_PAT.split(name.substring(pfxlen));
+ setProperty(map, components, properties.getProperty(name));
+ }
+ }
+
+ return map;
+ }
+
+ /**
+ * Sets a property within a hierarchical map.
+ *
+ * @param map map into which the value should be placed
+ * @param names property name components
+ * @param value value to be placed into the map
+ */
+ private static void setProperty(Map<String, Object> map, String[] names, String value) {
+ Map<String, Object> node = map;
+
+ final int lastComp = names.length - 1;
+
+ // process all but the final component
+ for (var comp = 0; comp < lastComp; ++comp) {
+ node = getNode(node, names[comp]);
+ }
+
+ // process the final component
+ String name = names[lastComp];
+ var matcher = NAME_PAT.matcher(name);
+
+ if (!matcher.find()) {
+ // no subscript
+ node.put(name, value);
+ return;
+ }
+
+ // subscripted
+ List<Object> array = getArray(node, name.substring(0, matcher.start()));
+ var index = Integer.parseInt(matcher.group(1));
+ expand(array, index);
+ array.set(index, value);
+ }
+
+ /**
+ * Gets a node.
+ *
+ * @param map map from which to get the object
+ * @param name name of the element to get from the map, with an optional subscript
+ * @return a Map
+ */
+ @SuppressWarnings("unchecked")
+ private static Map<String, Object> getNode(Map<String, Object> map, String name) {
+ var matcher = NAME_PAT.matcher(name);
+
+ if (!matcher.find()) {
+ // no subscript
+ return getObject(map, name);
+ }
+
+ // subscripted
+ List<Object> array = getArray(map, name.substring(0, matcher.start()));
+ var index = Integer.parseInt(matcher.group(1));
+ expand(array, index);
+
+ Object item = array.get(index);
+ if (item instanceof Map) {
+ return (Map<String, Object>) item;
+
+ } else {
+ LinkedHashMap<String, Object> result = new LinkedHashMap<>();
+ array.set(index, result);
+ return result;
+ }
+ }
+
+ /**
+ * Ensures that an array's size is large enough to hold the specified element.
+ *
+ * @param array array to be expanded
+ * @param index index of the desired element
+ */
+ private static void expand(List<Object> array, int index) {
+ while (array.size() <= index) {
+ array.add(null);
+ }
+ }
+
+ /**
+ * Gets an object (i.e., Map) from a map. If the particular element is not a Map, then
+ * it is replaced with an empty Map.
+ *
+ * @param map map from which to get the object
+ * @param name name of the element to get from the map, without any subscript
+ * @return a Map
+ */
+ private static Map<String, Object> getObject(Map<String, Object> map, String name) {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> result = (Map<String, Object>) map.compute(name, (key, value) -> {
+ if (value instanceof Map) {
+ return value;
+ } else {
+ return new LinkedHashMap<>();
+ }
+ });
+
+ return result;
+ }
+
+ /**
+ * Gets an array from a map. If the particular element is not an array, then it is
+ * replaced with an empty array.
+ *
+ * @param map map from which to get the array
+ * @param name name of the element to get from the map, without any subscript
+ * @return an array
+ */
+ private static List<Object> getArray(Map<String, Object> map, String name) {
+ @SuppressWarnings("unchecked")
+ List<Object> result = (List<Object>) map.compute(name, (key, value) -> {
+ if (value instanceof List) {
+ return value;
+ } else {
+ return new ArrayList<>();
+ }
+ });
+
+ return result;
+ }
+
+ /**
+ * Compresses lists contained within a generic object, removing all {@code null}
+ * items.
+ *
+ * @param object object to be compressed
+ * @return the original object, modified in place
+ */
+ public static Object compressLists(Object object) {
+ if (object instanceof Map) {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> asMap = (Map<String, Object>) object;
+ compressMapValues(asMap);
+
+ } else if (object instanceof List) {
+ @SuppressWarnings("unchecked")
+ List<Object> asList = (List<Object>) object;
+ compressListItems(asList);
+ }
+
+ // else: ignore anything else
+
+ return object;
+ }
+
+ /**
+ * Walks a hierarchical map and removes {@code null} items found in any Lists.
+ *
+ * @param map map whose lists are to be compressed
+ */
+ private static void compressMapValues(Map<String, Object> map) {
+ for (Object value : map.values()) {
+ compressLists(value);
+ }
+ }
+
+ /**
+ * Removes {@code null} items from the list. In addition, it walks the items within
+ * the list, compressing them, as well.
+ *
+ * @param list the list to be compressed
+ */
+ private static void compressListItems(List<Object> list) {
+ Iterator<Object> iter = list.iterator();
+ while (iter.hasNext()) {
+ Object item = iter.next();
+ if (item == null) {
+ // null item - remove it
+ iter.remove();
+
+ } else {
+ compressLists(item);
+ }
+ }
+ }
+}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/properties/SpecProperties.java b/utils/src/main/java/org/onap/policy/common/utils/properties/SpecProperties.java
index ec7157d3..2ea94959 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/properties/SpecProperties.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/properties/SpecProperties.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -21,10 +21,13 @@
package org.onap.policy.common.utils.properties;
import java.util.Properties;
+import lombok.AccessLevel;
+import lombok.Getter;
/**
* Properties with an optional specialization (e.g., session name, controller name).
*/
+@Getter(AccessLevel.PROTECTED)
public class SpecProperties extends Properties {
private static final long serialVersionUID = 1L;
@@ -89,7 +92,7 @@ public class SpecProperties extends Properties {
return super.getProperty(key);
}
- String suffix = key.substring(prefix.length());
+ var suffix = key.substring(prefix.length());
String val = super.getProperty(specPrefix + suffix);
if (val != null) {
@@ -99,14 +102,6 @@ public class SpecProperties extends Properties {
return super.getProperty(key);
}
- protected String getPrefix() {
- return prefix;
- }
-
- protected String getSpecPrefix() {
- return specPrefix;
- }
-
@Override
public final synchronized int hashCode() {
throw new UnsupportedOperationException("SpecProperties cannot be hashed");
diff --git a/utils/src/main/java/org/onap/policy/common/utils/properties/exception/PropertyException.java b/utils/src/main/java/org/onap/policy/common/utils/properties/exception/PropertyException.java
index 44edd428..3c03f38d 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/properties/exception/PropertyException.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/properties/exception/PropertyException.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,9 +20,12 @@
package org.onap.policy.common.utils.properties.exception;
+import lombok.Getter;
+
/**
* Exception associated with a Property.
*/
+@Getter
public class PropertyException extends Exception {
private static final long serialVersionUID = 1L;
@@ -38,7 +41,7 @@ public class PropertyException extends Exception {
/**
* Constructor.
- *
+ *
* @param propName name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
*/
@@ -51,7 +54,7 @@ public class PropertyException extends Exception {
/**
* Constructor.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @param message error message
@@ -65,7 +68,7 @@ public class PropertyException extends Exception {
/**
* Constructor.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @param cause cause of the exception
@@ -79,7 +82,7 @@ public class PropertyException extends Exception {
/**
* Constructor.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @param message error message
@@ -93,28 +96,8 @@ public class PropertyException extends Exception {
}
/**
- * Get the property name.
- *
- * @return name of the property for which the exception was thrown, or {@code null} if
- * no name was provided
- */
- public String getPropertyName() {
- return propertyName;
- }
-
- /**
- * Get the field name.
- *
- * @return name of the field for which the exception was thrown, or {@code null} if no
- * field was provided
- */
- public String getFieldName() {
- return fieldName;
- }
-
- /**
* Make the message.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @param message error message, never {@code null}
@@ -126,13 +109,13 @@ public class PropertyException extends Exception {
/**
* Make the message.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @return an error message composed of the two items
*/
private static String makeMessage(String propnm, String fieldName) {
- StringBuilder bldr = new StringBuilder(50);
+ var bldr = new StringBuilder(50);
if (propnm == null) {
bldr.append("property exception");
diff --git a/utils/src/main/java/org/onap/policy/common/utils/resources/DirectoryUtils.java b/utils/src/main/java/org/onap/policy/common/utils/resources/DirectoryUtils.java
new file mode 100644
index 00000000..35a13138
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/resources/DirectoryUtils.java
@@ -0,0 +1,63 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.utils.resources;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utilities for manipulating directories.
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class DirectoryUtils {
+ private static final Logger logger = LoggerFactory.getLogger(DirectoryUtils.class);
+
+ /**
+ * Creates a directory file, only accessible by the owner.
+ *
+ * @param prefix file name prefix
+ * @return a new, temporary directory
+ * @throws IOException if an error occurs
+ */
+ public static Path createTempDirectory(String prefix) throws IOException {
+ /*
+ * Disabling sonar, as the code below sets the permissions, just as sonar
+ * suggests it be fixed.
+ */
+ var path = Files.createTempDirectory(prefix); // NOSONAR
+ logger.info("created temporary directory, {}", path);
+
+ var file = path.toFile();
+
+ TextFileUtils.setDefaultPermissions(file);
+
+ // ensure nothing has been written to it yet
+ FileUtils.cleanDirectory(file);
+
+ return path;
+ }
+}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/resources/MessageConstants.java b/utils/src/main/java/org/onap/policy/common/utils/resources/MessageConstants.java
new file mode 100644
index 00000000..ef46fdf5
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/resources/MessageConstants.java
@@ -0,0 +1,43 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Bell Canada. All rights reserved.
+ * Modifications Copyright (C) 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.utils.resources;
+
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+
+/**
+ * Common messages to be used by all components.
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class MessageConstants {
+
+ public static final String POLICY_API = "policy-api";
+ public static final String POLICY_PAP = "policy-pap";
+ public static final String POLICY_APEX_PDP = "policy-apex-pdp";
+ public static final String POLICY_DROOLS_PDP = "policy-drools-pdp";
+ public static final String POLICY_XACML_PDP = "policy-xacml-pdp";
+ public static final String POLICY_DISTRIBUTION = "policy-distribution";
+ public static final String POLICY_CLAMP = "policy-clamp";
+
+ public static final String START_SUCCESS_MSG = "Started %s service successfully.";
+ public static final String START_FAILURE_MSG = "Start of %s service failed.";
+}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/resources/PrometheusUtils.java b/utils/src/main/java/org/onap/policy/common/utils/resources/PrometheusUtils.java
new file mode 100644
index 00000000..bac65d4e
--- /dev/null
+++ b/utils/src/main/java/org/onap/policy/common/utils/resources/PrometheusUtils.java
@@ -0,0 +1,107 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2022 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2022 Bell Canada. 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.utils.resources;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
+/**
+ * Prometheus constants and utilities.
+ */
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class PrometheusUtils {
+
+ /**
+ * Policy Deployments Metric Name.
+ */
+ public static final String POLICY_DEPLOYMENTS_METRIC = "policy_deployments";
+
+ /**
+ * Policy Deployments Metric Help Message.
+ */
+ public static final String POLICY_DEPLOYMENT_HELP = "The total number of policy deployments.";
+
+ /**
+ * Policy Execution Metric Name.
+ */
+ public static final String POLICY_EXECUTION_METRIC = "policy_executions";
+
+ /**
+ * Policy Execution Metric Help Message.
+ */
+ public static final String POLICY_EXECUTION_HELP = "The total number of TOSCA policy executions.";
+
+ /**
+ * Policy Execution Latency in Seconds Metric Name.
+ * This metric name is not to be used as a counter.
+ */
+ public static final String POLICY_EXECUTIONS_LATENCY_SECONDS_METRIC = "policy_executions_latency_seconds";
+
+ /**
+ * Policy Execution Latency in Seconds Metric Help message.
+ */
+ public static final String POLICY_EXECUTIONS_LATENCY_SECONDS_HELP =
+ "The latency in seconds of TOSCA policy executions.";
+
+ /**
+ * Metric label for arbitrary operations (eg. deploy, undeploy, execute).
+ */
+ public static final String OPERATION_METRIC_LABEL = "operation";
+
+ /**
+ * Deploy operation value.
+ */
+ public static final String DEPLOY_OPERATION = "deploy";
+
+ /**
+ * Undeploy operation value.
+ */
+ public static final String UNDEPLOY_OPERATION = "undeploy";
+
+ /**
+ * Metric label for states (ie. PASSIVE, ACTIVE).
+ */
+ public static final String STATE_METRIC_LABEL = "state";
+
+ /**
+ * Metric label for status of an operation (ie. SUCCESS or FAILURE).
+ */
+ public static final String STATUS_METRIC_LABEL = "status";
+
+ /**
+ * Prometheus namespace values mapping to the supported PDP types.
+ */
+ public enum PdpType {
+ PDPD("pdpd"),
+ PDPA("pdpa"),
+ PDPX("pdpx");
+
+ @Getter
+ private final String namespace;
+
+ PdpType(String namespace) {
+ this.namespace = namespace;
+ }
+ }
+} \ No newline at end of file
diff --git a/utils/src/main/java/org/onap/policy/common/utils/resources/ResourceUtils.java b/utils/src/main/java/org/onap/policy/common/utils/resources/ResourceUtils.java
index 365efabe..3ee062f1 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/resources/ResourceUtils.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/resources/ResourceUtils.java
@@ -1,7 +1,8 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 2023 Nordix Foundation.
+ * Modifications Copyright (C) 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.
@@ -21,18 +22,22 @@
package org.onap.policy.common.utils.resources;
-import java.io.ByteArrayOutputStream;
+import com.google.re2j.Pattern;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
+import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
-
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -40,25 +45,18 @@ import org.slf4j.LoggerFactory;
* This is common utility class with static methods for handling Java resources on the class path. It is an abstract
* class to prevent any direct instantiation and private constructor to prevent extending this class.
*/
-public abstract class ResourceUtils {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class ResourceUtils {
// Get a reference to the logger
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtils.class);
- // The length of byte buffers used to read resources into strings
- private static final int BYTE_BUFFER_LENGH = 1024;
+ private static final Pattern SLASH_PAT = Pattern.compile("/");
// Resource types
private static final String FILE_PROTOCOL = "file";
private static final String JAR_PROTOCOL = "jar";
/**
- * Private constructor used to prevent sub class instantiation.
- */
- private ResourceUtils() {
- // Prevent construction of this class
- }
-
- /**
* Method to resolve a resource; the local file system is checked first and then the class path is checked.
*
* @param resourceName The resource name
@@ -66,7 +64,7 @@ public abstract class ResourceUtils {
*/
public static URL getUrl4Resource(final String resourceName) {
// Check the local fine system first
- final URL urlToResource = getLocalFile(resourceName);
+ final var urlToResource = getLocalFile(resourceName);
// Check if this is a local file
if (urlToResource != null) {
@@ -86,25 +84,16 @@ public abstract class ResourceUtils {
*/
public static String getResourceAsString(final String resourceName) {
// Get the resource as a stream, we'll convert it to a string then
- final InputStream resourceStream = getResourceAsStream(resourceName);
- if (resourceStream == null) {
- return null;
- }
-
- // Read the stream contents in to an output stream
- final ByteArrayOutputStream resourceOutputStreamBuffer = new ByteArrayOutputStream();
- final byte[] resourceBuffer = new byte[BYTE_BUFFER_LENGH];
- int length;
- try {
- while ((length = resourceStream.read(resourceBuffer)) != -1) {
- resourceOutputStreamBuffer.write(resourceBuffer, 0, length);
+ // Read the stream contents, closing when done
+ try (var resourceStream = getResourceAsStream(resourceName)) {
+ if (resourceStream == null) {
+ return null;
}
+ return IOUtils.toString(resourceStream, StandardCharsets.UTF_8);
} catch (final IOException e) {
- LOGGER.debug("error reading resource stream \"{}\" : " + e.getMessage(), resourceName, e);
+ LOGGER.debug("error reading resource stream {}", resourceName, e);
return null;
}
-
- return resourceOutputStreamBuffer.toString();
}
/**
@@ -116,12 +105,12 @@ public abstract class ResourceUtils {
*/
public static InputStream getResourceAsStream(final String resourceName) {
// Find a URL to the resource first
- final URL urlToResource = getUrl4Resource(resourceName);
+ final var urlToResource = getUrl4Resource(resourceName);
// Check if the resource exists
if (urlToResource == null) {
// No resource found
- LOGGER.debug("cound not find resource \"{}\" : ", resourceName);
+ LOGGER.debug("could not find resource \"{}\" : ", resourceName);
return null;
}
@@ -130,7 +119,7 @@ public abstract class ResourceUtils {
return urlToResource.openStream();
} catch (final IOException e) {
// Any of many IO exceptions such as the resource is a directory
- LOGGER.debug("error attaching resource \"{}\" to stream : " + e.getMessage(), resourceName, e);
+ LOGGER.debug("error attaching resource {}", resourceName, e);
return null;
}
}
@@ -143,11 +132,11 @@ public abstract class ResourceUtils {
*/
public static URL getUrlResource(final String resourceName) {
try {
- final ClassLoader classLoader = ResourceUtils.class.getClassLoader();
+ final var classLoader = ResourceUtils.class.getClassLoader();
- final String[] fileParts = resourceName.split("/");
+ final String[] fileParts = SLASH_PAT.split(resourceName);
// Read the resource
- URL url = classLoader.getResource(resourceName);
+ var url = classLoader.getResource(resourceName);
// Check if the resource is defined
if (url != null) {
@@ -164,7 +153,7 @@ public abstract class ResourceUtils {
return url;
}
} catch (final Exception e) {
- LOGGER.debug("error getting URL resource \"{}\" : " + e.getMessage(), e);
+ LOGGER.debug("error getting URL resource {}", resourceName, e);
return null;
}
}
@@ -178,8 +167,8 @@ public abstract class ResourceUtils {
public static URL getLocalFile(final String resourceName) {
try {
// Input might already be in URL format
- final URL ret = new URL(resourceName);
- final File f = new File(ret.toURI());
+ final var ret = new URL(resourceName);
+ final var f = new File(ret.toURI());
if (f.exists()) {
return ret;
}
@@ -188,10 +177,10 @@ public abstract class ResourceUtils {
}
try {
- final File f = new File(resourceName);
+ final var f = new File(resourceName);
// Check if the file exists
if (f.exists()) {
- final URL urlret = f.toURI().toURL();
+ final var urlret = f.toURI().toURL();
LOGGER.debug("resource \"{}\" was found on the local file system", f.toURI().toURL());
return urlret;
} else {
@@ -199,7 +188,7 @@ public abstract class ResourceUtils {
return null;
}
} catch (final Exception e) {
- LOGGER.debug("error finding resource \"{}\" : " + e.getMessage(), e);
+ LOGGER.debug("error finding resource {}", resourceName, e);
return null;
}
}
@@ -215,7 +204,7 @@ public abstract class ResourceUtils {
return null;
}
- URL modelFileUrl = getUrl4Resource(resource);
+ var modelFileUrl = getUrl4Resource(resource);
if (modelFileUrl != null) {
return modelFileUrl.getPath();
} else {
@@ -227,11 +216,11 @@ public abstract class ResourceUtils {
* Read the list of entries in a resource directory.
*
* @param resourceDirectoryName the name of the resource directory
- * @return the list of entries
+ * @return a set of entries
*/
public static Set<String> getDirectoryContents(final String resourceDirectoryName) {
// Find the location of the resource, is it in a Jar or on the local file system?
- URL directoryUrl = ResourceUtils.getUrl4Resource(resourceDirectoryName);
+ var directoryUrl = ResourceUtils.getUrl4Resource(resourceDirectoryName);
if (directoryUrl == null) {
LOGGER.debug("resource \"{}\" was not found", resourceDirectoryName);
@@ -255,11 +244,11 @@ public abstract class ResourceUtils {
*
* @param localResourceDirectoryUrl the local resource file URL
* @param resourceDirectoryName the name of the resource directory
- * @return a list of the directory contents
+ * @return a set of the directory contents
*/
public static Set<String> getDirectoryContentsLocal(final URL localResourceDirectoryUrl,
final String resourceDirectoryName) {
- File localDirectory = new File(localResourceDirectoryUrl.getFile());
+ var localDirectory = new File(localResourceDirectoryUrl.getFile());
if (!localDirectory.isDirectory()) {
LOGGER.debug("resource \"{}\" is not a directory", resourceDirectoryName);
@@ -267,7 +256,7 @@ public abstract class ResourceUtils {
}
Set<String> localDirectorySet = new TreeSet<>();
- for (File localDirectoryEntry : localDirectory.listFiles()) {
+ for (File localDirectoryEntry : Objects.requireNonNull(localDirectory.listFiles())) {
if (localDirectoryEntry.isDirectory()) {
localDirectorySet
.add(resourceDirectoryName + File.separator + localDirectoryEntry.getName() + File.separator);
@@ -284,23 +273,29 @@ public abstract class ResourceUtils {
*
* @param jarResourceDirectoryUrl the name of the resource directory in the jar
* @param resourceDirectoryName the name of the resource directory
- * @return a list of the directory contents
+ * @return a set of the directory contents
*/
public static Set<String> getDirectoryContentsJar(final URL jarResourceDirectoryUrl,
final String resourceDirectoryName) {
- File jarResourceDirectory = new File(jarResourceDirectoryUrl.getPath());
+ String dirNameWithSlash = resourceDirectoryName + "/";
+ int minLength = dirNameWithSlash.length() + 1;
+ var jarResourceDirectory = new File(jarResourceDirectoryUrl.getPath());
String jarFileName = jarResourceDirectory.getParent().replaceFirst("^file:", "").replaceFirst("!.*$", "");
Set<String> localDirectorySet = new TreeSet<>();
- try (JarFile jarFile = new JarFile(jarFileName)) {
- Enumeration<JarEntry> entries = jarFile.entries();
+ try (var jarFile = new JarFile(jarFileName)) {
+ Enumeration<JarEntry> entries = jarFile.entries(); // NOSONAR
while (entries.hasMoreElements()) {
- JarEntry je = entries.nextElement();
-
- if (je.getName().matches("^" + resourceDirectoryName + "\\/.+")) {
- localDirectorySet.add(je.getName());
+ /*
+ * Ignore sonar issue, as the entries are not being expanded here.
+ */
+ JarEntry je = entries.nextElement(); // NOSONAR
+ String jeName = je.getName();
+
+ if (jeName.length() >= minLength && jeName.startsWith(dirNameWithSlash)) {
+ localDirectorySet.add(jeName);
}
}
} catch (IOException ioe) {
diff --git a/utils/src/main/java/org/onap/policy/common/utils/resources/TextFileUtils.java b/utils/src/main/java/org/onap/policy/common/utils/resources/TextFileUtils.java
index 01af7fd8..7701eae9 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/resources/TextFileUtils.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/resources/TextFileUtils.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 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.
@@ -25,7 +26,13 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.commons.io.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The Class TextFileUtils is class that provides useful functions for handling text files. Functions to read and write
@@ -33,13 +40,9 @@ import java.nio.file.Files;
*
* @author Liam Fallon (liam.fallon@est.tech)
*/
-public abstract class TextFileUtils {
- private static final String UTF_8 = "UTF-8";
- private static final int READER_CHAR_BUFFER_SIZE_4096 = 4096;
-
- private TextFileUtils() {
- // This class cannot be initialized
- }
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class TextFileUtils {
+ private static final Logger logger = LoggerFactory.getLogger(TextFileUtils.class);
/**
* Method to return the contents of a text file as a string.
@@ -49,8 +52,8 @@ public abstract class TextFileUtils {
* @throws IOException on errors reading text from the file
*/
public static String getTextFileAsString(final String textFilePath) throws IOException {
- final File textFile = new File(textFilePath);
- return new String(Files.readAllBytes(textFile.toPath()), UTF_8);
+ final var textFile = new File(textFilePath);
+ return Files.readString(textFile.toPath());
}
/**
@@ -61,7 +64,7 @@ public abstract class TextFileUtils {
* @throws IOException on errors reading text from the file
*/
public static void putStringAsTextFile(final String outString, final String textFilePath) throws IOException {
- final File textFile = new File(textFilePath);
+ final var textFile = new File(textFilePath);
if (!textFile.getParentFile().exists()) {
textFile.getParentFile().mkdirs();
}
@@ -77,7 +80,7 @@ public abstract class TextFileUtils {
* @throws IOException on errors reading text from the file
*/
public static void putStringAsFile(final String outString, final File textFile) throws IOException {
- Files.write(textFile.toPath(), outString.getBytes(UTF_8));
+ Files.writeString(textFile.toPath(), outString);
}
/**
@@ -88,7 +91,7 @@ public abstract class TextFileUtils {
* @throws IOException on errors reading text from the file
*/
public static String getStreamAsString(final InputStream textStream) throws IOException {
- return getReaderAsString(new InputStreamReader(textStream, UTF_8));
+ return getReaderAsString(new InputStreamReader(textStream, StandardCharsets.UTF_8));
}
/**
@@ -99,16 +102,37 @@ public abstract class TextFileUtils {
* @throws IOException on errors reading text from the file
*/
public static String getReaderAsString(final Reader textReader) throws IOException {
- final StringBuilder builder = new StringBuilder();
- int charsRead = -1;
- final char[] chars = new char[READER_CHAR_BUFFER_SIZE_4096];
- do {
- charsRead = textReader.read(chars);
- if (charsRead > 0) {
- builder.append(chars, 0, charsRead);
- }
+ return IOUtils.toString(textReader);
+ }
+
+ /**
+ * Creates a temporary file, only accessible by the owner.
+ *
+ * @param prefix file name prefix
+ * @param suffix file name suffix
+ * @return a new, temporary file
+ * @throws IOException if an error occurs
+ */
+ public static File createTempFile(String prefix, String suffix) throws IOException {
+ /*
+ * Disabling sonar, because setDefaultPermissions() will set the permissions of
+ * the file.
+ */
+ var file = File.createTempFile(prefix, suffix); // NOSONAR
+
+ setDefaultPermissions(file);
+
+ return file;
+ }
+
+ /**
+ * Sets permissions on a file or directory so that only the owner can access it.
+ *
+ * @param file file or directory on which permissions are to be set
+ */
+ public static void setDefaultPermissions(File file) {
+ if (!file.setReadable(true, true) || !file.setWritable(true, true) || !file.setExecutable(true, true)) {
+ logger.warn("cannot set permissions for {}", file);
}
- while (charsRead > 0);
- return builder.toString();
}
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java b/utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java
index 416c73a6..a974f1e5 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -20,12 +21,12 @@
package org.onap.policy.common.utils.security;
+import jakarta.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import javax.crypto.Cipher;
-import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
-import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -44,7 +45,9 @@ public class CryptoUtils implements CryptoCoder {
/**
* Detailed definition of encryption algorithm.
*/
- private static final String ALGORITHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING";
+ private static final String ALGORITHM_DETAILS = ALGORITHM + "/GCM/NoPadding";
+
+ private static final int TAG_SIZE_IN_BITS = 128;
private static final int IV_BLOCK_SIZE_IN_BITS = 128;
@@ -62,14 +65,14 @@ public class CryptoUtils implements CryptoCoder {
/**
* Used to generate a random "iv". Strong randomness is not needed, as this is only
- * used as a "salt".
+ * used as a "salt". (Thus sonar is disabled.)
*/
- private static final Random RANDOM = new Random();
+ private static final Random RANDOM = new Random(); // NOSONAR
/**
* CryptoUtils - encryption tool constructor.
* @param secretKeySpec
- * AES supports 128, 192 or 256-bit long key size, it can be plain text or generated with key generator
+ * AES supports 128, 192 or 256-bit long key size, it can be plain text or generated with key generator
*/
public CryptoUtils(SecretKeySpec secretKeySpec) {
this.secretKeySpec = secretKeySpec;
@@ -87,7 +90,7 @@ public class CryptoUtils implements CryptoCoder {
* <p>Final result is to put in properties file is: IV + Outcome of openssl command
*
* @param value
- * The plain text string
+ * The plain text string
* @return The encrypted String
*/
@Override
@@ -98,13 +101,13 @@ public class CryptoUtils implements CryptoCoder {
/**
* Encrypt a value based on the Policy Encryption Key.
* @param value
- * The plain text string
+ * The plain text string
* @param secretKey
- * The secret key
+ * The secret key
* @return The encrypted String
*/
public static String encrypt(String value, String secretKey) {
- SecretKeySpec keySpec = readSecretKeySpec(secretKey);
+ var keySpec = readSecretKeySpec(secretKey);
return encryptValue(value, keySpec);
}
@@ -117,10 +120,10 @@ public class CryptoUtils implements CryptoCoder {
return value;
}
try {
- Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS);
- byte[] iv = new byte[IV_BLOCK_SIZE_IN_BYTES];
+ var cipher = Cipher.getInstance(ALGORITHM_DETAILS);
+ var iv = new byte[IV_BLOCK_SIZE_IN_BYTES];
RANDOM.nextBytes(iv);
- IvParameterSpec ivspec = new IvParameterSpec(iv);
+ var ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS, iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
return "enc:" + DatatypeConverter.printBase64Binary(
@@ -137,7 +140,7 @@ public class CryptoUtils implements CryptoCoder {
* -K PrivateHexKey -iv 16BytesIVFromEncryptedString
*
* @param value
- * The encrypted string that must be decrypted using the Policy Encryption Key
+ * The encrypted string that must be decrypted using the Policy Encryption Key
* @return The String decrypted if string begin with 'enc:'
*/
@Override
@@ -149,13 +152,13 @@ public class CryptoUtils implements CryptoCoder {
* Decrypt a value based on the Policy Encryption Key if string begin with 'enc:'.
*
* @param value
- * The encrypted string that must be decrypted using the Policy Encryption Key
+ * The encrypted string that must be decrypted using the Policy Encryption Key
* @param secretKey
- * The secret key
+ * The secret key
* @return The String decrypted if string begin with 'enc:'
*/
public static String decrypt(String value, String secretKey) {
- SecretKeySpec keySpec = readSecretKeySpec(secretKey);
+ var keySpec = readSecretKeySpec(secretKey);
if (keySpec != null) {
return decryptValue(value, keySpec);
} else {
@@ -171,11 +174,11 @@ public class CryptoUtils implements CryptoCoder {
throw new IllegalArgumentException("Invalid size on input value");
}
try {
- String pureValue = value.substring(4);
+ var pureValue = value.substring(4);
byte[] encryptedValue = DatatypeConverter.parseBase64Binary(pureValue);
- Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS);
- IvParameterSpec ivspec = new IvParameterSpec(
+ var cipher = Cipher.getInstance(ALGORITHM_DETAILS);
+ var ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS,
ArrayUtils.subarray(encryptedValue, 0, IV_BLOCK_SIZE_IN_BYTES));
byte[] realData = ArrayUtils.subarray(encryptedValue, IV_BLOCK_SIZE_IN_BYTES, encryptedValue.length);
@@ -225,10 +228,10 @@ public class CryptoUtils implements CryptoCoder {
* Check if string is encrypted by verify if string prefix with 'enc:'.
*
* @param value
- * The encrypted string or plain text value
+ * The encrypted string or plain text value
* @return boolean value indicate if string prefix with enc: or not
*/
- public static Boolean isEncrypted(String value) {
+ public static boolean isEncrypted(String value) {
return (value != null && value.startsWith("enc:"));
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/services/FeatureApiUtils.java b/utils/src/main/java/org/onap/policy/common/utils/services/FeatureApiUtils.java
index e88361ea..042ee937 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/services/FeatureApiUtils.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/services/FeatureApiUtils.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,15 +23,14 @@ package org.onap.policy.common.utils.services;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
/**
* Utilities for use with "feature APIs".
*/
-public class FeatureApiUtils {
-
- private FeatureApiUtils() {
- // do nothing
- }
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class FeatureApiUtils {
/**
* Applies a function on each feature provider, stopping as soon as one returns true.
@@ -44,7 +43,7 @@ public class FeatureApiUtils {
* otherwise
*/
public static <T> boolean apply(List<T> providers, Predicate<T> predicate,
- BiConsumer<T,Exception> handleEx) {
+ BiConsumer<T, Exception> handleEx) {
for (T feature : providers) {
try {
diff --git a/utils/src/main/java/org/onap/policy/common/utils/services/OrderedServiceImpl.java b/utils/src/main/java/org/onap/policy/common/utils/services/OrderedServiceImpl.java
index bbd30220..998d6742 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/services/OrderedServiceImpl.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/services/OrderedServiceImpl.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* utils
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -24,18 +24,18 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import java.util.ServiceLoader;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is a template for building a sorted list of service instances,
- * which are discovered and created using 'ServiceLoader'.
+ * which are discovered and created using 'ServiceLoader'.
*/
public class OrderedServiceImpl<T extends OrderedService> {
// logger
- private static Logger logger = LoggerFactory.getLogger(OrderedServiceImpl.class);
+ private static Logger logger = LoggerFactory.getLogger(OrderedServiceImpl.class);
// sorted list of instances implementing the service
private List<T> implementers = null;
@@ -44,8 +44,7 @@ public class OrderedServiceImpl<T extends OrderedService> {
private ServiceLoader<T> serviceLoader = null;
// use this to ensure that we only use one unique instance of each class
- @SuppressWarnings("rawtypes")
- private static HashMap<Class,OrderedService> classToSingleton = new HashMap<>();
+ private static Map<Class<?>, OrderedService> classToSingleton = new HashMap<>();
/**
* Constructor - create the 'ServiceLoader' instance.
@@ -60,7 +59,7 @@ public class OrderedServiceImpl<T extends OrderedService> {
/**
* Get List of implementers.
- *
+ *
* @return the sorted list of services implementing interface 'T' discovered
* by 'ServiceLoader'.
*/
@@ -87,7 +86,7 @@ public class OrderedServiceImpl<T extends OrderedService> {
// build a list of all of the current implementors
List<T> tmp = new LinkedList<>();
for (T service : serviceLoader) {
- tmp.add((T)getSingleton(service));
+ tmp.add((T) getSingleton(service));
}
// Sort the list according to sequence number, and then alphabetically
diff --git a/utils/src/main/java/org/onap/policy/common/utils/services/Registry.java b/utils/src/main/java/org/onap/policy/common/utils/services/Registry.java
index c3eabe8e..8765ba8b 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/services/Registry.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/services/Registry.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,6 +22,8 @@ package org.onap.policy.common.utils.services;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,6 +31,7 @@ import org.slf4j.LoggerFactory;
* This is a simple object registry, similar in spirit to JNDI, but suitable for use in a
* stand-alone JVM.
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Registry {
private static final Logger logger = LoggerFactory.getLogger(Registry.class);
@@ -40,13 +43,6 @@ public class Registry {
private Map<String, Object> name2object = new ConcurrentHashMap<>();
/**
- * Constructs the object.
- */
- private Registry() {
- super();
- }
-
- /**
* Registers an object.
*
* @param name name by which the object is known
diff --git a/utils/src/main/java/org/onap/policy/common/utils/services/ServiceManager.java b/utils/src/main/java/org/onap/policy/common/utils/services/ServiceManager.java
index 5c8c01df..08994912 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/services/ServiceManager.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/services/ServiceManager.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP PAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,6 +23,9 @@ package org.onap.policy.common.utils.services;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
+import java.util.concurrent.atomic.AtomicBoolean;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
import org.onap.policy.common.capabilities.Startable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,6 +40,7 @@ public class ServiceManager implements Startable {
/**
* Manager name.
*/
+ @Getter
private final String name;
/**
@@ -47,7 +51,7 @@ public class ServiceManager implements Startable {
/**
* {@code True} if the services are currently running, {@code false} otherwise.
*/
- private boolean running;
+ private final AtomicBoolean running = new AtomicBoolean(false);
/**
* Constructs the object, with a default name.
@@ -58,16 +62,13 @@ public class ServiceManager implements Startable {
/**
* Constructs the object.
+ *
* @param name the manager's name, used for logging purposes
*/
public ServiceManager(String name) {
this.name = name;
}
- public String getName() {
- return name;
- }
-
/**
* Adds a pair of service actions to the manager.
*
@@ -77,7 +78,7 @@ public class ServiceManager implements Startable {
* @return this manager
*/
public synchronized ServiceManager addAction(String stepName, RunnableWithEx starter, RunnableWithEx stopper) {
- if (running) {
+ if (isAlive()) {
throw new IllegalStateException(name + " is already running; cannot add " + stepName);
}
@@ -94,7 +95,7 @@ public class ServiceManager implements Startable {
* @return this manager
*/
public synchronized ServiceManager addService(String stepName, Startable service) {
- if (running) {
+ if (isAlive()) {
throw new IllegalStateException(name + " is already running; cannot add " + stepName);
}
@@ -103,13 +104,13 @@ public class ServiceManager implements Startable {
}
@Override
- public synchronized boolean isAlive() {
- return running;
+ public boolean isAlive() {
+ return running.get();
}
@Override
public synchronized boolean start() {
- if (running) {
+ if (isAlive()) {
throw new IllegalStateException(name + " is already running");
}
@@ -134,7 +135,7 @@ public class ServiceManager implements Startable {
if (ex == null) {
logger.info("{} started", name);
- running = true;
+ running.set(true);
return true;
}
@@ -151,11 +152,11 @@ public class ServiceManager implements Startable {
@Override
public synchronized boolean stop() {
- if (!running) {
+ if (!isAlive()) {
throw new IllegalStateException(name + " is not running");
}
- running = false;
+ running.set(false);
rewind(items);
return true;
@@ -203,20 +204,20 @@ public class ServiceManager implements Startable {
/**
* Service information.
*/
+ @AllArgsConstructor
private static class Service {
private String stepName;
private RunnableWithEx starter;
private RunnableWithEx stopper;
-
- public Service(String stepName, RunnableWithEx starter, RunnableWithEx stopper) {
- this.stepName = stepName;
- this.starter = starter;
- this.stopper = stopper;
- }
}
+ /*
+ * Cannot use a plain Runnable, because it can't throw exceptions. Could use a
+ * Callable, instead, but then all the lambda expressions become rather messy, thus
+ * we'll stick with RunnableWithEx, and just disable the sonar warning.
+ */
@FunctionalInterface
public static interface RunnableWithEx {
- void run() throws Exception;
+ void run() throws Exception; // NOSONAR
}
}
diff --git a/utils/src/main/java/org/onap/policy/common/utils/time/CurrentTime.java b/utils/src/main/java/org/onap/policy/common/utils/time/CurrentTime.java
index 857b69b6..95f4d69a 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/time/CurrentTime.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/time/CurrentTime.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* Common Utils
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -21,24 +21,18 @@
package org.onap.policy.common.utils.time;
import java.util.Date;
+import lombok.NoArgsConstructor;
/**
* Methods to access the current time. Classes can use objects of this type to get current
* time information, while allowing the objects to be overridden by junit tests.
*/
+@NoArgsConstructor
public class CurrentTime {
/**
- * Constructor.
- *
- */
- public CurrentTime() {
- super();
- }
-
- /**
* Get the millisecond time.
- *
+ *
* @return the current time, in milliseconds
*/
public long getMillis() {
@@ -47,7 +41,7 @@ public class CurrentTime {
/**
* Get the current date.
- *
+ *
* @return the current Date
*/
public Date getDate() {
@@ -56,7 +50,7 @@ public class CurrentTime {
/**
* Sleeps for a period of time.
- *
+ *
* @param sleepMs amount of time to sleep, in milliseconds
* @throws InterruptedException can be interrupted
*/
diff --git a/utils/src/main/java/org/onap/policy/common/utils/validation/Assertions.java b/utils/src/main/java/org/onap/policy/common/utils/validation/Assertions.java
index 047989e7..8e474204 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/validation/Assertions.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/validation/Assertions.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications 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.
@@ -22,6 +22,8 @@
package org.onap.policy.common.utils.validation;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,17 +31,12 @@ import org.slf4j.LoggerFactory;
* The Class Assertions is a static class that is used as a shorthand for assertions in the source code.
* It throws runtime exceptions on assertion fails.
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Assertions {
// Logger for this class
private static final Logger LOGGER = LoggerFactory.getLogger(Assertions.class);
/**
- * Private constructor used to prevent sub class instantiation.
- */
- private Assertions() {
- }
-
- /**
* Gets the validation message for a string parameter.
*
* @param parameterName the string parameter name
diff --git a/utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java b/utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java
index f15d936b..0723242d 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications 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.
@@ -21,17 +21,17 @@
package org.onap.policy.common.utils.validation;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+
/**
* Class to provide utility methods for common parameter validations.
*
* @author Ram Krishna Verma (ram.krishna.verma@ericsson.com)
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ParameterValidationUtils {
- private ParameterValidationUtils() {
-
- }
-
/**
* Validates the given string input.
*
diff --git a/utils/src/main/java/org/onap/policy/common/utils/validation/Version.java b/utils/src/main/java/org/onap/policy/common/utils/validation/Version.java
index 41ff832a..46e006bd 100644
--- a/utils/src/main/java/org/onap/policy/common/utils/validation/Version.java
+++ b/utils/src/main/java/org/onap/policy/common/utils/validation/Version.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP COMMON
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,8 +21,7 @@
package org.onap.policy.common.utils.validation;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+import com.google.re2j.Pattern;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
@@ -56,14 +55,13 @@ public class Version implements Comparable<Version> {
* @param versionString the version string
*/
public Version(@NonNull final String versionString) {
- Version newVersion = makeVersion("String", "constructor", versionString);
+ var newVersion = makeVersion("String", "constructor", versionString);
if (newVersion != null) {
this.major = newVersion.major;
this.minor = newVersion.minor;
this.patch = newVersion.patch;
- }
- else {
+ } else {
this.major = 0;
this.minor = 0;
this.patch = 0;
@@ -80,7 +78,7 @@ public class Version implements Comparable<Version> {
* that does not match the major.minor.patch form)
*/
public static Version makeVersion(String type, String name, String versionText) {
- Matcher matcher = VERSION_PAT.matcher(versionText);
+ var matcher = VERSION_PAT.matcher(versionText);
if (!matcher.matches()) {
logger.info("invalid version for {} {}: {}", type, name, versionText);
return null;
@@ -114,7 +112,7 @@ public class Version implements Comparable<Version> {
@Override
public int compareTo(Version other) {
- int result = Integer.compare(major, other.major);
+ var result = Integer.compare(major, other.major);
if (result != 0) {
return result;
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java b/utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java
new file mode 100644
index 00000000..b45f107d
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java
@@ -0,0 +1,181 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.utils.cmd;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.junit.Test;
+
+public class TestCommandLineArguments {
+ private static final String FAKE_HELP_CLASS = "org.onap.policy.HelpClass";
+ private static final String FAKE_COMPONENT = "fake policy cpm";
+ private static final String TEST_CONFIG_FILE = "cmdFiles/configuration.json";
+ private static final String TEST_PROPERTY_FILE = "cmdFiles/property.json";
+ private static final String ERR_MSG_INVALID_ARGS = "invalid command line arguments specified";
+ private static final String ERR_MSG_POLICY_CONFIG_FILE =
+ "fake policy cpm configuration file was not specified as an argument";
+
+ CommandLineArgumentsHandler testCmd = new CommandLineArgumentsHandler(FAKE_HELP_CLASS, FAKE_COMPONENT);
+
+ @Test
+ public void testVersion() throws CommandLineException {
+ String[] version = {"-v"};
+ assertThat(testCmd.parse(version)).startsWith("ONAP Version test.");
+ }
+
+ @Test
+ public void testHelp() throws CommandLineException {
+ String[] help = {"-h"};
+ assertThat(testCmd.parse(help)).startsWith("usage: org.onap.policy.HelpClass [options...]");
+ }
+
+ @Test
+ public void testParse() throws CommandLineException {
+ String[] args = {"-c", TEST_CONFIG_FILE};
+ testCmd.parse(args);
+
+ assertTrue(testCmd.checkSetConfigurationFilePath());
+ assertThat(testCmd.getFullConfigurationFilePath()).contains(TEST_CONFIG_FILE);
+ }
+
+ @Test
+ public void testParse_ShouldThrowExceptionWithInvalidArguments() {
+ String[] invalidArgs = {"-a"};
+ assertThatThrownBy(() -> testCmd.parse(invalidArgs)).hasMessage(ERR_MSG_INVALID_ARGS)
+ .hasRootCauseMessage("Unrecognized option: -a");
+ }
+
+ @Test
+ public void testParse_ShouldThrowExceptionWithExtraArguments() {
+ String[] remainingArgs = {"-c", TEST_CONFIG_FILE, "extraArgs"};
+ String expectedErrorMsg =
+ "too many command line arguments specified: [-c, cmdFiles/configuration.json, extraArgs]";
+ assertThatThrownBy(() -> testCmd.parse(remainingArgs)).hasMessage(expectedErrorMsg);
+ }
+
+ @Test
+ public void testParse_ShouldThrowExceptionWhenFileNameNull() {
+ String[] nullArgs = {"-c", null};
+ assertThatThrownBy(() -> testCmd.parse(nullArgs)).hasMessage(ERR_MSG_INVALID_ARGS);
+ }
+
+ @Test
+ public void testValidate() throws CommandLineException {
+ String[] validConfigArgs = {"-c", TEST_CONFIG_FILE};
+ testCmd.parse(validConfigArgs);
+ assertThatCode(() -> testCmd.validate()).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testValidate_ShouldThrowExceptionWhenConfigFileNotPresent() throws CommandLineException {
+ String[] versionArgs = {"-v"};
+ testCmd.parse(versionArgs);
+ assertValidate(versionArgs, ERR_MSG_POLICY_CONFIG_FILE);
+ }
+
+ @Test
+ public void testValidate_ShouldThrowExceptionWhenFileNameEmpty() {
+ String[] argsOnlyKeyNoValue = {"-c", ""};
+ assertValidate(argsOnlyKeyNoValue, ERR_MSG_POLICY_CONFIG_FILE);
+ assertFalse(testCmd.checkSetConfigurationFilePath());
+ }
+
+ @Test
+ public void testValidate_ShouldThrowExceptionWhenFileNameEmptySpace() {
+ String[] argsOnlyKeyNoValue = {"-c", " "};
+ assertValidate(argsOnlyKeyNoValue, ERR_MSG_POLICY_CONFIG_FILE);
+ assertFalse(testCmd.checkSetConfigurationFilePath());
+ }
+
+ @Test
+ public void testValidate_ShouldThrowExceptionWhenFileNameDoesNotExist() {
+ String[] fileNameNotExistentArgs = {"-c", "someFileName.json"};
+ assertValidate(fileNameNotExistentArgs,
+ "fake policy cpm configuration file \"someFileName.json\" does not exist");
+ }
+
+ @Test
+ public void testValidate_ShouldThrowExceptionWhenFileNameIsNotFile() {
+ String[] folderAsFileNameArgs = {"-c", "src/test/resources"};
+ assertValidate(folderAsFileNameArgs,
+ "fake policy cpm configuration file \"src/test/resources\" is not a normal file");
+ }
+
+ @Test
+ public void testAddExtraOptions() throws CommandLineException {
+ Option extra = Option.builder("p").longOpt("property-file")
+ .desc("the full path to the topic property file to use, the property file contains the "
+ + FAKE_COMPONENT + " properties")
+ .hasArg().argName("PROP_FILE").required(false).type(String.class).build();
+
+ CommandLineArgumentsHandler testCmdExtraOpt =
+ new CommandLineArgumentsHandler(FAKE_HELP_CLASS, FAKE_COMPONENT, extra);
+
+ String[] args = {"-p", TEST_PROPERTY_FILE};
+ testCmdExtraOpt.parse(args);
+
+ assertTrue(testCmdExtraOpt.checkSetPropertyFilePath());
+ assertThat(testCmdExtraOpt.getFullPropertyFilePath()).contains(TEST_PROPERTY_FILE);
+
+ String[] argsNoProperty = {"-p", ""};
+ testCmdExtraOpt.parse(argsNoProperty);
+
+ assertFalse(testCmdExtraOpt.checkSetPropertyFilePath());
+ }
+
+ @Test
+ public void testNewOptions() throws CommandLineException {
+ Options newOptions = new Options();
+ newOptions.addOption(
+ Option.builder("a").longOpt("fake-option").desc("the fake property to check command line parse")
+ .hasArg().argName("FAKE_OPT").required(false).type(String.class).build());
+
+ CommandLineArgumentsHandler testCmdExtraOpt =
+ new CommandLineArgumentsHandler(FAKE_HELP_CLASS, FAKE_COMPONENT, newOptions);
+
+ String[] args = {"-a", "aaaa"};
+ testCmdExtraOpt.parse(args);
+
+ assertTrue(testCmdExtraOpt.getCommandLine().hasOption("a"));
+
+ // should raise exception as -c is not present on options;
+ // default options should've been replaced by constructor parameter.
+ String[] argsError = {"-c", "aaaa.json"};
+ assertThatThrownBy(() -> testCmdExtraOpt.parse(argsError)).hasMessage(ERR_MSG_INVALID_ARGS)
+ .hasRootCauseMessage("Unrecognized option: -c");
+ }
+
+ private void assertValidate(String[] testArgs, String expectedErrorMsg) {
+ try {
+ testCmd.parse(testArgs);
+ } catch (CommandLineException e) {
+ fail(e.getMessage());
+ }
+ assertThatThrownBy(() -> testCmd.validate()).hasMessage(expectedErrorMsg);
+ }
+}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/CoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/CoderTest.java
new file mode 100644
index 00000000..01821504
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/CoderTest.java
@@ -0,0 +1,129 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.utils.coder;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Writer;
+import org.junit.Before;
+import org.junit.Test;
+
+public class CoderTest {
+ private static final Long LONG = 10L;
+ private static final Integer INTEGER = 10;
+ private static final String INT_TEXT = INTEGER.toString();
+ private static final String TEXT = "some text";
+ private static final String ENCODED = "encoded value";
+ private static final String DECODED = "decoded value";
+
+ private MyCoder coder;
+
+ @Before
+ public void setUp() {
+ coder = new MyCoder();
+ }
+
+ @Test
+ public void testConvert() throws CoderException {
+ assertNull(coder.convert(null, String.class));
+
+ // same class of object
+ assertEquals(TEXT, coder.convert(TEXT, String.class));
+ assertEquals(INTEGER, coder.convert(INTEGER, Integer.class));
+
+ // source is a string
+ assertEquals(INTEGER, coder.convert(TEXT, Integer.class));
+
+ // target is a string
+ assertEquals(INT_TEXT, coder.convert(INTEGER, String.class));
+
+ // source and target are different types, neither is a string
+ assertEquals(INTEGER, coder.convert(LONG, Integer.class));
+ }
+
+ private static class MyCoder implements Coder {
+ @Override
+ public String encode(Object object) throws CoderException {
+ return (object.getClass() == String.class ? ENCODED : INT_TEXT);
+ }
+
+ @Override
+ public String encode(Object object, boolean pretty) throws CoderException {
+ // unused
+ return null;
+ }
+
+ @Override
+ public void encode(Writer target, Object object) throws CoderException {
+ // unused
+ }
+
+ @Override
+ public void encode(OutputStream target, Object object) throws CoderException {
+ // unused
+ }
+
+ @Override
+ public void encode(File target, Object object) throws CoderException {
+ // unused
+ }
+
+ @Override
+ public <T> T decode(String json, Class<T> clazz) throws CoderException {
+ return (clazz == String.class ? clazz.cast(DECODED) : clazz.cast(INTEGER));
+ }
+
+ @Override
+ public <T> T decode(Reader source, Class<T> clazz) throws CoderException {
+ // unused
+ return null;
+ }
+
+ @Override
+ public <T> T decode(InputStream source, Class<T> clazz) throws CoderException {
+ // unused
+ return null;
+ }
+
+ @Override
+ public <T> T decode(File source, Class<T> clazz) throws CoderException {
+ // unused
+ return null;
+ }
+
+ @Override
+ public StandardCoderObject toStandard(Object object) throws CoderException {
+ // unused
+ return null;
+ }
+
+ @Override
+ public <T> T fromStandard(StandardCoderObject sco, Class<T> clazz) throws CoderException {
+ // unused
+ return null;
+ }
+ }
+}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java
index 83017e70..86f8a1b1 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -23,28 +23,39 @@ package org.onap.policy.common.utils.coder;
import static org.junit.Assert.assertEquals;
import com.google.gson.annotations.SerializedName;
-
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
-
import lombok.Getter;
-
import org.junit.Before;
import org.junit.Test;
public class PropertyCoderTest {
private PropertyCoder propertyCoder = null;
private static final String AES_ENCRYPTION_KEY = "aes_encryption_key";
+
+ /*
+ * Note: to generate the encrypted values, invoke CryptoUtils passing both the value
+ * to be encrypted and the secret key.
+ *
+ * The secret key should typically be 32 characters long, resulting in a 256-bit
+ * key, and is placed in "aes_encryption_key".
+ *
+ * For "xacml.pdp.rest.password", the encrypted value was generated via:
+ * java org.onap.policy.common.utils.security.CryptoUtils enc alpha abcdefghijklmnopqrstuvwxyzabcdef
+ *
+ * For "pass", the encrypted value was generated via:
+ * java org.onap.policy.common.utils.security.CryptoUtils enc hello abcdefghijklmnopqrstuvwxyzabcdef
+ */
private static final String json =
("{'aes_encryption_key':'abcdefghijklmnopqrstuvwxyzabcdef'"
- + ",'xacml.pdp.rest.password':'enc:YZ8EqzsxIOzIuK416SWAdrv+0cKKkqsQt/NYH9+uxwI='"
+ + ",'xacml.pdp.rest.password':'enc:FSfOhDygtmnX3gkMSfTFMoBFW+AG5k6goNj2KZgQmeF0DqgcMg=='"
+ ",'xacml.pdp.rest.user':'testpdp'"
+ ",'xacml.pdp.rest.client.user':'policy'"
+ ",'xacml.pdp.rest.client.password':'policy'"
+ ",'xacml.pdp.rest.environment':'TEST'"
+ ",'servers':[{'name':'server1','port':'10',"
- + "'pass':'enc:KXIY94KcAapOAAeFbtjQL4kBPB4k+NJfwdP+GpG3LWQ='}"
+ + "'pass':'enc:08Fj6tLhmWjkZkf52O2A2ZNT8PpL80yEOEKXlbV/gnm0lkR9OA=='}"
+ ",{'name':'server2','port':'20','pass':'plaintext'}]"
+ "}").replace('\'', '"');
@@ -102,4 +113,4 @@ public class PropertyCoderTest {
private String port;
private String pass;
}
-} \ No newline at end of file
+}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillisTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillisTest.java
new file mode 100644
index 00000000..ec977da6
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillisTest.java
@@ -0,0 +1,160 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP PAP
+ * ================================================================================
+ * Copyright (C) 2019-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.utils.coder;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import com.google.gson.JsonElement;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import lombok.ToString;
+import org.junit.Before;
+import org.junit.Test;
+
+public class StandardCoderInstantAsMillisTest {
+ private static final long INSTANT_MILLIS = 1583249713500L;
+ private static final String INSTANT_TEXT = String.valueOf(INSTANT_MILLIS);
+
+ private StandardCoder coder;
+
+ @Before
+ public void setUp() {
+ coder = new StandardCoderInstantAsMillis();
+ }
+
+ @Test
+ public void testConvert() throws CoderException {
+ MyObject obj = makeObject();
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> map = coder.convert(obj, LinkedHashMap.class);
+
+ assertThat(map.toString()).contains(INSTANT_TEXT);
+
+ MyObject obj2 = coder.convert(map, MyObject.class);
+ assertEquals(obj.toString(), obj2.toString());
+ }
+
+ @Test
+ public void testEncodeDecode() throws CoderException {
+ MyObject obj = makeObject();
+ assertThat(coder.encode(obj, false)).contains(INSTANT_TEXT);
+ assertThat(coder.encode(obj, true)).contains(INSTANT_TEXT);
+
+ String json = coder.encode(obj);
+ MyObject obj2 = coder.decode(json, MyObject.class);
+ assertEquals(obj.toString(), obj2.toString());
+
+ StringWriter wtr = new StringWriter();
+ coder.encode(wtr, obj);
+ json = wtr.toString();
+ assertThat(json).contains(INSTANT_TEXT);
+
+ StringReader rdr = new StringReader(json);
+ obj2 = coder.decode(rdr, MyObject.class);
+ assertEquals(obj.toString(), obj2.toString());
+ }
+
+ @Test
+ public void testJson() {
+ MyObject obj = makeObject();
+ assertThat(coder.toPrettyJson(obj)).contains(INSTANT_TEXT);
+ }
+
+ @Test
+ public void testToJsonTree_testFromJsonJsonElementClassT() throws Exception {
+ MyMap map = new MyMap();
+ map.props = new LinkedHashMap<>();
+ map.props.put("jel keyA", "jel valueA");
+ map.props.put("jel keyB", "jel valueB");
+
+ JsonElement json = coder.toJsonTree(map);
+ assertEquals("{'props':{'jel keyA':'jel valueA','jel keyB':'jel valueB'}}".replace('\'', '"'), json.toString());
+
+ Object result = coder.fromJson(json, MyMap.class);
+
+ assertNotNull(result);
+ assertEquals("{jel keyA=jel valueA, jel keyB=jel valueB}", result.toString());
+ }
+
+ @Test
+ public void testConvertFromDouble() throws Exception {
+ String text = "[listA, {keyA=100}, 200]";
+ assertEquals(text, coder.decode(text, Object.class).toString());
+
+ text = "{keyB=200}";
+ assertEquals(text, coder.decode(text, Object.class).toString());
+ }
+
+ @Test
+ public void testToStandard() throws Exception {
+ MyObject obj = makeObject();
+ StandardCoderObject sco = coder.toStandard(obj);
+ assertNotNull(sco.getData());
+ assertEquals("{'abc':'xyz','instant':1583249713500}".replace('\'', '"'), sco.getData().toString());
+
+ // class instead of object -> exception
+ assertThatThrownBy(() -> coder.toStandard(String.class)).isInstanceOf(CoderException.class);
+ }
+
+ @Test
+ public void testFromStandard() throws Exception {
+ MyObject obj = new MyObject();
+ obj.abc = "pdq";
+ StandardCoderObject sco = coder.toStandard(obj);
+
+ MyObject obj2 = coder.fromStandard(sco, MyObject.class);
+ assertEquals(obj.toString(), obj2.toString());
+
+ // null class -> exception
+ assertThatThrownBy(() -> coder.fromStandard(sco, null)).isInstanceOf(CoderException.class);
+ }
+
+
+ private MyObject makeObject() {
+ MyObject obj = new MyObject();
+ obj.abc = "xyz";
+ obj.instant = Instant.ofEpochMilli(INSTANT_MILLIS);
+ return obj;
+ }
+
+
+ @ToString
+ private static class MyObject {
+ private String abc;
+ private Instant instant;
+ }
+
+ public static class MyMap {
+ private Map<String, Object> props;
+
+ @Override
+ public String toString() {
+ return props.toString();
+ }
+ }
+}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java
index 44086f30..1748aed3 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -20,6 +20,7 @@
package org.onap.policy.common.utils.coder;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -34,10 +35,11 @@ public class StandardCoderObjectTest {
private static final String PROP1 = "abc";
private static final String PROP2 = "ghi";
+ private static final Integer PROP2_INDEX = 1;
private static final String PROP2b = "jkl";
private static final String VAL1 = "def";
private static final String VAL2 = "mno";
- private static final String JSON = "{'abc':'def','ghi':{'jkl':'mno'}}".replace('\'', '"');
+ private static final String JSON = "{'abc':'def','ghi':[{},{'jkl':'mno'}]}".replace('\'', '"');
private StandardCoderObject sco;
@@ -68,7 +70,7 @@ public class StandardCoderObjectTest {
assertEquals(VAL1, sco.getString(PROP1));
// multiple fields
- assertEquals(VAL2, sco.getString(PROP2, PROP2b));
+ assertEquals(VAL2, sco.getString(PROP2, PROP2_INDEX, PROP2b));
// not found
assertNull(sco.getString("xyz"));
@@ -85,5 +87,44 @@ public class StandardCoderObjectTest {
// not a JSON object
assertNull(sco.getString(PROP1, PROP2));
+
+ // invalid subscript
+ assertThatIllegalArgumentException().isThrownBy(() -> sco.getString(10.0));
+ }
+
+ @Test
+ public void testGetFieldFromObject() {
+ // not an object
+ assertNull(sco.getFieldFromObject(fromJson("[]"), PROP1));
+
+ // field doesn't exist
+ assertNull(sco.getFieldFromObject(fromJson("{}"), "non-existent"));
+
+ // field exists
+ assertEquals(4, sco.getFieldFromObject(fromJson("{\"world\":4}"), "world").getAsInt());
+ }
+
+ @Test
+ public void testGetItemFromArray() {
+ // not an array
+ assertNull(sco.getItemFromArray(fromJson("{}"), 0));
+
+ // negative index
+ assertThatIllegalArgumentException().isThrownBy(() -> sco.getItemFromArray(fromJson("[]"), -1));
+
+ // index out of bounds
+ assertNull(sco.getItemFromArray(fromJson("[5]"), 1));
+ assertNull(sco.getItemFromArray(fromJson("[5]"), 2));
+
+ // index exists
+ assertEquals(6, sco.getItemFromArray(fromJson("[5,6,7]"), 1).getAsInt());
+
+ // edge case: first and last item
+ assertEquals(50, sco.getItemFromArray(fromJson("[50,60,70]"), 0).getAsInt());
+ assertEquals(700, sco.getItemFromArray(fromJson("[500,600,700]"), 2).getAsInt());
+ }
+
+ private JsonElement fromJson(String json) {
+ return gson.fromJson(json, JsonElement.class);
}
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java
index 2a70f85a..33c7331e 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP PAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,12 +23,15 @@ package org.onap.policy.common.utils.coder;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
+import com.google.gson.JsonSyntaxException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -45,8 +48,11 @@ import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
+import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.TreeMap;
+import lombok.ToString;
import org.junit.Before;
import org.junit.Test;
@@ -64,6 +70,35 @@ public class StandardCoderTest {
}
@Test
+ public void testConvert() throws CoderException {
+ // null source
+ assertNull(coder.convert(null, StandardCoderObject.class));
+
+ // same class of object
+ StandardCoderObject sco = new StandardCoderObject();
+ assertSame(sco, coder.convert(sco, StandardCoderObject.class));
+
+ // source is a string
+ assertEquals(Integer.valueOf(10), coder.convert("10", Integer.class));
+
+ // target is a string
+ assertEquals("10", coder.convert(10, String.class));
+
+ // source and target are different types, neither is a string
+ sco = coder.convert(Map.of("hello", "world"), StandardCoderObject.class);
+ assertEquals("world", sco.getString("hello"));
+
+ // throw an exeception
+ coder = new StandardCoder() {
+ @Override
+ protected <T> T fromJson(JsonElement json, Class<T> clazz) {
+ throw jpe;
+ }
+ };
+ assertThatThrownBy(() -> coder.convert(10, Long.class)).isInstanceOf(CoderException.class).hasCause(jpe);
+ }
+
+ @Test
public void testEncodeObject() throws Exception {
List<Integer> arr = Arrays.asList(1100, 1110);
assertEquals("[1100,1110]", coder.encode(arr));
@@ -75,6 +110,32 @@ public class StandardCoderTest {
}
@Test
+ public void testEncodeObjectBoolean() throws Exception {
+ final List<Integer> arr = Arrays.asList(1100, 1110);
+
+ /*
+ * As plain json.
+ */
+ assertEquals("[1100,1110]", coder.encode(arr, false));
+
+ // test exception case
+ coder = spy(new StandardCoder());
+ when(coder.toJson(arr)).thenThrow(jpe);
+ assertThatThrownBy(() -> coder.encode(arr, false)).isInstanceOf(CoderException.class).hasCause(jpe);
+
+
+ /*
+ * As pretty json.
+ */
+ assertEquals("[\n 1100,\n 1110\n]", coder.encode(arr, true));
+
+ // test exception case
+ coder = spy(new StandardCoder());
+ when(coder.toPrettyJson(arr)).thenThrow(jpe);
+ assertThatThrownBy(() -> coder.encode(arr, true)).isInstanceOf(CoderException.class).hasCause(jpe);
+ }
+
+ @Test
public void testEncodeWriterObject() throws Exception {
List<Integer> arr = Arrays.asList(1200, 1210);
StringWriter wtr = new StringWriter();
@@ -260,7 +321,9 @@ public class StandardCoderTest {
assertEquals(json, coder.toJson(sco));
// invalid json -> exception
- assertThatThrownBy(() -> coder.fromJson(new StringReader("["), StandardCoderObject.class));
+ StringReader rdr = new StringReader("[");
+ assertThatThrownBy(() -> coder.fromJson(rdr, StandardCoderObject.class))
+ .isInstanceOf(JsonSyntaxException.class);
}
@Test
@@ -281,16 +344,24 @@ public class StandardCoderTest {
assertEquals(-10, map.props.get("negInt"));
assertEquals(100000000000L, map.props.get("posLong"));
assertEquals(12.5, map.props.get("doubleVal"));
+
+ // test when decoding into a map
+ @SuppressWarnings("unchecked")
+ Map<String, Object> map2 = coder.decode("{'intValue':10, 'dblVal':20.1}", TreeMap.class);
+ assertEquals("{dblVal=20.1, intValue=10}", map2.toString());
+ }
+
+ @Test
+ public void testListDouble() throws Exception {
+ @SuppressWarnings("unchecked")
+ List<Object> list = coder.decode("[10, 20.1, 30]", LinkedList.class);
+ assertEquals("[10, 20.1, 30]", list.toString());
}
+ @ToString
private static class MyObject {
private String abc;
-
- @Override
- public String toString() {
- return "MyObject [abc=" + abc + "]";
- }
}
public static class MyMap {
diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java
new file mode 100644
index 00000000..2fcdb0dd
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java
@@ -0,0 +1,165 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.utils.coder;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.worldturner.medeia.api.ValidationFailedException;
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.List;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.junit.Before;
+import org.junit.Test;
+
+public class StandardValCoderTest {
+ private String jsonSchema;
+ private String validJson;
+ private String missingReqJson;
+ private String badRegexJson;
+
+ @Data
+ @NoArgsConstructor
+ public static class ValOuter {
+ @Data
+ @NoArgsConstructor
+ public static class ValInner {
+ public String subItemString;
+ public Integer subItemInteger;
+ }
+
+ public String aaString;
+ public int anInteger;
+ public boolean aaBoolean;
+ public List<ValInner> aaCollection;
+ }
+
+ @Before
+ public void testSetUp() throws Exception {
+ jsonSchema = getJson("src/test/resources/org/onap/policy/common/utils/coder/test.schema.json");
+ validJson = getJson("src/test/resources/org/onap/policy/common/utils/coder/valid.json");
+ missingReqJson = getJson("src/test/resources/org/onap/policy/common/utils/coder/missing-required.json");
+ badRegexJson = getJson("src/test/resources/org/onap/policy/common/utils/coder/bad-regex.json");
+ }
+
+ @Test
+ public void testDecode() throws CoderException {
+ StandardValCoder valCoder = new StandardValCoder(jsonSchema, "test-schema");
+
+ ValOuter valOuter = valCoder.decode(validJson, ValOuter.class);
+ assertValidJson(valOuter);
+
+ StringReader reader = new StringReader(validJson);
+ valOuter = valCoder.decode(reader, ValOuter.class);
+ assertValidJson(valOuter);
+
+ try {
+ valCoder.decode(missingReqJson, ValOuter.class);
+ fail("missing required field should have been flagged by the schema validation");
+ } catch (CoderException e) {
+ assertEquals("required", ((ValidationFailedException) e.getCause()).getFailures().get(0).getRule());
+ assertEquals("aaCollection",
+ ((ValidationFailedException) e.getCause()).getFailures().get(0).getProperty());
+ assertEquals("Required property aaCollection is missing from object",
+ ((ValidationFailedException) e.getCause()).getFailures().get(0).getMessage());
+ }
+
+ try {
+ valCoder.decode(badRegexJson, ValOuter.class);
+ fail("bad regex should have been flagged by the schema validation");
+ } catch (CoderException e) {
+ assertEquals("properties", ((ValidationFailedException) e.getCause()).getFailures().get(0).getRule());
+ assertEquals("aaString",
+ ((ValidationFailedException) e.getCause()).getFailures().get(0).getProperty());
+ assertEquals("Property validation failed",
+ ((ValidationFailedException) e.getCause()).getFailures().get(0).getMessage());
+ assertEquals("pattern",
+ ((ValidationFailedException) e.getCause()).getFailures()
+ .get(0).getDetails().iterator().next().getRule());
+ assertEquals("Pattern ^([a-z]*)$ is not contained in text",
+ ((ValidationFailedException) e.getCause()).getFailures()
+ .get(0).getDetails().iterator().next().getMessage());
+ }
+ }
+
+ @Test
+ public void testEncode() throws CoderException {
+ StandardValCoder valCoder = new StandardValCoder(jsonSchema, "test-schema");
+ ValOuter valOuter = valCoder.decode(validJson, ValOuter.class);
+
+ String valOuterJson = valCoder.encode(valOuter);
+ assertEquals(valOuter, valCoder.decode(valOuterJson, ValOuter.class));
+ assertValidJson(valOuter);
+
+ StringWriter writer = new StringWriter();
+ valCoder.encode(writer, valOuter);
+ assertEquals(valOuterJson, writer.toString());
+
+ // test exception case with an empty object
+ assertThatThrownBy(() -> valCoder.encode(new ValOuter())).isInstanceOf(CoderException.class);
+ }
+
+ @Test
+ public void testPretty() throws CoderException {
+ StandardValCoder valCoder = new StandardValCoder(jsonSchema, "test-schema");
+ ValOuter valOuter = valCoder.decode(validJson, ValOuter.class);
+
+ String valOuterJson = valCoder.encode(valOuter);
+ assertEquals(valOuterJson, valCoder.encode(valOuter, false));
+ String prettyValOuterJson = valCoder.encode(valOuter, true);
+ assertNotEquals(valOuterJson, prettyValOuterJson);
+
+ assertEquals(valOuter, valCoder.decode(prettyValOuterJson, ValOuter.class));
+
+ // test exception cases with an empty object
+ assertThatThrownBy(() -> valCoder.encode(new ValOuter(), false)).isInstanceOf(CoderException.class);
+ assertThatThrownBy(() -> valCoder.encode(new ValOuter(), true)).isInstanceOf(CoderException.class);
+ }
+
+ @Test
+ public void testConformance() {
+ StandardValCoder valCoder = new StandardValCoder(jsonSchema, "test-schema");
+ assertTrue(valCoder.isConformant(validJson));
+ assertFalse(valCoder.isConformant(missingReqJson));
+ assertFalse(valCoder.isConformant(badRegexJson));
+ }
+
+ private void assertValidJson(ValOuter valOuter) {
+ assertEquals("abcd", valOuter.getAaString());
+ assertEquals(90, valOuter.getAnInteger());
+ assertTrue(valOuter.isAaBoolean());
+ assertEquals("defg", valOuter.getAaCollection().get(0).getSubItemString());
+ assertEquals(Integer.valueOf(1200), valOuter.getAaCollection().get(0).getSubItemInteger());
+ }
+
+ private String getJson(String filePath) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(filePath)));
+ }
+} \ No newline at end of file
diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java
index e38c5c9c..cadeb055 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -20,8 +20,11 @@
package org.onap.policy.common.utils.coder;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
import java.io.File;
import java.io.StringWriter;
@@ -45,6 +48,25 @@ public class StandardYamlCoderTest {
}
@Test
+ public void testToPrettyJson() throws CoderException {
+ String expected = coder.encode(cont);
+ assertEquals(expected, coder.encode(cont, false));
+
+ String yaml = coder.encode(cont, true);
+ assertEquals(expected, yaml);
+
+ Container cont2 = coder.decode(yaml, Container.class);
+ assertEquals(cont, cont2);
+
+ // test exception cases
+ IllegalArgumentException expex = new IllegalArgumentException("expected exception");
+ coder = spy(new StandardYamlCoder());
+ when(coder.toJson(cont)).thenThrow(expex);
+ assertThatThrownBy(() -> coder.encode(cont, false)).isInstanceOf(CoderException.class).hasCause(expex);
+ assertThatThrownBy(() -> coder.encode(cont, true)).isInstanceOf(CoderException.class).hasCause(expex);
+ }
+
+ @Test
public void testToJsonObject() throws CoderException {
String yaml = coder.encode(cont);
@@ -75,6 +97,12 @@ public class StandardYamlCoderTest {
}
@Test
+ public void testFromJsonDoubleToInteger() throws Exception {
+ Object value = coder.decode("20", Object.class);
+ assertEquals(Integer.valueOf(20), value);
+ }
+
+ @Test
public void testStandardTypeAdapter() throws Exception {
String yaml = "abc: def\n";
StandardCoderObject sco = coder.fromJson(yaml, StandardCoderObject.class);
diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java
index 589d0924..17d7f7ff 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Common Utils
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 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.
@@ -25,8 +26,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import javax.persistence.EntityManager;
-
+import jakarta.persistence.EntityManager;
import org.junit.Before;
import org.junit.Test;
diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java
index ca2b7220..0e8edca2 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Common Utils
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 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.
@@ -25,8 +26,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import javax.persistence.EntityManagerFactory;
-
+import jakarta.persistence.EntityManagerFactory;
import org.junit.Before;
import org.junit.Test;
diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java
index d764e9d0..dc63c673 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Common Utils
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -27,8 +28,7 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import javax.persistence.EntityTransaction;
-
+import jakarta.persistence.EntityTransaction;
import org.junit.Before;
import org.junit.Test;
@@ -56,7 +56,7 @@ public class EntityTransCloserTest {
public void testEntityTransCloser() {
EntityTransCloser entityTransCloser = new EntityTransCloser(trans);
- assertEquals(trans, entityTransCloser.getTransation());
+ assertEquals(trans, entityTransCloser.getTransaction());
// verify that transaction was started
verify(trans).begin();
@@ -73,7 +73,7 @@ public class EntityTransCloserTest {
@Test
public void testGetTransation() {
try (EntityTransCloser t = new EntityTransCloser(trans)) {
- assertEquals(trans, t.getTransation());
+ assertEquals(trans, t.getTransaction());
}
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java
new file mode 100644
index 00000000..79db2093
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java
@@ -0,0 +1,53 @@
+/*-
+* ============LICENSE_START=======================================================
+* ONAP Policy
+* ================================================================================
+* Copyright (C) 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.utils.logging;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@RunWith(MockitoJUnitRunner.class)
+public class LoggerUtilsTest {
+ protected static final Logger logger = LoggerFactory.getLogger(LoggerUtilsTest.class);
+
+ @Test
+ public void testMarker() {
+ assertTrue(logger.isInfoEnabled());
+ logger.info("line 1");
+ logger.info(LoggerUtils.METRIC_LOG_MARKER, "line 1 Metric");
+ logger.info(LoggerUtils.AUDIT_LOG_MARKER, "line 1 Audit");
+ logger.info(LoggerUtils.SECURITY_LOG_MARKER, "line 1 Security");
+ logger.info(LoggerUtils.TRANSACTION_LOG_MARKER, "line 1 Transaction");
+ LoggerUtils.setLevel(LoggerUtils.ROOT_LOGGER, "debug");
+ logger.debug("line 2");
+ logger.debug(LoggerUtils.METRIC_LOG_MARKER, "line 2 Metric");
+ logger.debug(LoggerUtils.AUDIT_LOG_MARKER, "line 2 Audit");
+ logger.debug(LoggerUtils.SECURITY_LOG_MARKER, "line 2 Security");
+ logger.info(LoggerUtils.TRANSACTION_LOG_MARKER, "line 2 Transaction");
+ assertTrue(logger.isDebugEnabled());
+ }
+}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java b/utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java
index a0b8353d..4019ca79 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* policy-utils
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,8 +20,10 @@
package org.onap.policy.common.utils.network;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -67,7 +69,7 @@ public class NetworkUtilTest {
public void testAllocPort_testAllocPortString__testAllocPortInetSocketAddress() throws Exception {
// allocate wild-card port
int wildCardPort = NetworkUtil.allocPort();
- assertTrue(wildCardPort != 0);
+ assertNotEquals(0, wildCardPort);
// verify that we can listen on the port
try (ServerSocket wildSocket = new ServerSocket(wildCardPort)) {
@@ -78,10 +80,10 @@ public class NetworkUtilTest {
// allocate port using host name
int localPort = NetworkUtil.allocPort(LOCALHOST);
- assertTrue(localPort != 0);
+ assertNotEquals(0, localPort);
// the OS should have allocated a new port, even though the first has been closed
- assertTrue(localPort != wildCardPort);
+ assertNotEquals(wildCardPort, localPort);
try (ServerSocket localSocket = new ServerSocket()) {
localSocket.bind(new InetSocketAddress(LOCALHOST, localPort));
@@ -90,6 +92,15 @@ public class NetworkUtilTest {
}
}
+ @Test
+ public void testGenUniqueName() {
+ String name = NetworkUtil.genUniqueName(LOCALHOST);
+ assertThat(name).isNotBlank().isNotEqualTo(LOCALHOST);
+
+ // second call should generate a different value
+ assertThat(NetworkUtil.genUniqueName(LOCALHOST)).isNotEqualTo(name);
+ }
+
/**
* Thread that accepts a connection on a socket.
*/
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java
index 07e0795f..7da4eccd 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP - Common Modules
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -80,6 +80,10 @@ public class BeanConfiguratorTest {
@Test
public void testConfigureFromProperties() throws PropertyException {
+ testStringValueNoDefault();
+ }
+
+ private void testStringValueNoDefault() throws PropertyException {
props.setProperty(THE_VALUE, STRING_VALUE);
PlainStringConfig cfg = new PlainStringConfig();
@@ -177,11 +181,7 @@ public class BeanConfiguratorTest {
@Test
public void testSetValueObjectFieldProperties_FieldSet() throws PropertyException {
- props.setProperty(THE_VALUE, STRING_VALUE);
- PlainStringConfig cfg = new PlainStringConfig();
- beancfg.configureFromProperties(cfg, props);
-
- assertEquals(STRING_VALUE, cfg.value);
+ testStringValueNoDefault();
}
@Test
@@ -500,11 +500,7 @@ public class BeanConfiguratorTest {
@Test
public void testGetStringValue() throws PropertyException {
- props.setProperty(THE_VALUE, STRING_VALUE);
- PlainStringConfig cfg = new PlainStringConfig();
- beancfg.configureFromProperties(cfg, props);
-
- assertEquals(STRING_VALUE, cfg.value);
+ testStringValueNoDefault();
}
@Test
@@ -721,12 +717,7 @@ public class BeanConfiguratorTest {
@Test
public void testGetPropValue_Prop_NoDefault() throws PropertyException {
- props.setProperty(THE_VALUE, STRING_VALUE);
-
- PlainStringConfig cfg = new PlainStringConfig();
- beancfg.configureFromProperties(cfg, props);
-
- assertEquals(STRING_VALUE, cfg.value);
+ testStringValueNoDefault();
}
@Test
@@ -960,18 +951,8 @@ public class BeanConfiguratorTest {
@Test(expected = PropertyInvalidException.class)
public void testCheckDefaultValue_Empty_EmptyOk_Invalid() throws PropertyException {
- class Config {
-
- @Property(name = THE_VALUE, defaultValue = "", accept = "empty")
- private long value;
-
- @SuppressWarnings("unused")
- public void setValue(long value) {
- this.value = value;
- }
- }
- beancfg.configureFromProperties(new Config(), props);
+ beancfg.configureFromProperties(new PrimLongDefaultBlankAcceptEmptyConfig(), props);
}
@Test
@@ -1005,18 +986,8 @@ public class BeanConfiguratorTest {
@Test(expected = PropertyMissingException.class)
public void testIsEmptyOkPropertyString_False() throws PropertyException {
- class Config {
-
- @Property(name = THE_VALUE, defaultValue = "", accept = "")
- private long value;
- @SuppressWarnings("unused")
- public void setValue(long value) {
- this.value = value;
- }
- }
-
- beancfg.configureFromProperties(new Config(), props);
+ beancfg.configureFromProperties(new PrimLongDefaultBlankAcceptBlankConfig(), props);
}
@Test
@@ -1040,18 +1011,8 @@ public class BeanConfiguratorTest {
@Test(expected = PropertyMissingException.class)
public void testIsEmptyOkProperty_False() throws PropertyException {
- class Config {
-
- @Property(name = THE_VALUE, defaultValue = "", accept = "")
- private long value;
-
- @SuppressWarnings("unused")
- public void setValue(long value) {
- this.value = value;
- }
- }
- beancfg.configureFromProperties(new Config(), props);
+ beancfg.configureFromProperties(new PrimLongDefaultBlankAcceptBlankConfig(), props);
}
@Test
@@ -1420,6 +1381,26 @@ public class BeanConfiguratorTest {
}
}
+ class PrimLongDefaultBlankAcceptEmptyConfig {
+
+ @Property(name = THE_VALUE, defaultValue = "", accept = "empty")
+ private long value;
+
+ public void setValue(long value) {
+ this.value = value;
+ }
+ }
+
+ class PrimLongDefaultBlankAcceptBlankConfig {
+
+ @Property(name = THE_VALUE, defaultValue = "", accept = "")
+ private long value;
+
+ public void setValue(long value) {
+ this.value = value;
+ }
+ }
+
/**
* This is just used as a mix-in to ensure that the configuration ignores interfaces.
*/
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java
new file mode 100644
index 00000000..93b30643
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java
@@ -0,0 +1,212 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019-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.utils.properties;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.AbstractSet;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import org.junit.Test;
+import org.onap.policy.common.utils.coder.CoderException;
+import org.onap.policy.common.utils.coder.StandardCoder;
+
+public class PropertyObjectUtilsTest {
+
+ @Test
+ public void testToObject() {
+ Map<String, String> map = Map.of("abc", "def", "ghi", "jkl");
+ Properties props = new Properties();
+ props.putAll(map);
+
+ // with empty prefix
+ Map<String, Object> result = PropertyObjectUtils.toObject(props, "");
+ assertEquals(map, result);
+
+ // with dotted prefix - other items skipped
+ map = Map.of("pfx.abc", "def", "ghi", "jkl", "pfx.mno", "pqr", "differentpfx.stu", "vwx");
+ props.clear();
+ props.putAll(Map.of("pfx.abc", "def", "ghi", "jkl", "pfx.mno", "pqr", "differentpfx.stu", "vwx"));
+ result = PropertyObjectUtils.toObject(props, "pfx.");
+ map = Map.of("abc", "def", "mno", "pqr");
+ assertEquals(map, result);
+
+ // undotted prefix - still skips other items
+ result = PropertyObjectUtils.toObject(props, "pfx");
+ assertEquals(map, result);
+ }
+
+ @Test
+ public void testSetProperty() {
+ // one, two, and three components in the name, the last two with subscripts
+ Map<String, Object> map = Map.of("one", "one.abc", "two.def", "two.ghi", "three.jkl.mno[0]", "three.pqr",
+ "three.jkl.mno[1]", "three.stu");
+ Properties props = new Properties();
+ props.putAll(map);
+
+ Map<String, Object> result = PropertyObjectUtils.toObject(props, "");
+ // @formatter:off
+ map = Map.of(
+ "one", "one.abc",
+ "two", Map.of("def", "two.ghi"),
+ "three", Map.of("jkl",
+ Map.of("mno",
+ List.of("three.pqr", "three.stu"))));
+ // @formatter:on
+ assertEquals(map, result);
+ }
+
+ @Test
+ public void testGetNode() {
+ Map<String, Object> map = Map.of("abc[0].def", "node.ghi", "abc[0].jkl", "node.mno", "abc[1].def", "node.pqr");
+ Properties props = new Properties();
+ props.putAll(map);
+
+ Map<String, Object> result = PropertyObjectUtils.toObject(props, "");
+ // @formatter:off
+ map = Map.of(
+ "abc",
+ List.of(
+ Map.of("def", "node.ghi", "jkl", "node.mno"),
+ Map.of("def", "node.pqr")
+ ));
+ // @formatter:on
+ assertEquals(map, result);
+
+ }
+
+ @Test
+ public void testExpand() {
+ // add subscripts out of order
+ Properties props = makeProperties("abc[2]", "expand.def", "abc[1]", "expand.ghi");
+
+ Map<String, Object> result = PropertyObjectUtils.toObject(props, "");
+ // @formatter:off
+ Map<String, Object> map =
+ Map.of("abc",
+ Arrays.asList(null, "expand.ghi", "expand.def"));
+ // @formatter:on
+ assertEquals(map, result);
+
+ }
+
+ @Test
+ public void testGetObject() {
+ // first value is primitive, while second is a map
+ Properties props = makeProperties("object.abc", "object.def", "object.abc.ghi", "object.jkl");
+
+ Map<String, Object> result = PropertyObjectUtils.toObject(props, "");
+ // @formatter:off
+ Map<String, Object> map =
+ Map.of("object",
+ Map.of("abc",
+ Map.of("ghi", "object.jkl")));
+ // @formatter:on
+ assertEquals(map, result);
+ }
+
+ @Test
+ public void testGetArray() {
+ // first value is primitive, while second is an array
+ Properties props = makeProperties("array.abc", "array.def", "array.abc[0].ghi", "array.jkl");
+
+ Map<String, Object> result = PropertyObjectUtils.toObject(props, "");
+ // @formatter:off
+ Map<String, Object> map =
+ Map.of("array",
+ Map.of("abc",
+ List.of(
+ Map.of("ghi", "array.jkl"))));
+ // @formatter:on
+ assertEquals(map, result);
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testCompressLists() throws IOException, CoderException {
+ assertEquals("plain-string", PropertyObjectUtils.compressLists("plain-string").toString());
+
+ // @formatter:off
+ Map<String, Object> map =
+ Map.of(
+ "cmp.abc", "cmp.def",
+ "cmp.ghi",
+ Arrays.asList(null, "cmp.list1", null, "cmp.list2",
+ Map.of("cmp.map", Arrays.asList("cmp.map.list1", "cmp.map1.list2", null))));
+ // @formatter:on
+
+ // the data structure needs to be modifiable, so we'll encode/decode it
+ StandardCoder coder = new StandardCoder();
+ map = coder.decode(coder.encode(map), LinkedHashMap.class);
+
+ PropertyObjectUtils.compressLists(map);
+
+ // @formatter:off
+ Map<String, Object> expected =
+ Map.of(
+ "cmp.abc", "cmp.def",
+ "cmp.ghi",
+ Arrays.asList("cmp.list1", "cmp.list2",
+ Map.of("cmp.map", Arrays.asList("cmp.map.list1", "cmp.map1.list2"))));
+ // @formatter:on
+ assertEquals(expected, map);
+ }
+
+ /**
+ * Makes properties containing the specified key/value pairs. The property set returns
+ * names in the order listed.
+ *
+ * @return a new properties containing the specified key/value pairs
+ */
+ private Properties makeProperties(String key1, String value1, String key2, String value2) {
+ // control the order in which the names are returned
+ List<String> keyList = List.of(key1, key2);
+
+ Set<String> keySet = new AbstractSet<>() {
+ @Override
+ public Iterator<String> iterator() {
+ return keyList.iterator();
+ }
+
+ @Override
+ public int size() {
+ return 2;
+ }
+ };
+
+ Properties props = new Properties() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Set<String> stringPropertyNames() {
+ return keySet;
+ }
+ };
+
+ props.putAll(Map.of(key1, value1, key2, value2));
+
+ return props;
+ }
+}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java
index 190fddd5..ef2051d8 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -28,46 +28,46 @@ import org.junit.Test;
public class PropertyAccessExceptionTest extends SupportBasicPropertyExceptionTester {
/**
- * Test method for
+ * Test method for
* {@link org.onap.policy.common.utils.properties.exception.PropertyAccessException#PropertyAccessException
* (java.lang.String, java.lang.String)}.
*/
@Test
public void testPropertyAccessExceptionStringField() {
- doTestPropertyExceptionStringField_AllPopulated( new PropertyAccessException(PROPERTY, FIELD));
- doTestPropertyExceptionStringField_NullProperty( new PropertyAccessException(null, FIELD));
- doTestPropertyExceptionStringField_NullField( new PropertyAccessException(PROPERTY, null));
- doTestPropertyExceptionStringField_BothNull( new PropertyAccessException(null, null));
+ verifyPropertyExceptionStringField_AllPopulated(new PropertyAccessException(PROPERTY, FIELD));
+ verifyPropertyExceptionStringField_NullProperty(new PropertyAccessException(null, FIELD));
+ verifyPropertyExceptionStringField_NullField(new PropertyAccessException(PROPERTY, null));
+ verifyPropertyExceptionStringField_BothNull(new PropertyAccessException(null, null));
}
/**
- * Test method for
+ * Test method for
* {@link org.onap.policy.common.utils.properties.exception.PropertyAccessException#PropertyAccessException
* (java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
public void testPropertyAccessExceptionStringFieldString() {
- doTestPropertyExceptionStringFieldString(new PropertyAccessException(PROPERTY, FIELD, MESSAGE));
+ verifyPropertyExceptionStringFieldString(new PropertyAccessException(PROPERTY, FIELD, MESSAGE));
}
/**
- * Test method for
+ * Test method for
* {@link org.onap.policy.common.utils.properties.exception.PropertyAccessException#PropertyAccessException
* (java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
public void testPropertyAccessExceptionStringFieldThrowable() {
- doTestPropertyExceptionStringFieldThrowable(new PropertyAccessException(PROPERTY, FIELD, THROWABLE));
+ verifyPropertyExceptionStringFieldThrowable(new PropertyAccessException(PROPERTY, FIELD, THROWABLE));
}
/**
- * Test method for
+ * Test method for
* {@link org.onap.policy.common.utils.properties.exception.PropertyAccessException#PropertyAccessException
* (java.lang.String, java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
public void testPropertyAccessExceptionStringFieldStringThrowable() {
- doTestPropertyExceptionStringFieldStringThrowable(
+ verifyPropertyExceptionStringFieldStringThrowable(
new PropertyAccessException(PROPERTY, FIELD, MESSAGE, THROWABLE));
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java
index c4803912..91879763 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -34,10 +34,10 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti
*/
@Test
public void testPropertyExceptionStringField() {
- doTestPropertyExceptionStringField_AllPopulated(new PropertyAnnotationException(PROPERTY, FIELD));
- doTestPropertyExceptionStringField_NullProperty(new PropertyAnnotationException(null, FIELD));
- doTestPropertyExceptionStringField_NullField(new PropertyAnnotationException(PROPERTY, null));
- doTestPropertyExceptionStringField_BothNull(new PropertyAnnotationException(null, null));
+ verifyPropertyExceptionStringField_AllPopulated(new PropertyAnnotationException(PROPERTY, FIELD));
+ verifyPropertyExceptionStringField_NullProperty(new PropertyAnnotationException(null, FIELD));
+ verifyPropertyExceptionStringField_NullField(new PropertyAnnotationException(PROPERTY, null));
+ verifyPropertyExceptionStringField_BothNull(new PropertyAnnotationException(null, null));
}
/**
@@ -47,7 +47,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti
*/
@Test
public void testPropertyExceptionStringFieldString() {
- doTestPropertyExceptionStringFieldString(new PropertyAnnotationException(PROPERTY, FIELD, MESSAGE));
+ verifyPropertyExceptionStringFieldString(new PropertyAnnotationException(PROPERTY, FIELD, MESSAGE));
}
/**
@@ -57,7 +57,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti
*/
@Test
public void testPropertyExceptionStringFieldThrowable() {
- doTestPropertyExceptionStringFieldThrowable(new PropertyAnnotationException(PROPERTY, FIELD, THROWABLE));
+ verifyPropertyExceptionStringFieldThrowable(new PropertyAnnotationException(PROPERTY, FIELD, THROWABLE));
}
/**
@@ -67,7 +67,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti
*/
@Test
public void testPropertyExceptionStringFieldStringThrowable() {
- doTestPropertyExceptionStringFieldStringThrowable(
+ verifyPropertyExceptionStringFieldStringThrowable(
new PropertyAnnotationException(PROPERTY, FIELD, MESSAGE, THROWABLE));
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java
index 9055aeb7..9166749b 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -34,10 +34,10 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
*/
@Test
public void testPropertyExceptionStringField() {
- doTestPropertyExceptionStringField_AllPopulated(new PropertyException(PROPERTY, FIELD));
- doTestPropertyExceptionStringField_NullProperty(new PropertyException(null, FIELD));
- doTestPropertyExceptionStringField_NullField(new PropertyException(PROPERTY, null));
- doTestPropertyExceptionStringField_BothNull(new PropertyException(null, null));
+ verifyPropertyExceptionStringField_AllPopulated(new PropertyException(PROPERTY, FIELD));
+ verifyPropertyExceptionStringField_NullProperty(new PropertyException(null, FIELD));
+ verifyPropertyExceptionStringField_NullField(new PropertyException(PROPERTY, null));
+ verifyPropertyExceptionStringField_BothNull(new PropertyException(null, null));
}
/**
@@ -47,7 +47,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
*/
@Test
public void testPropertyExceptionStringFieldString() {
- doTestPropertyExceptionStringFieldString(new PropertyException(PROPERTY, FIELD, MESSAGE));
+ verifyPropertyExceptionStringFieldString(new PropertyException(PROPERTY, FIELD, MESSAGE));
}
/**
@@ -57,7 +57,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
*/
@Test
public void testPropertyExceptionStringFieldThrowable() {
- doTestPropertyExceptionStringFieldThrowable(new PropertyException(PROPERTY, FIELD, THROWABLE));
+ verifyPropertyExceptionStringFieldThrowable(new PropertyException(PROPERTY, FIELD, THROWABLE));
}
/**
@@ -67,7 +67,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
*/
@Test
public void testPropertyExceptionStringFieldStringThrowable() {
- doTestPropertyExceptionStringFieldStringThrowable(new PropertyException(PROPERTY, FIELD, MESSAGE, THROWABLE));
+ verifyPropertyExceptionStringFieldStringThrowable(new PropertyException(PROPERTY, FIELD, MESSAGE, THROWABLE));
}
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java
index 69ab1bd3..3edd7ff4 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -34,10 +34,10 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT
*/
@Test
public void testPropertyExceptionStringField() {
- doTestPropertyExceptionStringField_AllPopulated(new PropertyInvalidException(PROPERTY, FIELD));
- doTestPropertyExceptionStringField_NullProperty(new PropertyInvalidException(null, FIELD));
- doTestPropertyExceptionStringField_NullField(new PropertyInvalidException(PROPERTY, null));
- doTestPropertyExceptionStringField_BothNull(new PropertyInvalidException(null, null));
+ verifyPropertyExceptionStringField_AllPopulated(new PropertyInvalidException(PROPERTY, FIELD));
+ verifyPropertyExceptionStringField_NullProperty(new PropertyInvalidException(null, FIELD));
+ verifyPropertyExceptionStringField_NullField(new PropertyInvalidException(PROPERTY, null));
+ verifyPropertyExceptionStringField_BothNull(new PropertyInvalidException(null, null));
}
/**
@@ -47,7 +47,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT
*/
@Test
public void testPropertyExceptionStringFieldString() {
- doTestPropertyExceptionStringFieldString(new PropertyInvalidException(PROPERTY, FIELD, MESSAGE));
+ verifyPropertyExceptionStringFieldString(new PropertyInvalidException(PROPERTY, FIELD, MESSAGE));
}
/**
@@ -57,7 +57,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT
*/
@Test
public void testPropertyExceptionStringFieldThrowable() {
- doTestPropertyExceptionStringFieldThrowable(new PropertyInvalidException(PROPERTY, FIELD, THROWABLE));
+ verifyPropertyExceptionStringFieldThrowable(new PropertyInvalidException(PROPERTY, FIELD, THROWABLE));
}
/**
@@ -67,7 +67,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT
*/
@Test
public void testPropertyExceptionStringFieldStringThrowable() {
- doTestPropertyExceptionStringFieldStringThrowable(
+ verifyPropertyExceptionStringFieldStringThrowable(
new PropertyInvalidException(PROPERTY, FIELD, MESSAGE, THROWABLE));
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java
index 81a7c36a..948bc18e 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -34,10 +34,10 @@ public class PropertyMissingExceptionTest extends SupportBasicPropertyExceptionT
*/
@Test
public void testPropertyExceptionStringField() {
- doTestPropertyExceptionStringField_AllPopulated(new PropertyMissingException(PROPERTY, FIELD));
- doTestPropertyExceptionStringField_NullProperty(new PropertyMissingException(null, FIELD));
- doTestPropertyExceptionStringField_NullField(new PropertyMissingException(PROPERTY, null));
- doTestPropertyExceptionStringField_BothNull(new PropertyMissingException(null, null));
+ verifyPropertyExceptionStringField_AllPopulated(new PropertyMissingException(PROPERTY, FIELD));
+ verifyPropertyExceptionStringField_NullProperty(new PropertyMissingException(null, FIELD));
+ verifyPropertyExceptionStringField_NullField(new PropertyMissingException(PROPERTY, null));
+ verifyPropertyExceptionStringField_BothNull(new PropertyMissingException(null, null));
}
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java
index 97503f8c..be3f8183 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 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.
@@ -20,11 +20,9 @@
package org.onap.policy.common.utils.properties.exception;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-import org.hamcrest.CoreMatchers;
/**
* Superclass used to test subclasses of {@link PropertyException}.
@@ -52,45 +50,45 @@ public class SupportBasicPropertyExceptionTester {
protected static final String FIELD = "PROPERTY";
/*
- * Methods to perform various tests on the except subclass.
+ * Methods to perform various tests on the except subclass.
*/
- protected void doTestPropertyExceptionStringField_AllPopulated(PropertyException ex) {
+ protected void verifyPropertyExceptionStringField_AllPopulated(PropertyException ex) {
standardTests(ex);
}
- protected void doTestPropertyExceptionStringField_NullProperty(PropertyException ex) {
+ protected void verifyPropertyExceptionStringField_NullProperty(PropertyException ex) {
assertEquals(null, ex.getPropertyName());
assertEquals(FIELD, ex.getFieldName());
assertNotNull(ex.getMessage());
assertNotNull(ex.toString());
}
- protected void doTestPropertyExceptionStringField_NullField(PropertyException ex) {
+ protected void verifyPropertyExceptionStringField_NullField(PropertyException ex) {
assertEquals(PROPERTY, ex.getPropertyName());
assertEquals(null, ex.getFieldName());
assertNotNull(ex.getMessage());
assertNotNull(ex.toString());
}
- protected void doTestPropertyExceptionStringField_BothNull(PropertyException ex) {
+ protected void verifyPropertyExceptionStringField_BothNull(PropertyException ex) {
assertEquals(null, ex.getPropertyName());
assertEquals(null, ex.getFieldName());
assertNotNull(ex.getMessage());
assertNotNull(ex.toString());
}
- protected void doTestPropertyExceptionStringFieldString(PropertyException ex) {
+ protected void verifyPropertyExceptionStringFieldString(PropertyException ex) {
standardTests(ex);
standardMessageTests(ex);
}
- protected void doTestPropertyExceptionStringFieldThrowable(PropertyException ex) {
+ protected void verifyPropertyExceptionStringFieldThrowable(PropertyException ex) {
standardTests(ex);
standardThrowableTests(ex);
}
- protected void doTestPropertyExceptionStringFieldStringThrowable(PropertyException ex) {
+ protected void verifyPropertyExceptionStringFieldStringThrowable(PropertyException ex) {
standardTests(ex);
standardMessageTests(ex);
standardThrowableTests(ex);
@@ -98,7 +96,7 @@ public class SupportBasicPropertyExceptionTester {
/**
* Performs standard tests that should apply to all subclasses.
- *
+ *
* @param ex exception to test
*/
protected void standardTests(PropertyException ex) {
@@ -111,17 +109,17 @@ public class SupportBasicPropertyExceptionTester {
/**
* Performs standard tests for exceptions that were provided a message in their
* constructor.
- *
+ *
* @param ex exception to test
*/
protected void standardMessageTests(PropertyException ex) {
- assertThat(ex.getMessage(), CoreMatchers.endsWith(MESSAGE));
+ assertThat(ex.getMessage()).endsWith(MESSAGE);
}
/**
* Performs standard tests for exceptions that were provided a throwable in their
* constructor.
- *
+ *
* @param ex exception to test
*/
protected void standardThrowableTests(PropertyException ex) {
diff --git a/utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java
new file mode 100644
index 00000000..c12ef9f8
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java
@@ -0,0 +1,42 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 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.utils.resources;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import org.apache.commons.io.FileUtils;
+import org.junit.Test;
+
+public class DirectoryUtilsTest {
+
+ @Test
+ public void testCreateTempDirectory() throws IOException {
+ Path path = DirectoryUtils.createTempDirectory("directoryUtilsTest");
+
+ var file = path.toFile();
+ FileUtils.forceDeleteOnExit(file);
+
+ assertThat(file).canRead().canWrite().isDirectory();
+ assertThat(file.canExecute()).isTrue();
+ }
+}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java
index 2991009f..a39b4fc2 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java
@@ -1,8 +1,8 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020-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.
@@ -30,11 +30,9 @@ import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
-import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -79,12 +77,12 @@ public class ResourceUtilsTest {
}
/**
- * Cleandown resource utils test.
+ * Clean resource utils test.
*/
@After
- public void cleandownResourceUtilsTest() {
- tmpEmptyFile.delete();
- tmpUsedFile.delete();
+ public void cleanDownResourceUtilsTest() {
+ assertTrue(tmpEmptyFile.delete());
+ assertTrue(tmpUsedFile.delete());
}
/**
@@ -184,45 +182,26 @@ public class ResourceUtilsTest {
* Test get resource as stream.
*/
@Test
- public void testGetResourceAsStream() {
- InputStream theStream = ResourceUtils.getResourceAsStream(tmpDir.getAbsolutePath());
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(tmpEmptyFile.getAbsolutePath());
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(tmpUsedFile.getAbsolutePath());
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(jarDirResource);
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(jarFileResource);
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(PATH_DIR_RESOURCE);
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(PATH_FILE_RESOURCE);
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(RESOURCES_PATH + PATH_DIR_RESOURCE);
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(RESOURCES_PATH + PATH_FILE_RESOURCE);
- assertNotNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(NON_EXISTENT_RESOURCE);
- assertNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(INVALID_RESOURCE);
- assertNull(theStream);
-
- theStream = ResourceUtils.getResourceAsStream(null);
- assertNull(theStream);
+ public void testGetResourceAsStream() throws IOException {
+ verifyStream(tmpDir.getAbsolutePath());
+ verifyStream(tmpEmptyFile.getAbsolutePath());
+ verifyStream(tmpUsedFile.getAbsolutePath());
+ verifyStream(jarDirResource);
+ verifyStream(jarFileResource);
+ verifyStream(PATH_DIR_RESOURCE);
+ verifyStream(PATH_FILE_RESOURCE);
+ verifyStream(RESOURCES_PATH + PATH_DIR_RESOURCE);
+ verifyStream(RESOURCES_PATH + PATH_FILE_RESOURCE);
+ assertNull(ResourceUtils.getResourceAsStream(NON_EXISTENT_RESOURCE));
+ assertNull(ResourceUtils.getResourceAsStream(INVALID_RESOURCE));
+ assertNull(ResourceUtils.getResourceAsStream(null));
+ verifyStream("");
+ }
- theStream = ResourceUtils.getResourceAsStream("");
- assertNotNull(theStream);
+ private void verifyStream(String path) throws IOException {
+ try (var theStream = ResourceUtils.getResourceAsStream(path)) {
+ assertNotNull(theStream);
+ }
}
/**
@@ -234,10 +213,10 @@ public class ResourceUtilsTest {
assertNotNull(theString);
theString = ResourceUtils.getResourceAsString(tmpEmptyFile.getAbsolutePath());
- assertTrue(theString.equals(""));
+ assertEquals("", theString);
theString = ResourceUtils.getResourceAsString(tmpUsedFile.getAbsolutePath());
- assertTrue(theString.equals("Bluebirds fly over the rainbow"));
+ assertEquals("Bluebirds fly over the rainbow", theString);
theString = ResourceUtils.getResourceAsString(jarFileResource);
assertNotNull(theString);
@@ -265,7 +244,7 @@ public class ResourceUtilsTest {
theString = ResourceUtils.getResourceAsString("");
- assertEquals("logback-test.xml\nMETA-INF\norg\ntestdir\n", theString);
+ assertEquals("cmdFiles\nlogback-test.xml\nMETA-INF\norg\ntestdir\nversion.txt\n", theString);
}
@@ -310,7 +289,7 @@ public class ResourceUtilsTest {
assertNull(ResourceUtils.getFilePath4Resource(null));
assertEquals("/something/else", ResourceUtils.getFilePath4Resource("/something/else"));
assertTrue(ResourceUtils.getFilePath4Resource("xml/example.xml").endsWith("xml/example.xml"));
- assertTrue(ResourceUtils.getFilePath4Resource("com/google").endsWith("com/google"));
+ assertTrue(ResourceUtils.getFilePath4Resource("com/google").contains("com/google"));
}
@Test
@@ -321,26 +300,37 @@ public class ResourceUtilsTest {
Set<String> resultD0 = ResourceUtils.getDirectoryContents("testdir");
assertEquals(1, resultD0.size());
- assertEquals("testdir/testfile.xml", resultD0.iterator().next());
+ assertEquals("testdir/testfile.xml", normalizePath(resultD0.iterator().next()));
Set<String> resultD1 = ResourceUtils.getDirectoryContents("org/onap/policy/common");
assertTrue(resultD1.size() > 0);
- assertEquals("org/onap/policy/common/utils/", resultD1.iterator().next());
+ assertEquals("org/onap/policy/common/utils/", normalizePath(resultD1.iterator().next()));
Set<String> resultD2 = ResourceUtils.getDirectoryContents("org/onap/policy/common/utils/coder");
assertTrue(resultD2.size() >= 15);
- assertEquals("org/onap/policy/common/utils/coder/CoderExceptionTest.class", resultD2.iterator().next());
+ assertEquals("org/onap/policy/common/utils/coder/CoderExceptionTest.class",
+ normalizePath(resultD2.iterator().next()));
Set<String> resultJ0 = ResourceUtils.getDirectoryContents("com");
- assertEquals(189, resultJ0.size());
- assertEquals("com/google/", resultJ0.iterator().next());
+ assertTrue(resultJ0.contains("com/worldturner/medeia/"));
+ assertEquals("com/worldturner/", normalizePath(resultJ0.iterator().next()));
- Set<String> resultJ1 = ResourceUtils.getDirectoryContents("com/google/gson/util");
- assertEquals(1, resultJ1.size());
- assertEquals("com/google/gson/util/VersionUtils.class", resultJ1.iterator().next());
+ Set<String> resultJ1 = ResourceUtils.getDirectoryContents("com/google/gson");
+ assertTrue(resultJ1.size() > 1);
+ assertTrue(resultJ1.contains("com/google/gson/JsonElement.class"));
URL dummyUrl = new URL("http://even/worse");
assertTrue(ResourceUtils.getDirectoryContentsJar(dummyUrl, "nonexistantdirectory").isEmpty());
}
+
+ /**
+ * Normalizes a path name, replacing OS-specific separators with "/".
+ *
+ * @param pathName path name to be normalized
+ * @return the normalized path name
+ */
+ private String normalizePath(String pathName) {
+ return pathName.replace(File.separator, "/");
+ }
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java
index 0952b168..91268979 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 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.
@@ -20,12 +21,13 @@
package org.onap.policy.common.utils.resources;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
-
+import org.apache.commons.io.FileUtils;
import org.junit.Test;
/**
@@ -39,35 +41,80 @@ public class TextFileUtilsTest {
@Test
public void testPutToFile() throws IOException {
- final File tempTextFile = File.createTempFile("Test", "txt");
+ final File tempTextFile = File.createTempFile("Test", ".txt");
+ tempTextFile.deleteOnExit();
TextFileUtils.putStringAsTextFile(FILE_CONTENT, tempTextFile.getAbsolutePath());
final String textFileString0 = TextFileUtils.getTextFileAsString(tempTextFile.getAbsolutePath());
assertEquals(FILE_CONTENT, textFileString0);
- final FileInputStream fis = new FileInputStream(tempTextFile);
- final String textFileString1 = TextFileUtils.getStreamAsString(fis);
- assertEquals(textFileString0, textFileString1);
+ try (final FileInputStream fis = new FileInputStream(tempTextFile)) {
+ final String textFileString1 = TextFileUtils.getStreamAsString(fis);
+ assertEquals(textFileString0, textFileString1);
+ }
}
@Test
public void testPutToFileWithNewPath() throws IOException {
String tempDirAndFileName = System.getProperty("java.io.tmpdir") + "/non/existant/path/Test.txt";
+ FileUtils.forceDeleteOnExit(new File(tempDirAndFileName));
TextFileUtils.putStringAsTextFile(FILE_CONTENT, tempDirAndFileName);
final String textFileString0 = TextFileUtils.getTextFileAsString(tempDirAndFileName);
assertEquals(FILE_CONTENT, textFileString0);
- final FileInputStream fis = new FileInputStream(tempDirAndFileName);
- final String textFileString1 = TextFileUtils.getStreamAsString(fis);
- assertEquals(textFileString0, textFileString1);
+ try (final FileInputStream fis = new FileInputStream(tempDirAndFileName)) {
+ final String textFileString1 = TextFileUtils.getStreamAsString(fis);
+ assertEquals(textFileString0, textFileString1);
+ }
+ }
+
+ @Test
+ public void testCreateTempFile() throws IOException {
+ var file = TextFileUtils.createTempFile("textFileUtilsTest", ".txt");
+ file.deleteOnExit();
+
+ verifyDefaultPermissions(file);
+ }
+
+ @Test
+ public void testSetDefaultPermissions() throws IOException {
+ var file = new File("target/tempfile.txt");
+ file.deleteOnExit();
+
+ // ensure it doesn't exist before we create it
+ file.delete();
+ assertThat(file.createNewFile()).isTrue();
+
+ // check using whatever permissions it comes with
+
+ TextFileUtils.setDefaultPermissions(file);
+
+ verifyDefaultPermissions(file);
+
+ // prevent read-write-execute by anyone
+ file.setReadable(false);
+ file.setWritable(false);
+ file.setExecutable(false);
+
+ TextFileUtils.setDefaultPermissions(file);
+
+ verifyDefaultPermissions(file);
+
+ // make it read-write-execute by everyone
+ file.setReadable(true);
+ file.setWritable(true);
+ file.setExecutable(true);
+
+ TextFileUtils.setDefaultPermissions(file);
+
+ verifyDefaultPermissions(file);
+ }
- File tempDirAndFile = new File(tempDirAndFileName);
- tempDirAndFile.delete();
- tempDirAndFile.getParentFile().delete();
- tempDirAndFile.getParentFile().getParentFile().delete();
- tempDirAndFile.getParentFile().getParentFile().getParentFile().delete();
+ private void verifyDefaultPermissions(File file) {
+ assertThat(file).canRead().canWrite();
+ assertThat(file.canExecute()).isTrue();
}
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java
index ce9435d8..625fd1f5 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-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.
@@ -37,7 +37,7 @@ public class CryptoUtilsTest {
private static Logger logger = LoggerFactory.getLogger(CryptoUtilsTest.class);
private static final String PASS = "HelloWorld";
private static final String SECRET_KEY = "MTIzNDU2Nzg5MDEyMzQ1Ng==";
- private static final String ENCRYPTED_PASS = "enc:hcI2XVX+cxPz/6rlbebkWpCFF6WPbBtT7iJRr2VHUkA=";
+ private static final String ENCRYPTED_PASS = "enc:Z6QzirpPyDpwmIcNbE3U2iq6g/ubJBEdzssoigxGGChlQtdWOLD8y00O";
private static final String DECRYPTED_MSG = "encrypted value: {} decrypted value : {}";
private static final String ENCRYPTED_MSG = "original value : {} encrypted value: {}";
@@ -120,4 +120,4 @@ public class CryptoUtilsTest {
String decryptedAgain = CryptoUtils.decrypt(decryptedValue, SECRET_KEY);
assertEquals(decryptedValue, decryptedAgain);
}
-} \ No newline at end of file
+}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java
index 232d3409..d111962e 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java
@@ -61,7 +61,7 @@ public class FeatureApiUtilsTest {
public void testApplyFeatureFalse() {
List<String> lst = Arrays.asList("falseF1", "exceptF2", "falseF3");
- assertFalse(FeatureApiUtils.apply(lst, pred, (str,ex) -> errors.add(str)));
+ assertFalse(FeatureApiUtils.apply(lst, pred, (str, ex) -> errors.add(str)));
assertEquals(lst.toString(), tried.toString());
assertEquals("[exceptF2]", errors.toString());
}
diff --git a/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java b/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java
index 1a45f9e1..4673233e 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP PAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,7 +22,7 @@
package org.onap.policy.common.utils.validation;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -48,7 +48,7 @@ public class VersionTest {
public void testHashCode() {
int hash = vers.hashCode();
int hash2 = new Version(MAJOR, MINOR, PATCH + 1).hashCode();
- assertTrue(hash != hash2);
+ assertNotEquals(hash, hash2);
}
@Test
@@ -72,16 +72,16 @@ public class VersionTest {
@Test
public void testEquals() {
- assertFalse(vers.equals(null));
- assertFalse(vers.equals(new Object()));
+ assertNotEquals(vers, null);
+ assertNotEquals(vers, new Object());
- assertTrue(vers.equals(vers));
+ assertEquals(vers, vers);
- assertTrue(vers.equals(new Version(MAJOR, MINOR, PATCH)));
+ assertEquals(vers, new Version(MAJOR, MINOR, PATCH));
- assertFalse(vers.equals(new Version(MAJOR + 1, MINOR, PATCH)));
- assertFalse(vers.equals(new Version(MAJOR, MINOR + 1, PATCH)));
- assertFalse(vers.equals(new Version(MAJOR, MINOR, PATCH + 1)));
+ assertNotEquals(vers, new Version(MAJOR + 1, MINOR, PATCH));
+ assertNotEquals(vers, new Version(MAJOR, MINOR + 1, PATCH));
+ assertNotEquals(vers, new Version(MAJOR, MINOR, PATCH + 1));
}
@Test
@@ -89,7 +89,7 @@ public class VersionTest {
vers = new Version(101, 201, 301);
// equals case
- assertTrue(new Version(101, 201, 301).compareTo(vers) == 0);
+ assertEquals(0, new Version(101, 201, 301).compareTo(vers));
// major takes precedence
assertTrue(new Version(102, 200, 300).compareTo(vers) > 0);
@@ -139,4 +139,4 @@ public class VersionTest {
public void testVersion() {
assertEquals("0.0.0", new Version().toString());
}
-} \ No newline at end of file
+}
diff --git a/utils/src/test/resources/cmdFiles/configuration.json b/utils/src/test/resources/cmdFiles/configuration.json
new file mode 100644
index 00000000..64cd100c
--- /dev/null
+++ b/utils/src/test/resources/cmdFiles/configuration.json
@@ -0,0 +1,4 @@
+{
+ "propertyName" : "test",
+ "propertyType" : "string"
+}
diff --git a/utils/src/test/resources/cmdFiles/property.json b/utils/src/test/resources/cmdFiles/property.json
new file mode 100644
index 00000000..be63ece4
--- /dev/null
+++ b/utils/src/test/resources/cmdFiles/property.json
@@ -0,0 +1,3 @@
+{
+ "configName" : "test"
+}
diff --git a/utils/src/test/resources/org/onap/policy/common/utils/coder/bad-regex.json b/utils/src/test/resources/org/onap/policy/common/utils/coder/bad-regex.json
new file mode 100644
index 00000000..049de2cf
--- /dev/null
+++ b/utils/src/test/resources/org/onap/policy/common/utils/coder/bad-regex.json
@@ -0,0 +1,9 @@
+{
+ "aaString": "abc123",
+ "anInteger": 90,
+ "aaBoolean": true,
+ "aaCollection": [ {
+ "subItemString": "defg",
+ "subItemInteger": 1200
+ }]
+} \ No newline at end of file
diff --git a/utils/src/test/resources/org/onap/policy/common/utils/coder/missing-required.json b/utils/src/test/resources/org/onap/policy/common/utils/coder/missing-required.json
new file mode 100644
index 00000000..e19db9db
--- /dev/null
+++ b/utils/src/test/resources/org/onap/policy/common/utils/coder/missing-required.json
@@ -0,0 +1,5 @@
+{
+ "aaString": "abcd",
+ "anInteger": 90,
+ "aaBoolean": true
+} \ No newline at end of file
diff --git a/utils/src/test/resources/org/onap/policy/common/utils/coder/test.schema.json b/utils/src/test/resources/org/onap/policy/common/utils/coder/test.schema.json
new file mode 100644
index 00000000..e79475eb
--- /dev/null
+++ b/utils/src/test/resources/org/onap/policy/common/utils/coder/test.schema.json
@@ -0,0 +1,71 @@
+{
+ "definitions": {},
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "http://onap.org/policy/common/coders/root.json",
+ "type": "object",
+ "title": "Test Schema",
+ "required": [
+ "aaString",
+ "anInteger",
+ "aaBoolean",
+ "aaCollection"
+ ],
+ "properties": {
+ "aaString": {
+ "$id": "#/properties/aaString",
+ "type": "string",
+ "title": "an alphabetical string",
+ "default": "",
+ "examples": [
+ "abcdef"
+ ],
+ "pattern": "^([a-z]*)$"
+ },
+ "anInteger": {
+ "$id": "#/properties/anInteger",
+ "type": "integer",
+ "title": "a bounded integer",
+ "default": 5,
+ "examples": [
+ 98
+ ],
+ "minimum": 10,
+ "maximum": 100
+ },
+ "aaBoolean": {
+ "$id": "#/properties/aaBoolean",
+ "type": "boolean",
+ "title": "a boolean",
+ "default": false,
+ "examples": [
+ true
+ ]
+ },
+ "aaCollection": {
+ "$id": "#/properties/aaCollection",
+ "type": "array",
+ "title": "a collection",
+ "items": {
+ "$id": "#/properties/aaCollection/items",
+ "type": "object",
+ "title": "the collection items",
+ "required": [
+ "subItemString"
+ ],
+ "properties": {
+ "subItemString": {
+ "$id": "#/properties/aaCollection/items/properties/subItemString",
+ "type": "string",
+ "title": "the subitem string",
+ "default": "blah",
+ "pattern": "^(.*)$"
+ },
+ "subItemInteger": {
+ "$id": "#/properties/aaCollection/items/properties/subItemInteger",
+ "type": "integer"
+ }
+ }
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/utils/src/test/resources/org/onap/policy/common/utils/coder/valid.json b/utils/src/test/resources/org/onap/policy/common/utils/coder/valid.json
new file mode 100644
index 00000000..c1738176
--- /dev/null
+++ b/utils/src/test/resources/org/onap/policy/common/utils/coder/valid.json
@@ -0,0 +1,9 @@
+{
+ "aaString": "abcd",
+ "anInteger": 90,
+ "aaBoolean": true,
+ "aaCollection": [ {
+ "subItemString": "defg",
+ "subItemInteger": 1200
+ }]
+} \ No newline at end of file
diff --git a/utils/src/test/resources/version.txt b/utils/src/test/resources/version.txt
new file mode 100644
index 00000000..9970c7b4
--- /dev/null
+++ b/utils/src/test/resources/version.txt
@@ -0,0 +1 @@
+ONAP Version test.
diff --git a/version.properties b/version.properties
index 41565bf0..50539a03 100644
--- a/version.properties
+++ b/version.properties
@@ -2,8 +2,8 @@
# Note that these variables cannot be structured (e.g. : version.release or version.snapshot etc... )
# because they are used in Jenkins, whose plug-in doesn't support
-major=1
-minor=6
+major=2
+minor=1
patch=2
base_version=${major}.${minor}.${patch}