From f2f7df9c9d4b3d605ed2fbe7e6fd78e3764adf66 Mon Sep 17 00:00:00 2001 From: Jeff Zemerick <13176962+jzonthemtn@users.noreply.github.com> Date: Wed, 3 Apr 2024 11:39:58 -0400 Subject: [PATCH] Removing OWNER dependency for managing application properties (#54) * PHL-313: Removing OWNER project for property management. --------- Co-authored-by: jzonthemtn --- .github/workflows/build.yml | 2 +- owner/README.md | 26 - owner/pom.xml | 47 -- .../java/org/aeonbits/owner/Accessible.java | 156 ----- .../main/java/org/aeonbits/owner/Config.java | 370 ---------- .../java/org/aeonbits/owner/ConfigCache.java | 160 ----- .../org/aeonbits/owner/ConfigFactory.java | 164 ----- .../org/aeonbits/owner/ConfigURIFactory.java | 65 -- .../java/org/aeonbits/owner/Converter.java | 35 - .../java/org/aeonbits/owner/Converters.java | 332 --------- .../org/aeonbits/owner/DefaultFactory.java | 110 --- .../java/org/aeonbits/owner/Delegate.java | 20 - .../aeonbits/owner/DelegateMethodHandle.java | 41 -- .../main/java/org/aeonbits/owner/Factory.java | 107 --- .../org/aeonbits/owner/HotReloadLogic.java | 129 ---- .../java/org/aeonbits/owner/JMXSupport.java | 109 --- .../org/aeonbits/owner/LoadersManager.java | 96 --- .../main/java/org/aeonbits/owner/Mutable.java | 118 ---- .../java/org/aeonbits/owner/Preprocessor.java | 20 - .../aeonbits/owner/PreprocessorResolver.java | 52 -- .../owner/PropertiesInvocationHandler.java | 163 ----- .../org/aeonbits/owner/PropertiesManager.java | 634 ------------------ .../org/aeonbits/owner/PropertiesMapper.java | 52 -- .../java/org/aeonbits/owner/Reloadable.java | 70 -- .../aeonbits/owner/SplitAndTrimTokenizer.java | 33 - .../org/aeonbits/owner/StrSubstitutor.java | 101 --- .../java/org/aeonbits/owner/Tokenizer.java | 29 - .../org/aeonbits/owner/TokenizerResolver.java | 77 --- .../org/aeonbits/owner/VariablesExpander.java | 43 -- .../owner/crypto/AbstractDecryptor.java | 17 - .../owner/crypto/AbstractEncryptor.java | 9 - .../org/aeonbits/owner/crypto/Decryptor.java | 27 - .../org/aeonbits/owner/crypto/Encryptor.java | 17 - .../owner/crypto/IdentityDecryptor.java | 13 - .../java/org/aeonbits/owner/event/Event.java | 31 - .../org/aeonbits/owner/event/ReloadEvent.java | 77 --- .../aeonbits/owner/event/ReloadListener.java | 33 - .../owner/event/RollbackBatchException.java | 37 - .../owner/event/RollbackException.java | 34 - .../event/RollbackOperationException.java | 35 - .../TransactionalPropertyChangeListener.java | 33 - .../event/TransactionalReloadListener.java | 28 - .../owner/event/UnmodifiableProperties.java | 64 -- .../aeonbits/owner/event/package-info.java | 17 - .../org/aeonbits/owner/loaders/Loader.java | 50 -- .../owner/loaders/PhileasSystemLoader.java | 61 -- .../owner/loaders/PropertiesLoader.java | 57 -- .../aeonbits/owner/loaders/SystemLoader.java | 56 -- .../org/aeonbits/owner/loaders/XMLLoader.java | 158 ----- .../aeonbits/owner/loaders/package-info.java | 12 - .../java/org/aeonbits/owner/package-info.java | 51 -- .../java/org/aeonbits/owner/util/Base64.java | 83 --- .../org/aeonbits/owner/util/Collections.java | 99 --- .../org/aeonbits/owner/util/Reflection.java | 70 -- .../java/org/aeonbits/owner/util/Util.java | 292 -------- .../org/aeonbits/owner/util/package-info.java | 12 - .../org/aeonbits/owner/ConfigFactoryTest.java | 166 ----- .../aeonbits/owner/ConfigInheritanceTest.java | 50 -- .../java/org/aeonbits/owner/ConfigTest.java | 144 ---- .../aeonbits/owner/ConfigURIFactoryTest.java | 36 - .../owner/ConfigWithSubstitutionTest.java | 71 -- .../aeonbits/owner/DisableFeatureTest.java | 130 ---- .../aeonbits/owner/EqualsAndHashCodeTest.java | 110 --- .../org/aeonbits/owner/LoaderManagerTest.java | 143 ---- .../aeonbits/owner/LoadersManagerForTest.java | 23 - .../org/aeonbits/owner/PreprocessorTest.java | 96 --- .../PropertiesInvocationHandlerTest.java | 66 -- .../owner/PropertiesManagerForTest.java | 41 -- .../aeonbits/owner/StrSubstitutorTest.java | 108 --- .../owner/SystemVariableExpanderTest.java | 71 -- .../org/aeonbits/owner/TestConstants.java | 16 - .../owner/UndefinedPropertiesTest.java | 44 -- .../owner/VariablesExpanderForTest.java | 25 - .../aeonbits/owner/cache/CacheConfigTest.java | 143 ---- .../owner/crypto/CryptoConfigTest.java | 127 ---- .../aeonbits/owner/crypto/CryptoUtils.java | 22 - .../owner/crypto/SampleDecryptor.java | 36 - .../owner/crypto/StandardEncryptor.java | 70 -- .../owner/debugging/ToStringTest.java | 47 -- .../event/EventListenerOnReloadTest.java | 435 ------------ .../owner/event/EventListenerTest.java | 474 ------------- .../aeonbits/owner/event/ExceptionTests.java | 36 - .../owner/event/PropertyChangeMatcher.java | 37 - .../event/UnmodifiablePropertiesTest.java | 81 --- .../examples/EncryptedPropertiesExample.java | 62 -- .../aeonbits/owner/examples/JMXExample.java | 74 -- .../owner/examples/MapPropertyExample.java | 55 -- .../ScheduledExecutorServiceSpike.java | 60 -- .../owner/importedprops/ImportConfigTest.java | 119 ---- .../SystemPropertiesAndEnvTest.java | 49 -- .../WithImportedPropertiesTest.java | 131 ---- .../interfaces/AccessibleConfigTest.java | 140 ---- .../owner/interfaces/MutableConfigTest.java | 111 --- .../org/aeonbits/owner/issues/Issue123.java | 58 -- .../org/aeonbits/owner/issues/Issue184.java | 50 -- .../org/aeonbits/owner/issues/Issue203.java | 57 -- .../org/aeonbits/owner/issues/Issue268.java | 95 --- .../org/aeonbits/owner/issues/Issue87.java | 75 --- .../org/aeonbits/owner/jmx/JMXMBeanTest.java | 94 --- .../owner/loaders/PropertiesLoaderTest.java | 49 -- .../owner/loaders/SystemLoaderTest.java | 140 ---- .../DefaultLoadStrategyTest.java | 72 -- .../loadstrategies/FirstLoadStrategyTest.java | 116 ---- .../LoadPathsWithSpacesTest.java | 52 -- .../loadstrategies/LoadStrategyTestBase.java | 37 - .../loadstrategies/MergeLoadStrategyTest.java | 68 -- .../multithread/MultiThreadReloadTest.java | 134 ---- .../multithread/MultiThreadTestBase.java | 62 -- .../owner/multithread/ThreadBase.java | 62 -- .../owner/reload/AsyncAutoReloadTest.java | 122 ---- .../owner/reload/AsyncReloadSupport.java | 30 - ...HotReloadWhenURLContainsVariablesTest.java | 89 --- .../org/aeonbits/owner/reload/ReloadTest.java | 142 ---- .../owner/reload/SyncAutoReloadTest.java | 190 ------ .../reload/SystemPropertiesReloadTest.java | 72 -- .../owner/serializable/TestSerialization.java | 114 ---- .../typeconversion/ConverterClassTest.java | 198 ------ .../typeconversion/ConverterRegistryTest.java | 76 --- .../typeconversion/PrimitiveTypesTest.java | 78 --- .../typeconversion/SpecialTypesTest.java | 228 ------- .../arrays/ArraySupportTest.java | 102 --- .../arrays/BasicArrayWithAnnotationTest.java | 49 -- .../ConflictingAnnotationResolutionTest.java | 59 -- ...onflictingAnnotationsOnClassLevelTest.java | 54 -- ...nflictingAnnotationsOnMethodLevelTest.java | 52 -- .../arrays/CustomCommaTokenizer.java | 20 - .../arrays/CustomDashTokenizer.java | 20 - .../arrays/InvalidAnnotationTest.java | 52 -- .../SeparatorAnnotationOnClassLevelTest.java | 60 -- .../TokenizerAnnotationOnClassLevelTest.java | 62 -- .../collections/CollectionSupportTest.java | 120 ---- .../editor/PropertyEditorNotAvailable.java | 37 - .../editor/PropertyEditorTest.java | 58 -- .../editor/PropertyEditorTestUtil.java | 27 - .../owner/typeconversion/editor/User.java | 24 - .../editor/UserPropertyEditor.java | 23 - .../org/aeonbits/owner/util/Base64Test.java | 46 -- .../aeonbits/owner/util/ReflectionTest.java | 33 - .../owner/util/SystemProviderForTest.java | 48 -- .../owner/util/TimeProviderForTest.java | 48 -- .../org/aeonbits/owner/util/UtilTest.java | 176 ----- .../variableexpansion/KeyExpansionTest.java | 153 ----- .../ParametrizedKeyTest.java | 54 -- .../variableexpansion/PropertyNotSetTest.java | 57 -- .../VariableExpansionTest.java | 34 - .../owner/xml/SAXParserFactoryForTest.java | 45 -- .../org/aeonbits/owner/xml/XmlSourceTest.java | 150 ----- .../owner/ConfigTest$SampleConfig.properties | 13 - ...Test$ConfigWithSubstitutionFile.properties | 13 - .../org/aeonbits/owner/FooBar.properties | 9 - ...aderManagerTest$MyConfigDefaultSpec.foobar | 9 - ...ManagerTest$MyConfigDefaultSpec.properties | 9 - .../directory with spaces/simple.properties | 9 - .../org/aeonbits/owner/first.properties | 10 - ...tedPropertiesHaveHigherPriority.properties | 9 - ...tiesTest$WithImportedProperties.properties | 9 - ...ltLoadStrategyTest$SampleConfig.properties | 9 - .../org/aeonbits/owner/second.properties | 10 - .../org/aeonbits/owner/third.properties | 12 - .../variableexpansion/KeyExpansionExample.xml | 24 - .../org/aeonbits/owner/xml/Config.xml | 18 - .../owner/xml/XmlSourceTest$ServerConfig.xml | 19 - .../xml/XmlSourceTest$ServerConfigInvalid.xml | 19 - .../XmlSourceTest$ServerConfigJavaFormat.xml | 19 - owner/src/test/resources/test.properties | 9 - phileas-configuration/pom.xml | 25 - .../configuration/PhileasConfiguration.java | 184 ----- .../src/test/resources/log4j2.xml | 14 - phileas-core/pom.xml | 15 +- .../services/PhileasFilterService.java | 2 +- .../filters/ai/python/PersonsV1Filter.java | 8 +- .../test/phileas/services/EndToEndTests.java | 74 +- .../services/PhileasFilterServiceTest.java | 8 +- .../registry/S3PolicyServiceTest.java | 17 +- phileas-model/pom.xml | 17 +- .../cache/AbstractRedisCacheService.java | 2 +- .../configuration/PhileasConfiguration.java | 230 +++++++ .../pom.xml | 10 +- .../phileas-processors-unstructured/pom.xml | 2 +- phileas-processors/pom.xml | 8 - phileas-services-split/pom.xml | 2 +- phileas-services/phileas-services-ai/pom.xml | 21 +- .../phileas/services/ai/InferenceTest.java | 20 - .../services/ai/models/ModelCacheTest.java | 6 +- .../phileas-services-alerts/pom.xml | 2 +- .../services/alerts/AlertServiceFactory.java | 2 +- .../services/alerts/RedisAlertService.java | 2 +- .../alerts/RedisAlertServiceTest.java | 13 +- .../phileas-services-anonymization/pom.xml | 7 +- .../AnonymizationCacheServiceFactory.java | 2 +- .../cache/RedisAnonymizationCacheService.java | 2 +- .../AnonymizationCacheServiceFactoryTest.java | 12 +- .../RedisAnonymizationCacheServiceTest.java | 10 +- .../phileas-services-disambiguation/pom.xml | 7 +- .../AbstractSpanDisambiguationService.java | 4 +- .../VectorBasedSpanDisambiguationService.java | 3 +- .../SpanDisambiguationRedisCacheService.java | 2 +- ...torBasedSpanDisambiguationServiceTest.java | 7 +- ...torBasedSpanDisambiguationServiceTest.java | 5 +- .../phileas-services-metrics/pom.xml | 15 +- .../metrics/PhileasMetricsService.java | 2 +- phileas-services/phileas-services-pdf/pom.xml | 2 +- .../phileas-services-policies/pom.xml | 7 +- .../services/policies/LocalPolicyService.java | 6 +- .../services/policies/S3PolicyService.java | 2 +- .../cache/PolicyCacheServiceFactory.java | 2 +- .../cache/RedisPolicyCacheService.java | 2 +- .../phileas-services-split/pom.xml | 2 +- phileas-services/pom.xml | 8 - pom.xml | 27 +- 210 files changed, 353 insertions(+), 13402 deletions(-) delete mode 100644 owner/README.md delete mode 100644 owner/pom.xml delete mode 100644 owner/src/main/java/org/aeonbits/owner/Accessible.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Config.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/ConfigCache.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/ConfigFactory.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/ConfigURIFactory.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Converter.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Converters.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/DefaultFactory.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Delegate.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/DelegateMethodHandle.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Factory.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/HotReloadLogic.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/JMXSupport.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/LoadersManager.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Mutable.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Preprocessor.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/PreprocessorResolver.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/PropertiesInvocationHandler.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/PropertiesManager.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/PropertiesMapper.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Reloadable.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/SplitAndTrimTokenizer.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/StrSubstitutor.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/Tokenizer.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/TokenizerResolver.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/VariablesExpander.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/crypto/AbstractDecryptor.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/crypto/AbstractEncryptor.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/crypto/Decryptor.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/crypto/Encryptor.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/crypto/IdentityDecryptor.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/Event.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/ReloadEvent.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/ReloadListener.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/RollbackBatchException.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/RollbackException.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/RollbackOperationException.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/TransactionalPropertyChangeListener.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/TransactionalReloadListener.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/UnmodifiableProperties.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/event/package-info.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/loaders/Loader.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/loaders/PhileasSystemLoader.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/loaders/PropertiesLoader.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/loaders/SystemLoader.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/loaders/XMLLoader.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/loaders/package-info.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/package-info.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/util/Base64.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/util/Collections.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/util/Reflection.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/util/Util.java delete mode 100644 owner/src/main/java/org/aeonbits/owner/util/package-info.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/ConfigFactoryTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/ConfigInheritanceTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/ConfigTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/ConfigURIFactoryTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/ConfigWithSubstitutionTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/DisableFeatureTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/EqualsAndHashCodeTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/LoaderManagerTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/LoadersManagerForTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/PreprocessorTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/PropertiesInvocationHandlerTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/PropertiesManagerForTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/StrSubstitutorTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/SystemVariableExpanderTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/TestConstants.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/UndefinedPropertiesTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/VariablesExpanderForTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/cache/CacheConfigTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/crypto/CryptoConfigTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/crypto/CryptoUtils.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/crypto/SampleDecryptor.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/crypto/StandardEncryptor.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/debugging/ToStringTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/event/EventListenerOnReloadTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/event/EventListenerTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/event/ExceptionTests.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/event/PropertyChangeMatcher.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/event/UnmodifiablePropertiesTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/examples/EncryptedPropertiesExample.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/examples/JMXExample.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/examples/MapPropertyExample.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/examples/ScheduledExecutorServiceSpike.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/importedprops/ImportConfigTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/importedprops/SystemPropertiesAndEnvTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/importedprops/WithImportedPropertiesTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/interfaces/AccessibleConfigTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/interfaces/MutableConfigTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/issues/Issue123.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/issues/Issue184.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/issues/Issue203.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/issues/Issue268.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/issues/Issue87.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/jmx/JMXMBeanTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/loaders/PropertiesLoaderTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/loaders/SystemLoaderTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/loadstrategies/FirstLoadStrategyTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/loadstrategies/LoadPathsWithSpacesTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/loadstrategies/LoadStrategyTestBase.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/loadstrategies/MergeLoadStrategyTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/multithread/MultiThreadReloadTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/multithread/MultiThreadTestBase.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/multithread/ThreadBase.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/reload/AsyncAutoReloadTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/reload/AsyncReloadSupport.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/reload/HotReloadWhenURLContainsVariablesTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/reload/ReloadTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/reload/SyncAutoReloadTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/reload/SystemPropertiesReloadTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/serializable/TestSerialization.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterClassTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterRegistryTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/PrimitiveTypesTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/SpecialTypesTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ArraySupportTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/BasicArrayWithAnnotationTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationResolutionTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationsOnClassLevelTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationsOnMethodLevelTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/CustomCommaTokenizer.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/CustomDashTokenizer.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/InvalidAnnotationTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/SeparatorAnnotationOnClassLevelTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/TokenizerAnnotationOnClassLevelTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/collections/CollectionSupportTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorNotAvailable.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorTestUtil.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/editor/User.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/typeconversion/editor/UserPropertyEditor.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/util/Base64Test.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/util/ReflectionTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/util/SystemProviderForTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/util/TimeProviderForTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/util/UtilTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/variableexpansion/KeyExpansionTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/variableexpansion/ParametrizedKeyTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/variableexpansion/PropertyNotSetTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/variableexpansion/VariableExpansionTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/xml/SAXParserFactoryForTest.java delete mode 100644 owner/src/test/java/org/aeonbits/owner/xml/XmlSourceTest.java delete mode 100644 owner/src/test/resources/org/aeonbits/owner/ConfigTest$SampleConfig.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/ConfigWithSubstitutionTest$ConfigWithSubstitutionFile.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/FooBar.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/LoaderManagerTest$MyConfigDefaultSpec.foobar delete mode 100644 owner/src/test/resources/org/aeonbits/owner/LoaderManagerTest$MyConfigDefaultSpec.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/directory with spaces/simple.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/first.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/importedprops/ImportConfigTest$ImportedPropertiesHaveHigherPriority.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/importedprops/WithImportedPropertiesTest$WithImportedProperties.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest$SampleConfig.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/second.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/third.properties delete mode 100644 owner/src/test/resources/org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml delete mode 100644 owner/src/test/resources/org/aeonbits/owner/xml/Config.xml delete mode 100644 owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfig.xml delete mode 100644 owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfigInvalid.xml delete mode 100644 owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfigJavaFormat.xml delete mode 100644 owner/src/test/resources/test.properties delete mode 100644 phileas-configuration/pom.xml delete mode 100644 phileas-configuration/src/main/java/ai/philterd/phileas/configuration/PhileasConfiguration.java delete mode 100644 phileas-configuration/src/test/resources/log4j2.xml create mode 100644 phileas-model/src/main/java/ai/philterd/phileas/model/configuration/PhileasConfiguration.java delete mode 100644 phileas-services/phileas-services-ai/src/test/java/ai/philterd/test/phileas/services/ai/InferenceTest.java diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 040856f67..d06c9de0d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,5 @@ name: Build -on: [pull_request, workflow_dispatch] +on: [push, pull_request, workflow_dispatch] jobs: build: runs-on: ubuntu-latest diff --git a/owner/README.md b/owner/README.md deleted file mode 100644 index e28a2e419..000000000 --- a/owner/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# `owner` - -This module is a fork of the [owner](https://github.com/matteobaccan/owner) project that provides an easy to use API for Java property files. - -The project was forked here and not used as a dependency because it adds the `PhileasSystemLoader` class. This class allows for specifying `system:properties` and `system:env` with the `@Sources` annotation. -It looks for environment variables whose names start with `philter_`. Note that underscores are replaced for periods because periods are not allowed in environment variable names. - -This allows properties to be set either via a properties file or via environment variables. Note that properties set by environment variables take precedence over properties set in a properties file. - -For more context, see this [comment and thread](https://github.com/matteobaccan/owner/issues/267#issuecomment-642194768) on GitHub. - -``` - -Copyright (c) 2012-2015, Luigi R. Viggiano -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE -``` \ No newline at end of file diff --git a/owner/pom.xml b/owner/pom.xml deleted file mode 100644 index 7a929732e..000000000 --- a/owner/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - 4.0.0 - - ai.philterd - phileas - 2.6.0-SNAPSHOT - - owner - owner - Get rid of the boilerplate code in Java properties based configuration. - jar - - - - org.hamcrest - hamcrest-all - 1.3 - test - - - junit - junit - 4.13.1 - test - - - org.mockito - mockito-core - 2.23.4 - test - - - commons-codec - commons-codec - ${commons.codec.version} - test - - - \ No newline at end of file diff --git a/owner/src/main/java/org/aeonbits/owner/Accessible.java b/owner/src/main/java/org/aeonbits/owner/Accessible.java deleted file mode 100644 index e568d96e5..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Accessible.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.util.Map; -import java.util.Set; - -/** - *

Allows a Config object to access the contents of the properties, providing utility methods to perform - * consequent operations.

- *

Example:

- *
- *     public interface MyConfig extends Config, Accessible {
- *         int someProperty();
- *     }
- *
- *     public void doSomething() {
- *         MyConfig cfg = ConfigFactory.create(MyConfig.class);
- *         cfg.list(System.out);
- *     }
- * 
- *

These methods will print the list of properties, see {@link java.util.Properties#list(java.io.PrintStream)} and - * {@link java.util.Properties#list(java.io.PrintWriter)}.

- * - * @author Luigi R. Viggiano - * @since 1.0.4 - */ -public interface Accessible extends Config { - - /** - * Prints this property list out to the specified output stream. This method is useful for debugging. - * - * @param out an output stream. - * @throws ClassCastException if any key in this property list is not a string. - * @see java.util.Properties#list(java.io.PrintStream) - * @since 1.0.4 - */ - void list(PrintStream out); - - /** - * Prints this property list out to the specified output stream. This method is useful for debugging. - * - * @param out an output stream. - * @throws ClassCastException if any key in this property list is not a string. - * @see java.util.Properties#list(java.io.PrintWriter) - * @since 1.0.4 - */ - void list(PrintWriter out); - - /** - * Stores the underlying properties into an {@link java.io.OutputStream}. - *

- * Notice that method {@link java.util.Properties#store(java.io.Writer, String)} is not implemented since it's not - * available in JDK 1.5 (while the target of this library is Java 1.5+). - * - * @param out an output stream. - * @param comments a description of the property list. - * @throws IOException if writing this property list to the specified output stream throws an IOException. - * @see java.util.Properties#store(java.io.OutputStream, String) - * @since 1.0.4 - */ - void store(OutputStream out, String comments) throws IOException; - - /** - * Fills the given {@link java.util.Map} with the properties contained by this object.
- * This is useful to extract the content of the config object into a {@link java.util.Map}. - *

- * Notice that you can specify a properties object as parameter instead of a map, - * since {@link java.util.Properties} implements the {@link java.util.Map} interface. - * - * @param map the {@link java.util.Map} to fill. - * @since 1.0.9 - */ - void fill(Map map); - - /** - * Searches for the property with the specified key in this property list. - * If the key is not found in this property list, the default property list, - * and its defaults, recursively, are then checked. The method returns - * null if the property is not found. - * - * @param key the property key. - * @return the value in this property list with the specified key value. - * @see java.util.Properties#getProperty(String) - * @since 1.0.4 - */ - String getProperty(String key); - - /** - * Searches for the property with the specified key in this property list. - * If the key is not found in this property list, the default property list, - * and its defaults, recursively, are then checked. The method returns the - * default value argument if the property is not found. - * - * @param key the property key. - * @param defaultValue a default value. - * @return the value in this property list with the specified key value. - * @see java.util.Properties#getProperty(String, String) - * - * @since 1.0.4 - */ - String getProperty(String key, String defaultValue); - - /** - * Emits an XML document representing all of the properties contained - * in this table. - * - *

An invocation of this method of the form props.storeToXML(os, - * comment) behaves in exactly the same way as the invocation - * props.storeToXML(os, comment, "UTF-8");. - * - * @param os the output stream on which to emit the XML document. - * @param comment a description of the property list, or null - * if no comment is desired. - * @throws IOException if writing to the specified output stream - * results in an IOException. - * @throws NullPointerException if os is null. - * @throws ClassCastException if this Properties object - * contains any keys or values that are not - * Strings. - * @since 1.0.5 - */ - void storeToXML(OutputStream os, String comment) throws IOException; - - /** - * Returns a set of keys in this property list - * including distinct keys in the default property list if a key - * of the same name has not already been found from the main - * properties list. - *

- * The returned set is not backed by the Properties object. - * Changes to this Properties are not reflected in the set, - * or vice versa. - * - * @return a set of keys in this property list, including the keys in the - * default property list. - * @throws ClassCastException if any key in this property list - * is not a string. - * @see java.util.Properties#defaults - * @see java.util.Properties#stringPropertyNames() - * @see java.util.Properties#propertyNames() - * @since 1.0.5 - */ - Set propertyNames(); - -} diff --git a/owner/src/main/java/org/aeonbits/owner/Config.java b/owner/src/main/java/org/aeonbits/owner/Config.java deleted file mode 100644 index 930cf5159..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Config.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - - -import org.aeonbits.owner.crypto.Decryptor; -import org.aeonbits.owner.crypto.IdentityDecryptor; - -import java.io.IOException; -import java.io.Serializable; -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; -import java.net.URI; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.aeonbits.owner.Config.HotReloadType.SYNC; -import static org.aeonbits.owner.Config.LoadType.FIRST; -import static org.aeonbits.owner.util.Util.ignore; -import static org.aeonbits.owner.util.Util.reverse; -/** - * Marker interface that must be implemented by all Config sub-interfaces. - *

- * Sub-interfaces may also extend {@link Accessible} to allow some debugging facility, or {@link Reloadable} to allow the - * user to programmatically reload properties. - *

- * - * @author Luigi R. Viggiano - * @see java.util.Properties - */ -public interface Config extends Serializable { - /** - * Specifies the policy for loading the properties files. By default the first available properties file specified - * by {@link Sources} will be loaded, see {@link LoadType#FIRST}. User can also specify that the load policy is - * {@link LoadType#MERGE} to have the properties files merged: properties are loaded in order from the first file to - * the last, if there are conflicts in properties names the earlier files loaded prevail. - * - * @since 1.0.2 - */ - @Retention(RUNTIME) - @Target(TYPE) - @Documented - @interface LoadPolicy { - LoadType value() default FIRST; - } - - /** - * Specifies the source from which to load the properties file. It has to be specified in a URI string format. - * By default, allowed protocols are the ones allowed by {@link java.net.URL} plus - * classpath:path/to/resource.properties, but user can specify his own additional protocols. - * - * @since 1.0.2 - */ - @Retention(RUNTIME) - @Target(TYPE) - @Documented - @interface Sources { - String[] value(); - } - - /** - * Default value to be used if no property is found. No quoting (other than normal Java string quoting) is done. - */ - @Retention(RUNTIME) - @Target(METHOD) - @Documented - @interface DefaultValue { - String value(); - } - - /** - * The key used for lookup for the property. If not present, the key will be generated based on the unqualified - * method name. - */ - @Retention(RUNTIME) - @Target(METHOD) - @Documented - @interface Key { - String value(); - } - - /** - * When a value should be decrypted this annotation is needed. - * If value is not supplied it assumes that will be used the {@link Decryptor} setted in {@link DecryptorClass}. - * This overrides the {@link EncryptedValue} Descryptor defined for the class. - */ - @Retention(RUNTIME) - @Target(METHOD) - @Documented - @interface EncryptedValue { - Class value() default IdentityDecryptor.class; - } - - /** - * When a value should be decrypted this annotation is needed. - * This is the class {@link Decryptor}, the default Decryptor used to decrypt a key when none is - * defined at {@link EncryptedValue}. This allows share the same decryptor for all encrypted keys. - */ - @Retention(RUNTIME) - @Target(TYPE) - @Documented - @interface DecryptorClass { - Class value() default IdentityDecryptor.class; - } - - /** - * Specifies the policy type to use to load the {@link org.aeonbits.owner.Config.Sources} files for properties. - * - * @since 1.0.2 - */ - enum LoadType { - - /** - * The first available of the specified sources will be loaded. - */ - FIRST { - @Override - Properties load(List uris, LoadersManager loaders) { - Properties result = new Properties(); - for (URI uri : uris) - try { - loaders.load(result, uri); - break; - } catch (IOException ex) { - // happens when a file specified in the sources is not found or cannot be read. - ignore(); - } - return result; - } - }, - - /** - * All the specified sources will be loaded and merged. If the same property key is - * specified from more than one source, the one specified first will prevail. - */ - MERGE { - @Override - Properties load(List uris, LoadersManager loaders) { - Properties result = new Properties(); - for (URI uri : reverse(uris)) - try { - loaders.load(result, uri); - } catch (IOException ex) { - // happens when a file specified in the sources is not found or cannot be read. - ignore(); - } - return result; - } - }; - - abstract Properties load(List uris, LoadersManager loaders); - } - - /** - * Specify that the class implements hot reloading of properties from filesystem baked {@link Sources} (hot - * reloading can't be applied to all types of URIs). - *

- * It is possible to specify an interval to indicate how frequently the library shall check the files for - * modifications and perform the reload. - *

- * Examples: - *
-     *      @HotReload    // will check for file changes every 5 seconds.
-     *      @Sources("file:foo/bar/baz.properties")
-     *      interface MyConfig extends Config { ... }
-     *
-     *      @HotReload(2)    // will check for file changes every 2 seconds.
-     *      @Sources("file:foo/bar/baz.properties")
-     *      interface MyConfig extends Config { ... }
-     *
-     *      @HotReload(500, unit = TimeUnit.MILLISECONDS);  // will check for file changes every 500 milliseconds.
-     *      @Sources("file:foo/bar/baz.properties")
-     *      interface MyConfig extends Config { ... }
-     *
-     *      @HotReload(type=HotReloadType.ASYNC);  // will use ASYNC reload type: will span a separate thread
-     *                                                 // that will check for the file change every 5 seconds (default).
-     *      @Sources("file:foo/bar/baz.properties")
-     *      interface MyConfig extends Config { ... }
-     *
-     *      @HotReload(2, type=HotReloadType.ASYNC);  // will use ASYNC reload type and will check every 2 seconds.
-     *      @Sources("file:foo/bar/baz.properties")
-     *      interface MyConfig extends Config { ... }
-     * 
- * - *

- * To intercept the {@link org.aeonbits.owner.event.ReloadEvent} see {@link Reloadable#addReloadListener(org.aeonbits.owner.event.ReloadListener)}. - * - * @since 1.0.4 - */ - @Retention(RUNTIME) - @Target(TYPE) - @Documented - @interface HotReload { - /** - * The interval, expressed in seconds (by default), to perform checks on the filesystem to identify modified - * files and eventually perform the reloading of the properties. By default is 5 seconds. - * - * @return the hot reload value; default is 5. - */ - long value() default 5; - - /** - *

- * The time unit for the interval. By default it is {@link TimeUnit#SECONDS}. - *

- *

- * Date resolution vary from filesystem to filesystem.
- * For instance, for Ext3, ReiserFS and HSF+ the date resolution is of 1 second.
- * For FAT32 the date resolution for the last modified time is 2 seconds.
- * For Ext4 the date resolution is in nanoseconds. - *

- *

- * So, it is a good idea to express the time unit in seconds or more, since higher time resolution - * will probably not be supported by the underlying filesystem. - *

- * @return the time unit; default is SECONDS. - */ - TimeUnit unit() default SECONDS; - - /** - * The type of HotReload to use. It can be: - * - *

- * {@link HotReloadType#SYNC Synchronous}: the configuration file is checked when a method is invoked on the - * config object. So if the config object is not used for some time, the configuration doesn't get reloaded, - * until its next usage. i.e. until next method invocation. - *

- * {@link HotReloadType#ASYNC}: the configuration file is checked by a background thread despite the fact that - * the config object is used or not. - * - * @return the hot reload type; default is SYNC. - */ - HotReloadType type() default SYNC; - } - - /** - * Allows to specify which type of HotReload should be applied. - */ - enum HotReloadType { - /** - * The hot reload will happen when one of the methods is invoked on the Config class. - */ - SYNC, - - /** - * The hot reload will happen in background at the specified interval. - */ - ASYNC - } - - /** - * Specifies to disable some of the features supported by the API. - * This may be useful in case the user prefers to implement by his own, or just has troubles with something that - * is unwanted. - * Features that can be disabled are specified in the enum {@link DisableableFeature}. - * - * @since 1.0.4 - */ - @Retention(RUNTIME) - @Target({METHOD, TYPE}) - @Documented - @interface DisableFeature { - DisableableFeature[] value(); - } - - /** - * This enum contains the features that can be disabled using the annotation {@link DisableFeature}. - * - * @since 1.0.4 - */ - enum DisableableFeature { - VARIABLE_EXPANSION, - PARAMETER_FORMATTING - } - - /** - * Specifies simple {@link String} as separator to tokenize properties values specified as a - * single string value, into elements for vectors and collections. - * The value specified is used as per {@link String#split(String, int)} with int=-1, every element is also - * trimmed out from spaces using {@link String#trim()}. - * - * Notice that {@link TokenizerClass} and {@link Separator} do conflict with each-other when they are both specified - * together on the same level: - *

    - *
  • - * You cannot specify {@link TokenizerClass} and {@link Separator} both together on the same method - *
  • - *
  • - * You cannot specify {@link TokenizerClass} and {@link Separator} both together on the same class - *
  • - *
- * in the two above cases an {@link UnsupportedOperationException} will be thrown when the corresponding conversion - * is executed. - * - * @since 1.0.4 - */ - @Retention(RUNTIME) - @Target({METHOD, TYPE}) - @Documented - @interface Separator { - /** - * @return the value specified is used as per {@link java.lang.String#split(String, int)} with int=-1 - */ - String value(); - } - - /** - * Specifies a {@link Tokenizer} class to allow the user to define a custom logic to split - * the property value into tokens to be used as single elements for vectors and collections. - * - * Notice that {@link TokenizerClass} and {@link Separator} do conflict with each-other when they are both specified - * together on the same level: - *
    - *
  • - * You cannot specify {@link TokenizerClass} and {@link Separator} both together on the same method - *
  • - *
  • - * You cannot specify {@link TokenizerClass} and {@link Separator} both together on the same class - *
  • - *
- * in the two above cases an {@link UnsupportedOperationException} will be thrown when the corresponding conversion - * is executed. - * - * @since 1.0.4 - */ - @Retention(RUNTIME) - @Target({METHOD, TYPE}) - @Documented - @interface TokenizerClass { - Class value(); - } - - /** - * Specifies a {@link Converter} class to allow the user to define a custom conversion logic for the - * type returned by the method. If the method returns a collection, the Converter is used to convert a single - * element. - */ - @Retention(RUNTIME) - @Target(METHOD) - @Documented - @interface ConverterClass { - Class value(); - } - - /** - * Specifies a {@link Preprocessor} class to allow the user to define a custom logic to pre-process - * the property value before being used by the library. - * - * @since 1.0.9 - */ - @Retention(RUNTIME) - @Target({METHOD, TYPE}) - @Documented - @interface PreprocessorClasses { - Class[] value(); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/ConfigCache.java b/owner/src/main/java/org/aeonbits/owner/ConfigCache.java deleted file mode 100644 index 7902f3344..000000000 --- a/owner/src/main/java/org/aeonbits/owner/ConfigCache.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.util.Collections; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * Utility class caching Config instances that can be used as Singletons. - * - * This class is designed to be thread safe. - * - * @author Luigi R. Viggiano - * @since 1.0.6 - */ -public final class ConfigCache { - private static final ConcurrentMap CACHE = new ConcurrentHashMap(); - - /** Don't let anyone instantiate this class */ - private ConfigCache() {} - - /** - * Gets from the cache or create, an instance of the given class using the given imports. - * The factory used to create new instances is the static {@link ConfigFactory#INSTANCE}. - * - * @param clazz the interface extending from {@link Config} that you want to instantiate. - * @param imports additional variables to be used to resolve the properties. - * @param type of the interface. - * @return an object implementing the given interface, that can be taken from the cache, - * which maps methods to property values. - */ - public static T getOrCreate(Class clazz, Map... imports) { - return getOrCreate(ConfigFactory.INSTANCE, clazz, clazz, imports); - } - - /** - * Gets from the cache or create, an instance of the given class using the given imports. - * - * @param factory the factory to use to eventually create the instance. - * @param clazz the interface extending from {@link Config} that you want to instantiate. - * @param imports additional variables to be used to resolve the properties. - * @param type of the interface. - * @return an object implementing the given interface, that can be taken from the cache, - * which maps methods to property values. - */ - public static T getOrCreate(Factory factory, Class clazz, Map... imports) { - return getOrCreate(factory, clazz, clazz, imports); - } - - /** - * Gets from the cache or create, an instance of the given class using the given imports. - * The factory used to create new instances is the static {@link ConfigFactory#INSTANCE}. - * - * @param key the key object to be used to identify the instance in the cache. - * @param clazz the interface extending from {@link Config} that you want to instantiate. - * @param imports additional variables to be used to resolve the properties. - * @param type of the interface. - * @return an object implementing the given interface, that can be taken from the cache, - * which maps methods to property values. - */ - public static T getOrCreate(Object key, Class clazz, Map... imports) { - return getOrCreate(ConfigFactory.INSTANCE, key, clazz, imports); - } - - /** - * Gets from the cache or create, an instance of the given class using the given imports. - * - * @param factory the factory to use to eventually create the instance. - * @param key the key object to be used to identify the instance in the cache. - * @param clazz the interface extending from {@link Config} that you want to instantiate. - * @param imports additional variables to be used to resolve the properties. - * @param type of the interface. - * @return an object implementing the given interface, that can be taken from the cache, - * which maps methods to property values. - */ - public static T getOrCreate(Factory factory, Object key, - Class clazz, Map... imports) { - T existing = get(key); - if (existing != null) return existing; - T created = factory.create(clazz, imports); - T raced = add(key, created); - return raced != null ? raced : created; - } - - /** - * Gets from the cache the {@link Config} instance identified by the given key. - * - * @param key the key object to be used to identify the instance in the cache. - * @param type of the interface. - * @return the {@link Config} object from the cache if exists, or null if it doesn't. - */ - @SuppressWarnings("unchecked") - public static T get(Object key) { - return (T) CACHE.get(key); - } - - /** - * Adds a {@link Config} object into the cache. - * - * @param key the key object to be used to identify the instance in the cache. - * @param instance the instance of the {@link Config} object to be stored into the cache. - * @param type of the interface. - * @return the previous value associated with the specified key, or - * null if there was no mapping for the key. - */ - @SuppressWarnings("unchecked") - public static T add(Object key, T instance) { - return (T) CACHE.putIfAbsent(key, instance); - } - - /** - * Lists the key objects for all configuration instances present in the cache. - * - * @return a set containing the key objects for all instance in the cache. - */ - public static Set list() { - // Return an unmodifiableSet to ensure that the caller does not modify the contents of our - // private map via the result of this call. The key objects themselves are the same as - // those contained in the private map, which means that if they are mutable, the caller - // will be able to affect the contents of the map (albeit only the keys). - return Collections.unmodifiableSet(CACHE.keySet()); - } - - /** - * Removes all of the cached instances. - * The cache will be empty after this call returns. - */ - public static void clear() { - CACHE.clear(); - } - - /** - * Removes the cached instance for the given key if it is present. - * - *

Returns previous instance associated to the given key in the cache, - * or null if the cache contained no instance for the given key. - * - *

The cache will not contain the instance for the specified key once the - * call returns. - * - * @param type of the interface. - * @param key key whose instance is to be removed from the cache. - * @return the previous instance associated with key, or - * null if there was no instance for key. - */ - @SuppressWarnings("unchecked") - public static T remove(Object key) { - return (T) CACHE.remove(key); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/ConfigFactory.java b/owner/src/main/java/org/aeonbits/owner/ConfigFactory.java deleted file mode 100644 index a33949e0f..000000000 --- a/owner/src/main/java/org/aeonbits/owner/ConfigFactory.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.loaders.Loader; - -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; - -import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; - -/** - * A static factory class to instantiate {@link Config} instances. - *

- * By default a {@link Config} sub-interface is associated to a property having the same package name and class name as - * the interface itself.

- *

- * Method names are mapped to property names contained in the property files.

- *

- * This is a singleton static class, to be used as convenience when only a single factory is needed inside an - * application. It exposes the {@link #newInstance()} method to create new instances of {@link Factory} objects. - *

- * @author Luigi R. Viggiano - */ -public final class ConfigFactory { - - static final Factory INSTANCE = newInstance(); - - /** Don't let anyone instantiate this class */ - private ConfigFactory() {} - - /** - * Returns a new instance of a config Factory object. - * - * @return a new instance of a config Factory object. - */ - public static Factory newInstance() { - ScheduledExecutorService scheduler = newSingleThreadScheduledExecutor(new ThreadFactory() { - public Thread newThread(Runnable r) { - Thread result = new Thread(r); - result.setDaemon(true); - return result; - } - }); - Properties props = new Properties(); - return new DefaultFactory(scheduler, props); - } - - /** - * Creates a {@link Config} instance from the specified interface - * - * @param clazz the interface extending from {@link Config} that you want to instantiate. - * @param imports additional variables to be used to resolve the properties. - * @param type of the interface. - * @return an object implementing the given interface, which maps methods to property values. - */ - public static T create(Class clazz, Map... imports) { - for( Map map : imports ){ - for( Object key : map.keySet() ){ - if( key == null || map.get(key) == null){ - throw new IllegalArgumentException(String.format("An import contains a null value for key: '%s'", key)); - } - } - } - return INSTANCE.create(clazz, imports); - } - - /** - * Set a property in the ConfigFactory. Those properties will be used to expand variables specified in the `@Source` - * annotation, or by the ConfigFactory to configure its own behavior. - * - * @param key the key for the property. - * @param value the value for the property. - * @return the old value. - * @since 1.0.4 - */ - public static String setProperty(String key, String value) { - return INSTANCE.setProperty(key, value); - } - - /** - * Those properties will be used to expand variables specified in the `@Source` annotation, or by the ConfigFactory - * to configure its own behavior. - * - * @return the properties in the ConfigFactory - * @since 1.0.4 - */ - public static Properties getProperties() { - return INSTANCE.getProperties(); - } - - /** - * Those properties will be used to expand variables specified in the `@Source` annotation, or by the ConfigFactory - * to configure its own behavior. - * - * @param properties the properties to set in the config Factory. - * @since 1.0.4 - */ - public static void setProperties(Properties properties) { - INSTANCE.setProperties(properties); - } - - /** - * Returns the value for a given property. - * - * @param key the key for the property - * @return the value for the property, or null if the property is not set. - * @since 1.0.4 - */ - public static String getProperty(String key) { - return INSTANCE.getProperty(key); - } - - /** - * Clears the value for the property having the given key. This means, that the given property is removed. - * - * @param key the key for the property to remove. - * @return the old value for the given key, or null if the property was not set. - * @since 1.0.4 - */ - public static String clearProperty(String key) { - return INSTANCE.clearProperty(key); - } - - /** - * Registers a loader to enables additional file formats. - * - * @param loader the loader to register. - * @throws NullPointerException if specified loader is null. - * @since 1.0.5 - */ - public static void registerLoader(Loader loader) { - INSTANCE.registerLoader(loader); - } - - /** - * Sets a converter for the given type. Setting a converter via this method will override any default converters - * but not {@link Config.ConverterClass} annotations. - * - * @param type the type for which to set a converter. - * @param converter the converter class to use for the specified type. - * @since 1.0.10 - */ - public static void setTypeConverter(Class type, Class> converter) { - INSTANCE.setTypeConverter(type, converter); - } - - /** - * Removes a converter for the given type. - * @param type the type for which to remove the converter. - * @since 1.0.10 - */ - public static void removeTypeConverter(Class type){ - INSTANCE.removeTypeConverter(type); - } -} diff --git a/owner/src/main/java/org/aeonbits/owner/ConfigURIFactory.java b/owner/src/main/java/org/aeonbits/owner/ConfigURIFactory.java deleted file mode 100644 index b7276db0c..000000000 --- a/owner/src/main/java/org/aeonbits/owner/ConfigURIFactory.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; - -import static org.aeonbits.owner.util.Util.fixBackslashesToSlashes; -import static org.aeonbits.owner.util.Util.fixSpacesToPercentTwenty; - -/** - * @author Luigi R. Viggiano - */ -class ConfigURIFactory { - - private static final String CLASSPATH_PROTOCOL = "classpath:"; - private static final String FILE_PROTOCOL = "file:"; - private final transient ClassLoader classLoader; - private final VariablesExpander expander; - - ConfigURIFactory(ClassLoader classLoader, VariablesExpander expander) { - this.classLoader = classLoader; - this.expander = expander; - } - - URI newURI(String spec) throws URISyntaxException { - String expanded = expand(spec); - String fixed = fixBackslashesToSlashes(expanded); - if (fixed.startsWith(CLASSPATH_PROTOCOL)) { - String path = fixed.substring(CLASSPATH_PROTOCOL.length()); - URL url = classLoader.getResource(path); - if (url == null) - return null; - return url.toURI(); - } else if (fixed.startsWith(FILE_PROTOCOL)) { - // This check fixes the case where an environment variable has been - // specified for the path to the config file, but that environment - // variable is blank / undefined. - if ( fixed.equals(FILE_PROTOCOL) ) { - return new URI(""); - } else { - String path = fixSpacesToPercentTwenty(fixed); - return new URI(path); - } - } else { - return new URI(fixed); - } - } - - private String expand(String path) { - return expander.expand(path); - } - - String toClasspathURLSpec(String name) { - return CLASSPATH_PROTOCOL + name.replace('.', '/'); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/Converter.java b/owner/src/main/java/org/aeonbits/owner/Converter.java deleted file mode 100644 index f4ced2ae1..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Converter.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.lang.reflect.Method; - -/** - * Converter interface specifies how to convert an input string coming from a property value to a target object returned - * by the Config method. - * - * @param the type of the class that should be returned from the conversion. - * @author Luigi R. Viggiano - * @since 1.0.4 - */ -public interface Converter { - - /** - * Converts the given input into an Object of type T. - * If the method returns null, null will be returned by the Config object. - * The converter is instantiated for every call, so it shouldn't have any internal state. - * - * @param method the method invoked on the {@link Config} object - * @param input the property value specified as input text to be converted to the T return type - * @return the object of type T converted from the input string. - * @since 1.0.4 - */ - T convert(Method method, String input); - -} diff --git a/owner/src/main/java/org/aeonbits/owner/Converters.java b/owner/src/main/java/org/aeonbits/owner/Converters.java deleted file mode 100644 index 4231c7f45..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Converters.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.ConverterClass; - -import java.beans.PropertyEditor; -import java.beans.PropertyEditorManager; -import java.io.File; -import java.lang.reflect.Array; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -import static java.beans.PropertyEditorManager.findEditor; -import static java.lang.Boolean.getBoolean; -import static java.lang.reflect.Modifier.isStatic; -import static org.aeonbits.owner.Converters.SpecialValue.NULL; -import static org.aeonbits.owner.Converters.SpecialValue.SKIP; -import static org.aeonbits.owner.util.Util.expandUserHome; -import static org.aeonbits.owner.util.Util.unreachableButCompilerNeedsThis; -import static org.aeonbits.owner.util.Util.unsupported; -import static org.aeonbits.owner.util.Reflection.isClassAvailable; - -/** - * Converter class from {@link java.lang.String} to property types. - * - * @author Luigi R. Viggiano - */ -enum Converters { - - ARRAY { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - if (!targetType.isArray()) return SKIP; - - Class type = targetType.getComponentType(); - - if (text.trim().isEmpty()) - return Array.newInstance(type, 0); - - Tokenizer tokenizer = TokenizerResolver.resolveTokenizer(targetMethod); - String[] chunks = tokenizer.tokens(text); - - Converters converter = doConvert(targetMethod, type, chunks[0]).getConverter(); - Object result = Array.newInstance(type, chunks.length); - - for (int i = 0; i < chunks.length; i++) { - String chunk = chunks[i]; - Object value = converter.tryConvert(targetMethod, type, chunk); - Array.set(result, i, value); - } - - return result; - } - }, - - COLLECTION { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - if (!Collection.class.isAssignableFrom(targetType)) return SKIP; - - Object[] array = convertToArray(targetMethod, text); - Collection collection = Arrays.asList(array); - Collection result = instantiateCollection(targetType); - result.addAll(collection); - return result; - } - - private Object[] convertToArray(Method targetMethod, String text) { - Class type = getGenericType(targetMethod); - Object stub = Array.newInstance(type, 0); - return (Object[]) ARRAY.tryConvert(targetMethod, stub.getClass(), text); - } - - private Class getGenericType(Method targetMethod) { - if (targetMethod.getGenericReturnType() instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) targetMethod.getGenericReturnType(); - return (Class) parameterizedType.getActualTypeArguments()[0]; - } - // Default generic type for raw collections. - return String.class; - } - - private Collection instantiateCollection(Class targetType) { - if (targetType.isInterface()) - return instantiateCollectionFromInterface(targetType); - return instantiateCollectionFromClass(targetType); - } - - @SuppressWarnings("unchecked") - private Collection instantiateCollectionFromClass(Class targetType) { - try { - return (Collection) targetType.newInstance(); - } catch (Exception e) { - throw unsupported(e, "Cannot instantiate collection of type '%s'", targetType.getCanonicalName()); - } - } - - private Collection instantiateCollectionFromInterface(Class targetType) { - if (List.class.isAssignableFrom(targetType)) - return new ArrayList(); - else if (SortedSet.class.isAssignableFrom(targetType)) - return new TreeSet(); - else if (Set.class.isAssignableFrom(targetType)) - return new LinkedHashSet(); - return new ArrayList(); - } - - }, - - METHOD_WITH_CONVERTER_CLASS_ANNOTATION { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - ConverterClass annotation = targetMethod.getAnnotation(ConverterClass.class); - if (annotation == null) return SKIP; - - Class converterClass = annotation.value(); - return convertWithConverterClass(targetMethod, text, converterClass); - } - }, - - METHOD_WITH_REGISTERED_CONVERTER { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - if (!converterRegistry.containsKey(targetType)) return SKIP; - - Class converterClass = converterRegistry.get(targetType); - return convertWithConverterClass(targetMethod, text, converterClass); - } - }, - - PROPERTY_EDITOR { - private final boolean isPropertyEditorAvailable = - isClassAvailable("java.beans.PropertyEditorManager"); - - private final boolean isPropertyEditorDisabled = - getBoolean("org.aeonbits.owner.property.editor.disabled"); - - private final boolean canUsePropertyEditors = isPropertyEditorAvailable && !isPropertyEditorDisabled; - - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - if (!canUsePropertyEditors) - return SKIP; - - PropertyEditor editor = findEditor(targetType); - if (editor == null) return SKIP; - try { - editor.setAsText(text); - return editor.getValue(); - } catch (Exception e) { - throw unsupportedConversion(e, targetType, text); - } - } - }, - - /* - * This is needed for cases like when the PropertyEditor classes are not available - */ - PRIMITIVE { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - if (!targetType.isPrimitive()) return SKIP; - if (targetType == Byte.TYPE) return Byte.parseByte(text); - if (targetType == Short.TYPE) return Short.parseShort(text); - if (targetType == Integer.TYPE) return Integer.parseInt(text); - if (targetType == Long.TYPE) return Long.parseLong(text); - if (targetType == Boolean.TYPE) return Boolean.parseBoolean(text); - if (targetType == Float.TYPE) return Float.parseFloat(text); - if (targetType == Double.TYPE) return Double.parseDouble(text); - return SKIP; - } - }, - - FILE { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - if (targetType != File.class) return SKIP; - return new File(expandUserHome(text)); - } - }, - - CLASS { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - if (targetType != Class.class) return SKIP; - try { - return Class.forName(text); - } catch (ClassNotFoundException ex) { - throw unsupported(ex, CANNOT_CONVERT_MESSAGE, text, targetType.getCanonicalName()); - } - } - }, - - CLASS_WITH_STRING_CONSTRUCTOR { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - try { - Constructor constructor = targetType.getConstructor(String.class); - return constructor.newInstance(text); - } catch (Exception e) { - return SKIP; - } - } - }, - - CLASS_WITH_VALUE_OF_METHOD { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - try { - Method method = targetType.getMethod("valueOf", String.class); - if (isStatic(method.getModifiers())) - return method.invoke(null, text); - return SKIP; - } catch (Exception e) { - return SKIP; - } - } - }, - - CLASS_WITH_OBJECT_CONSTRUCTOR { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - try { - Constructor constructor = targetType.getConstructor(Object.class); - return constructor.newInstance(text); - } catch (Exception e) { - return SKIP; - } - } - }, - - UNSUPPORTED { - @Override - Object tryConvert(Method targetMethod, Class targetType, String text) { - throw unsupportedConversion(targetType, text); - } - }; - - private static Object convertWithConverterClass( - Method targetMethod, String text, Class converterClass) { - Converter converter; - try { - converter = converterClass.newInstance(); - } catch (InstantiationException e) { - throw unsupported(e, "Converter class %s can't be instantiated: %s", - converterClass.getCanonicalName(), e.getMessage()); - } catch (IllegalAccessException e) { - throw unsupported(e, "Converter class %s can't be accessed: %s", - converterClass.getCanonicalName(), e.getMessage()); - } - Object result = converter.convert(targetMethod, text); - if (result == null) return NULL; - return result; - } - - private static final Map, Class>> converterRegistry = - new ConcurrentHashMap, Class>>(); - - abstract Object tryConvert(Method targetMethod, Class targetType, String text); - - static void setTypeConverter(Class type, Class> converter) { - converterRegistry.put(type, converter); - } - - public static void removeTypeConverter(Class type) { - converterRegistry.remove(type); - } - - static Object convert(Method targetMethod, Class targetType, String text) { - return doConvert(targetMethod, targetType, text).getConvertedValue(); - } - - private static ConversionResult doConvert(Method targetMethod, Class targetType, String text) { - for (Converters converter : values()) { - Object convertedValue = converter.tryConvert(targetMethod, targetType, text); - if (convertedValue != SKIP) - return new ConversionResult(converter, convertedValue); - } - return unreachableButCompilerNeedsThis(); - } - - private static UnsupportedOperationException unsupportedConversion( - Exception cause, Class targetType, String text) { - return unsupported(cause, CANNOT_CONVERT_MESSAGE, text, targetType.getCanonicalName()); - } - - private static UnsupportedOperationException unsupportedConversion(Class targetType, String text) { - return unsupported(CANNOT_CONVERT_MESSAGE, text, targetType.getCanonicalName()); - } - - private static class ConversionResult { - private final Converters converter; - private final Object convertedValue; - - public ConversionResult(Converters converter, Object convertedValue) { - this.converter = converter; - this.convertedValue = convertedValue; - } - - public Converters getConverter() { - return converter; - } - - public Object getConvertedValue() { - return convertedValue; - } - } - - enum SpecialValue { - /** - * The NULL object: when tryConvert returns this object, the conversion result is null. - */ - NULL, - - /** - * The SKIP object: when tryConvert returns this object the conversion is skipped in favour of the next one. - */ - SKIP - } - - static final String CANNOT_CONVERT_MESSAGE = "Cannot convert '%s' to %s"; -} diff --git a/owner/src/main/java/org/aeonbits/owner/DefaultFactory.java b/owner/src/main/java/org/aeonbits/owner/DefaultFactory.java deleted file mode 100644 index 8100ce788..000000000 --- a/owner/src/main/java/org/aeonbits/owner/DefaultFactory.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.loaders.Loader; - -import javax.management.DynamicMBean; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -import static java.lang.reflect.Proxy.newProxyInstance; -import static org.aeonbits.owner.util.Reflection.isClassAvailable; - -/** - * Default implementation for {@link Factory}. - * - * @author Luigi R. Viggiano - */ -class DefaultFactory implements Factory { - - private static final boolean isJMXAvailable = isClassAvailable("javax.management.DynamicMBean"); - private final ScheduledExecutorService scheduler; - private Properties props; - final LoadersManager loadersManager; - - DefaultFactory(ScheduledExecutorService scheduler, Properties props) { - this.scheduler = scheduler; - this.props = props; - this.loadersManager = new LoadersManager(); - } - - @SuppressWarnings("unchecked") - public T create(Class clazz, Map... imports) { - Class[] interfaces = interfaces(clazz); - VariablesExpander expander = new VariablesExpander(props); - PropertiesManager manager = new PropertiesManager(clazz, new Properties(), scheduler, expander, loadersManager, - imports); - Object jmxSupport = getJMXSupport(clazz, manager); - PropertiesInvocationHandler handler = new PropertiesInvocationHandler(manager, jmxSupport); - T proxy = (T) newProxyInstance(clazz.getClassLoader(), interfaces, handler); - handler.setProxy(proxy); - return proxy; - } - - public String setProperty(String key, String value) { - checkKey(key); - return (String) props.setProperty(key, value); - } - - private void checkKey(String key) { - if (key == null) - throw new IllegalArgumentException("key can't be null"); - if (key.isEmpty()) - throw new IllegalArgumentException("key can't be empty"); - } - - public Properties getProperties() { - return props; - } - - public void setProperties(Properties properties) { - if (properties == null) - props = new Properties(); - else - props = properties; - } - - public void registerLoader(Loader loader) { - loadersManager.registerLoader(loader); - } - - public void setTypeConverter(Class type, Class> converter) { - Converters.setTypeConverter(type, converter); - } - - public void removeTypeConverter(Class type){ - Converters.removeTypeConverter(type); - } - - public String getProperty(String key) { - checkKey(key); - return props.getProperty(key); - } - - public String clearProperty(String key) { - checkKey(key); - return (String) props.remove(key); - } - - private Object getJMXSupport(Class clazz, PropertiesManager manager) { - if (isJMXAvailable) - return new JMXSupport(clazz, manager); - return null; - } - - private Class[] interfaces(Class clazz) { - if (isJMXAvailable) - return new Class[]{clazz, DynamicMBean.class}; - else - return new Class[]{clazz}; - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/Delegate.java b/owner/src/main/java/org/aeonbits/owner/Delegate.java deleted file mode 100644 index 2f9327fa3..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Delegate.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -@Retention(RUNTIME) -@Target(METHOD) -@interface Delegate { -} diff --git a/owner/src/main/java/org/aeonbits/owner/DelegateMethodHandle.java b/owner/src/main/java/org/aeonbits/owner/DelegateMethodHandle.java deleted file mode 100644 index b51fb8885..000000000 --- a/owner/src/main/java/org/aeonbits/owner/DelegateMethodHandle.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; - -/** - * @author Luigi R. Viggiano - */ -class DelegateMethodHandle { - private final Object target; - private final Method method; - - public DelegateMethodHandle(Object target, Method method) { - this.target = target; - this.method = method; - } - - public Object invoke(Object[] args) throws Throwable { - try { - return method.invoke(target, args); - } catch (InvocationTargetException e) { - throw e.getTargetException(); - } - } - - public boolean matches(Method invokedMethod) { - return invokedMethod.getName().equals(method.getName()) - && invokedMethod.getReturnType().equals(method.getReturnType()) - && Arrays.equals(invokedMethod.getParameterTypes(), method.getParameterTypes()); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/Factory.java b/owner/src/main/java/org/aeonbits/owner/Factory.java deleted file mode 100644 index 59b784383..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Factory.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.loaders.Loader; - -import java.util.Map; -import java.util.Properties; - -/** - * Interface for factory implementation used to instantiate {@link Config} instances. - * - * @author Luigi R. Viggiano - * @since 1.0.5 - */ -public interface Factory { - - /** - * Creates a {@link Config} instance from the specified interface - * - * @param clazz the interface extending from {@link Config} that you want to instantiate. - * @param imports additional variables to be used to resolve the properties. - * @param type of the interface. - * @return an object implementing the given interface, which maps methods to property values. - * @since 1.0.5 - */ - T create(Class clazz, Map... imports); - - /** - * Returns the value for a given property. - * - * @param key the key for the property - * @return the value for the property, or null if the property is not set. - * @since 1.0.5 - */ - String getProperty(String key); - - /** - * Set a property in the ConfigFactory. Those properties will be used to expand variables specified in the `@Source` - * annotation, or by the ConfigFactory to configure its own behavior. - * - * @param key the key for the property. - * @param value the value for the property. - * @return the old value. - * @since 1.0.5 - */ - String setProperty(String key, String value); - - /** - * Clears the value for the property having the given key. This means, that the given property is removed. - * - * @param key the key for the property to remove. - * @return the old value for the given key, or null if the property was not set. - * @since 1.0.5 - */ - String clearProperty(String key); - - /** - * Those properties will be used to expand variables specified in the `@Source` annotation, or by the ConfigFactory - * to configure its own behavior. - * - * @return the properties in the ConfigFactory - * @since 1.0.5 - */ - Properties getProperties(); - - /** - * Those properties will be used to expand variables specified in the `@Source` annotation, or by the ConfigFactory - * to configure its own behavior. - * - * @param properties the properties to set in the config Factory. - * @since 1.0.5 - */ - void setProperties(Properties properties); - - /** - * Registers a loader to enables additional file formats. - * - * @param loader the loader to register. - * @throws NullPointerException if specified loader is null. - * @since 1.0.5 - */ - void registerLoader(Loader loader); - - /** - * Sets a converter for the given type. Setting a converter via this method will override any default converters - * but not {@link Config.ConverterClass} annotations. - * - * @param type the type for which to set a converter. - * @param converter the converter class to use for the specified type. - * @since 1.0.10 - */ - void setTypeConverter(Class type, Class> converter); - - /** - * Removes a converter for the given type. - * @param type the type for which to remove the converter. - * @since 1.0.10 - */ - void removeTypeConverter(Class type); -} diff --git a/owner/src/main/java/org/aeonbits/owner/HotReloadLogic.java b/owner/src/main/java/org/aeonbits/owner/HotReloadLogic.java deleted file mode 100644 index 4e5aedb56..000000000 --- a/owner/src/main/java/org/aeonbits/owner/HotReloadLogic.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.HotReload; -import org.aeonbits.owner.Config.HotReloadType; - -import java.io.File; -import java.io.Serializable; -import java.net.URI; -import java.util.*; - -import static org.aeonbits.owner.Config.HotReloadType.ASYNC; -import static org.aeonbits.owner.Config.HotReloadType.SYNC; -import static org.aeonbits.owner.util.Util.fileFromURI; -import static org.aeonbits.owner.util.Util.now; -import static org.aeonbits.owner.util.Util.system; - -/** - * @author Luigi R. Viggiano - */ -class HotReloadLogic implements Serializable { - - private final PropertiesManager manager; - private final long interval; - private final HotReloadType type; - private volatile long lastCheckTime = now(); - private final List watchableResources = new ArrayList(); - - private interface WatchableResource extends Serializable { - boolean isChanged(); - } - - private static class WatchableFile implements WatchableResource { - private final File file; - private long lastModifiedTime; - - WatchableFile(File file) { - this.file = file; - this.lastModifiedTime = file.lastModified(); - } - - public boolean isChanged() { - long lastModifiedTimeNow = file.lastModified(); - boolean changed = lastModifiedTime != lastModifiedTimeNow; - if (changed) - lastModifiedTime = lastModifiedTimeNow; - return changed; - } - } - - private static class WatchableSystemProperties implements WatchableResource { - private final Properties props; - private int lastHashCode; - - - WatchableSystemProperties() { - props = system().getProperties(); - lastHashCode = props.hashCode(); - } - - public boolean isChanged() { - int newHashCode = props.hashCode(); - boolean changed = lastHashCode != newHashCode; - if (changed) - lastHashCode = newHashCode; - return changed; - } - } - - HotReloadLogic(HotReload hotReload, List uris, PropertiesManager manager) { - this.manager = manager; - type = hotReload.type(); - interval = hotReload.unit().toMillis(hotReload.value()); - setupWatchableResources(uris); - } - - private void setupWatchableResources(List uris) { - Set files = new LinkedHashSet(); - for (URI uri : uris) { - if (uri.toString().equals("system:properties")) { - watchableResources.add(new WatchableSystemProperties()); - } else { - File file = fileFromURI(uri); - if (file != null) - files.add(file); - } - } - for (File file : files) - watchableResources.add(new WatchableFile(file)); - } - - synchronized void checkAndReload() { - if (needsReload()) - manager.reload(); - } - - private boolean needsReload() { - if (manager.isLoading()) return false; - - long now = now(); - if (now < lastCheckTime + interval) - return false; - - try { - for (WatchableResource resource : watchableResources) - if (resource.isChanged()) - return true; - return false; - } finally { - lastCheckTime = now; - } - } - - boolean isAsync() { - return type == ASYNC; - } - - boolean isSync() { - return type == SYNC; - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/JMXSupport.java b/owner/src/main/java/org/aeonbits/owner/JMXSupport.java deleted file mode 100644 index 5dbe9c63c..000000000 --- a/owner/src/main/java/org/aeonbits/owner/JMXSupport.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import javax.management.Attribute; -import javax.management.AttributeList; -import javax.management.AttributeNotFoundException; -import javax.management.InvalidAttributeValueException; -import javax.management.MBeanAttributeInfo; -import javax.management.MBeanException; -import javax.management.MBeanInfo; -import javax.management.MBeanOperationInfo; -import javax.management.MBeanParameterInfo; -import javax.management.ReflectionException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * @author Robin Meißner - * @author Luigi R. Viggiano - */ -class JMXSupport implements Serializable { - - private final Class clazz; - private final PropertiesManager manager; - - public JMXSupport(Class clazz, PropertiesManager manager) { - this.clazz = clazz; - this.manager = manager; - } - - @Delegate - public Object getAttribute(String attribute) - throws AttributeNotFoundException, MBeanException, - ReflectionException { - return manager.getProperty(attribute); - } - - @Delegate - public void setAttribute(Attribute attribute) - throws AttributeNotFoundException, InvalidAttributeValueException, - MBeanException, ReflectionException { - manager.setProperty(attribute.getName(), (String) attribute.getValue()); - } - - @Delegate - public AttributeList getAttributes(String[] attributes) { - List attrList = new LinkedList(); - for (String propertyName : attributes) - attrList.add(new Attribute(propertyName, manager.getProperty(propertyName))); - return new AttributeList(attrList); - } - - @Delegate - public AttributeList setAttributes(AttributeList attributes) { - for (Attribute attr : attributes.asList()) - manager.setProperty(attr.getName(), (String) attr.getValue()); - return attributes; - } - - @Delegate - public Object invoke(String actionName, Object[] params, String[] signature) - throws MBeanException, ReflectionException { - if (actionName.equals("getProperty") && params != null && params.length == 1) { - return manager.getProperty((String) params[0]); - } else if (actionName.equals("setProperty") && params != null && params.length == 2) { - manager.setProperty((String) params[0], (String) params[1]); - return null; - } else if (actionName.equals("reload") && (params == null || params.length == 0)) { - manager.reload(); - return null; - } - throw new ReflectionException(new NoSuchMethodException(actionName)); - } - - @Delegate - public MBeanInfo getMBeanInfo() { - List attributesInfo = new ArrayList(); - Set propertyNames = manager.propertyNames(); - for (String name : propertyNames) - attributesInfo.add(new MBeanAttributeInfo(name, "java.lang.String", name, true, true, false)); - - MBeanAttributeInfo[] attributes = attributesInfo.toArray(new MBeanAttributeInfo[propertyNames.size()]); - - MBeanParameterInfo key = new MBeanParameterInfo("key", "java.lang.String", "Key of the property"); - MBeanParameterInfo value = new MBeanParameterInfo("value", "java.lang.String", "Value of the property"); - - MBeanOperationInfo[] operations = new MBeanOperationInfo[] { - new MBeanOperationInfo("getProperty", "Gets value for a property", - new MBeanParameterInfo[] { key }, "java.lang.String", MBeanOperationInfo.INFO), - new MBeanOperationInfo("setProperty", "Sets the value for a property", - new MBeanParameterInfo[] { key, value }, "void", MBeanOperationInfo.ACTION), - new MBeanOperationInfo("reload", "Reload properties", null, "void", MBeanOperationInfo.ACTION) - }; - - return new MBeanInfo(clazz.getName(), clazz.getSimpleName() + " OWNER MBean", - attributes, null, operations, null); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/LoadersManager.java b/owner/src/main/java/org/aeonbits/owner/LoadersManager.java deleted file mode 100644 index 30bc034cb..000000000 --- a/owner/src/main/java/org/aeonbits/owner/LoadersManager.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.loaders.*; - -import java.io.IOException; -import java.io.Serializable; -import java.net.URI; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import static org.aeonbits.owner.util.Util.unsupported; - - -/** - * This class is responsible of locating an appropriate Loader for a given URL (based the extension in the resource - * name)and load the properties from it. - * - * @author Luigi R. Viggiano - * @since 1.0.5 - */ -class LoadersManager implements Serializable { - - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - private final List loaders = new LinkedList(); - - LoadersManager() { - registerLoader(new PropertiesLoader()); - registerLoader(new XMLLoader()); - registerLoader(new SystemLoader()); - registerLoader(new PhileasSystemLoader()); - } - - void load(Properties result, URI uri) throws IOException { - Loader loader = findLoader(uri); - loader.load(result, uri); - } - - Loader findLoader(URI uri) { - lock.readLock().lock(); - try { - for (Loader loader : loaders) - if (loader.accept(uri)) - return loader; - throw unsupported("Can't resolve a Loader for the URL %s.", uri.toString()); - } finally { - lock.readLock().unlock(); - } - } - - final void registerLoader(Loader loader) { - if (loader == null) - throw new IllegalArgumentException("loader can't be null"); - lock.writeLock().lock(); - try { - loaders.add(0, loader); - } finally { - lock.writeLock().unlock(); - } - } - - void clear() { - lock.writeLock().lock(); - try { - loaders.clear(); - } finally { - lock.writeLock().unlock(); - } - } - - String[] defaultSpecs(String prefix) { - lock.readLock().lock(); - try { - List defaultSpecs = new ArrayList(loaders.size()); - for (Loader loader : loaders) { - String spec = loader.defaultSpecFor(prefix); - if (spec != null) - defaultSpecs.add(spec); - } - return defaultSpecs.toArray(new String[0]); - } finally { - lock.readLock().unlock(); - } - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/Mutable.java b/owner/src/main/java/org/aeonbits/owner/Mutable.java deleted file mode 100644 index 06a0fb1bd..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Mutable.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.beans.PropertyChangeListener; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; - -/** - *

Allows a Config object to change its property values at runtime.

- *

Example:

- *
- *     public interface MyConfig extends Config, Mutable {
- *         @DefaultValue("18")
- *         int minAge();
- *     }
- *
- *     public void example() {
- *         MyConfig cfg = ConfigFactory.create(MyConfig.class);
- *         int before = cfg.minAge();                 // before = 18
- *         int old = cfg.setProperty("minAge", "21"); // old = 18
- *         int after = cfg.minAge();                  // after = 21
- *         int old2 = cfg.removeProperty("minAge");   // old2 = 21
- *         int end = cfg.minAge();                    // end = null
- *     }
- * 
- * - * @author Luigi R. Viggiano - * @since 1.0.4 - */ -public interface Mutable extends Config { - - /** - *

Sets a given property to the specified value.

- *

Differently than {@link - * java.util.Properties#setProperty(String, String)}, if key is set to null then this call is - * equivalent to {@link #removeProperty(String)}.

- * - * @param key the key to be placed into the property list. - * @param value the value corresponding to key, or null if the property must be removed. - * @return the previous value of the specified key, or null if it did not have one. - * @since 1.0.4 - */ - String setProperty(String key, String value); - - /** - * Removes a given property. - * - * @param key the key of the property to remove. - * @return the previous value of the specified key, or null if it did not have one. - * @see java.util.Hashtable#remove(Object) - * @since 1.0.4 - */ - String removeProperty(String key); - - /** - * Clears all properties. - * - * @since 1.0.4 - */ - void clear(); - - /** - * Reads a property list (key and element pairs) from the input byte stream. - * - * @param inStream the input stream. - * @throws java.io.IOException if an error occurred when reading from the input stream. - * @throws IllegalArgumentException if the input stream contains a malformed Unicode escape sequence. - * @see java.util.Properties#load(java.io.InputStream) - * @since 1.0.4 - */ - void load(InputStream inStream) throws IOException; - - /** - * Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format. - * - * @param reader the input character stream. - * @throws IOException if an error occurred when reading from the input stream. - * @throws IllegalArgumentException if a malformed Unicode escape appears in the input. - * @see java.util.Properties#load(java.io.Reader) - * @since 1.0.4 - */ - void load(Reader reader) throws IOException; - - /** - * Adds a {@link PropertyChangeListener} to the Mutable interface. - * - * @param listener the listener to be added. - * @since 1.0.5 - */ - void addPropertyChangeListener(PropertyChangeListener listener); - - /** - * Removes a {@link PropertyChangeListener} from the Mutable interface. - * - * @param listener the property change listener to be removed - */ - void removePropertyChangeListener(PropertyChangeListener listener); - - /** - * Adds a PropertyChangeListener to the listener list for a specific - * property. - * If propertyName or listener is null, - * no exception is thrown and no action is taken. - * - * @param propertyName one of the property names listed above - * @param listener the property change listener to be added - */ - void addPropertyChangeListener(String propertyName, PropertyChangeListener listener); - -} diff --git a/owner/src/main/java/org/aeonbits/owner/Preprocessor.java b/owner/src/main/java/org/aeonbits/owner/Preprocessor.java deleted file mode 100644 index 043c31632..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Preprocessor.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -/** - * Preprocessor interface specifies how to pre-process an input string coming from a property value before being used by - * OWNER. - * - * @author Luigi R. Viggiano - * @since 1.0.9 - */ -public interface Preprocessor { - String process(String input); -} diff --git a/owner/src/main/java/org/aeonbits/owner/PreprocessorResolver.java b/owner/src/main/java/org/aeonbits/owner/PreprocessorResolver.java deleted file mode 100644 index 93a207f28..000000000 --- a/owner/src/main/java/org/aeonbits/owner/PreprocessorResolver.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.PreprocessorClasses; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import static java.util.Collections.emptyList; -import static org.aeonbits.owner.util.Util.newInstance; - -/** - * @author Luigi R. Viggiano - */ -final class PreprocessorResolver { - - /** - * Don't let anyone instantiate this class - */ - private PreprocessorResolver() { - } - - public static List resolvePreprocessors(Method method) { - List result = new ArrayList(); - List preprocessorsOnMethod = getPreprocessor(method.getAnnotation(PreprocessorClasses.class)); - result.addAll(preprocessorsOnMethod); - - List preprocessorsOnClass = getPreprocessor(method.getDeclaringClass() - .getAnnotation(PreprocessorClasses.class)); - result.addAll(preprocessorsOnClass); - - return result; - } - - private static List getPreprocessor(PreprocessorClasses preprocessorClassesAnnotation) { - if (preprocessorClassesAnnotation == null) return emptyList(); - Class[] preprocessorClasses = preprocessorClassesAnnotation.value(); - if (preprocessorClasses == null) return emptyList(); - List result = new LinkedList(); - return newInstance(preprocessorClassesAnnotation.value(), result); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/PropertiesInvocationHandler.java b/owner/src/main/java/org/aeonbits/owner/PropertiesInvocationHandler.java deleted file mode 100644 index fd3355d8e..000000000 --- a/owner/src/main/java/org/aeonbits/owner/PropertiesInvocationHandler.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.util.LinkedList; -import java.util.List; - -import static org.aeonbits.owner.Config.DisableableFeature.PARAMETER_FORMATTING; -import static org.aeonbits.owner.Config.DisableableFeature.VARIABLE_EXPANSION; -import static org.aeonbits.owner.Converters.SpecialValue.NULL; -import static org.aeonbits.owner.Converters.convert; -import static org.aeonbits.owner.PreprocessorResolver.resolvePreprocessors; -import static org.aeonbits.owner.PropertiesMapper.key; -import static org.aeonbits.owner.util.Util.isFeatureDisabled; -import static org.aeonbits.owner.util.Reflection.invokeDefaultMethod; -import static org.aeonbits.owner.util.Reflection.isDefault; - -/** - * This {@link InvocationHandler} receives method calls from the delegate instantiated by {@link ConfigFactory} and maps - * it to a property value from a property file, or a {@link Config.DefaultValue} specified in method annotation. - *

- * The {@link Config.Key} annotation can be used to override default mapping between method names and property names. - *

- *

- * Automatic conversion is handled between the property value and the return type expected by the method of the - * delegate. - *

- * - * @author Luigi R. Viggiano - */ -class PropertiesInvocationHandler implements InvocationHandler, Serializable { - - private static final long serialVersionUID = 5432212884255718342L; - private transient List delegates; - private final Object jmxSupport; - private final StrSubstitutor substitutor; - final PropertiesManager propertiesManager; - - - PropertiesInvocationHandler(PropertiesManager manager, Object jmxSupport) { - this.propertiesManager = manager; - this.jmxSupport = jmxSupport; - delegates = findDelegates(manager, jmxSupport); - this.substitutor = new StrSubstitutor(manager.load()); - } - - public Object invoke(Object proxy, Method invokedMethod, Object... args) throws Throwable { - propertiesManager.syncReloadCheck(); - - if (isDefault(invokedMethod)) - return invokeDefaultMethod(proxy, invokedMethod, args); - - DelegateMethodHandle delegate = getDelegateMethod(invokedMethod); - if (delegate != null) - return delegate.invoke(args); - - return resolveProperty(invokedMethod, args); - } - - private DelegateMethodHandle getDelegateMethod(Method invokedMethod) { - for (DelegateMethodHandle delegate : delegates) - if (delegate.matches(invokedMethod)) - return delegate; - return null; - } - - private Object resolveProperty(Method method, Object... args) { - String key = expandKey(method, args); - String value = propertiesManager.getProperty(key); - - // TODO: this if should go away! See #84 and #86 - if (value == null && !isFeatureDisabled(method, VARIABLE_EXPANSION)) { - String unexpandedKey = key(method); - value = propertiesManager.getProperty(unexpandedKey); - } - if (value == null) - return null; - value = preProcess(method, value); - Object result = convert(method, method.getReturnType(), - format(method, propertiesManager - .decryptIfNecessary(method, expandVariables(method, value)), - args)); - if (result == NULL) return null; - return result; - } - - private String preProcess(Method method, String value) { - List preprocessors = resolvePreprocessors(method); - String result = value; - for (Preprocessor preprocessor : preprocessors) - result = preprocessor.process(result); - return result; - } - - private String expandKey(Method method, Object... args) { - String key = key(method); - if (isFeatureDisabled(method, VARIABLE_EXPANSION)) - return key; - return substitutor.replace(key, args); - } - - private String format(Method method, String format, Object... args) { - if (isFeatureDisabled(method, PARAMETER_FORMATTING)) - return format; - - // If there are no arguments to format, we can just return. - // This is also helpful when the {@code format} is a property value that contains a '%' character, - // such as '@#$%^&*()" (e.g., a clear-text password). In such cases, the '%' character is not - // a placeholder in a format string -- its just a random character in the property value. - if ( args == null || args.length == 0 ) - return format; - - try { - // Do this to achieve property expansion - return String.format(format, args); - } - catch ( Exception e ) { - // There's no guarantee that a property value from a config file - // is a legal format string. When formatting doesn't work, let's - // just return the original property value. - return format; - } - } - - private String expandVariables(Method method, String value) { - if (isFeatureDisabled(method, VARIABLE_EXPANSION)) - return value; - return substitutor.replace(value); - } - - private List findDelegates(Object... targets) { - List result = new LinkedList(); - for (Object target : targets) { - if (target == null) - continue; - Method[] methods = target.getClass().getMethods(); - for (Method m : methods) - if (m.getAnnotation(Delegate.class) != null) - result.add(new DelegateMethodHandle(target, m)); - } - return result; - } - - public void setProxy(T proxy) { - propertiesManager.setProxy(proxy); - } - - private void readObject(java.io.ObjectInputStream in) - throws IOException, ClassNotFoundException { - in.defaultReadObject(); - delegates = findDelegates(propertiesManager, jmxSupport); - } -} diff --git a/owner/src/main/java/org/aeonbits/owner/PropertiesManager.java b/owner/src/main/java/org/aeonbits/owner/PropertiesManager.java deleted file mode 100644 index 813bd76dc..000000000 --- a/owner/src/main/java/org/aeonbits/owner/PropertiesManager.java +++ /dev/null @@ -1,634 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.crypto.Decryptor; -import org.aeonbits.owner.crypto.IdentityDecryptor; -import org.aeonbits.owner.event.*; -import org.aeonbits.owner.util.Util; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.*; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; -import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; - -import static java.util.Collections.synchronizedList; -import static org.aeonbits.owner.Config.LoadType.FIRST; -import static org.aeonbits.owner.PropertiesMapper.defaults; -import static org.aeonbits.owner.util.Util.*; - -/** - * Loads properties and manages access to properties handling concurrency. - * - * @author Luigi R. Viggiano - */ -class PropertiesManager implements Reloadable, Accessible, Mutable { - private final Class clazz; - private final Map[] imports; - private final Properties properties; - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - private final ReadLock readLock = lock.readLock(); - private final WriteLock writeLock = lock.writeLock(); - - private final LoadType loadType; - private final List uris; - private final HotReloadLogic hotReloadLogic; - - private volatile boolean loading = false; - - final List reloadListeners = synchronizedList(new LinkedList()); - - private Object proxy; - private final LoadersManager loaders; - - - /** - * A cache of encryptedKeys with its decryptor. - *

- * This allows each key has its own decryptor. - * Reflection is slow. - */ - private Map encryptedKeys = new HashMap(); - - final List propertyChangeListeners = synchronizedList( - new LinkedList() { - @Override - public boolean remove(Object o) { - Iterator iterator = iterator(); - while (iterator.hasNext()) { - Object item = iterator.next(); - if (item.equals(o)) { - iterator.remove(); - return true; - } - } - return false; - } - }); - - PropertiesManager(Class clazz, Properties properties, ScheduledExecutorService scheduler, - VariablesExpander expander, LoadersManager loaders, Map... imports) { - this.clazz = clazz; - this.properties = properties; - this.loaders = loaders; - this.imports = imports; - ConfigURIFactory urlFactory = new ConfigURIFactory(clazz.getClassLoader(), expander); - uris = toURIs(clazz.getAnnotation(Sources.class), urlFactory); - - for (Class inter : clazz.getInterfaces()) { - this.uris.addAll(toURIs(inter.getAnnotation(Sources.class), urlFactory)); - } - - LoadPolicy loadPolicy = clazz.getAnnotation(LoadPolicy.class); - if (loadPolicy == null) { - for (Class inter : clazz.getInterfaces()) { - loadPolicy = inter.getAnnotation(LoadPolicy.class); - if (loadPolicy != null) { - break; - } - } - } - loadType = (loadPolicy != null) ? loadPolicy.value() : FIRST; - - HotReload hotReload = clazz.getAnnotation(HotReload.class); - if (hotReload == null) { - for (Class inter : clazz.getInterfaces()) { - hotReload = inter.getAnnotation(HotReload.class); - if (hotReload != null) { - break; - } - } - } - if (hotReload != null) { - hotReloadLogic = new HotReloadLogic(hotReload, uris, this); - - if (hotReloadLogic.isAsync()) - scheduler.scheduleAtFixedRate(new Runnable() { - public void run() { - hotReloadLogic.checkAndReload(); - } - }, hotReload.value(), hotReload.value(), hotReload.unit()); - } else { - hotReloadLogic = null; - } - - // We try to identify the DecryptorClass annotation, to assign the Decryptor to this configuration. - // If it isn't present then we assign the IdentityDecryptor. - DecryptorClass decryptorManager = clazz.getAnnotation(DecryptorClass.class); - Class decryptorClazz; - if (decryptorManager != null) { - decryptorClazz = decryptorManager.value(); - } else { - decryptorClazz = IdentityDecryptor.class; - } - Decryptor classDecryptor = Util.newInstance(decryptorClazz); - - // Reflection is slow, so we will cache all methods with EncryptedValue annotation. - Method[] methods = clazz.getMethods(); - for (Method method : methods) { - if (PropertiesMapper.isEncryptedValue(method)) { - EncryptedValue encriptedKey = method.getAnnotation(EncryptedValue.class); - decryptorClazz = encriptedKey.value(); - if (decryptorClazz != IdentityDecryptor.class) { - encryptedKeys.put(method, Util.newInstance(decryptorClazz)); - } else { - encryptedKeys.put(method, classDecryptor); - } - } - } - } - - /** - * If method contains the EncryptedValue annotation it Decrypts the value with the associated {@link Decryptor}. - * - * @param method with the key definition. - * @param value the value to decrypt when the method contains the EncryptedValue annotation - * @return - * the value if the method doesn't contains the EncryptedValue annotation - * or the result of decrypt the value if it does. - */ - String decryptIfNecessary(Method method, String value) { - // Value can't be null, it has been checked previously in PropertiesInvocationHandler.resolveProperty - if (this.encryptedKeys.containsKey(method)) { - Decryptor decryptor = this.encryptedKeys.get(method); - return decryptor.decrypt(value); - } - return value; - } - - private List toURIs(Sources sources, ConfigURIFactory uriFactory) { - String[] specs = specs(sources, uriFactory); - List result = new ArrayList(); - for (String spec : specs) { - try { - URI uri = uriFactory.newURI(spec); - if (uri != null) - result.add(uri); - } catch (URISyntaxException e) { - throw unsupported(e, "Can't convert '%s' to a valid URI", spec); - } - } - return result; - } - - private String[] specs(Sources sources, ConfigURIFactory uriFactory) { - if (sources != null) return sources.value(); - return defaultSpecs(uriFactory); - } - - private String[] defaultSpecs(ConfigURIFactory uriFactory) { - String prefix = uriFactory.toClasspathURLSpec(clazz.getName()); - return loaders.defaultSpecs(prefix); - } - - Properties load() { - writeLock.lock(); - try { - return load(properties); - } finally { - writeLock.unlock(); - } - } - - private Properties load(Properties props) { - try { - loading = true; - defaults(props, clazz); - Properties loadedFromFile = doLoad(); - merge(props, loadedFromFile); - merge(props, reverse(imports)); - return props; - } finally { - loading = false; - } - } - - @Delegate - public void reload() { - writeLock.lock(); - try { - Properties loaded = load(new Properties()); - List events = - fireBeforePropertyChangeEvents(keys(properties, loaded), properties, loaded); - ReloadEvent reloadEvent = fireBeforeReloadEvent(events, properties, loaded); - applyPropertyChangeEvents(events); - firePropertyChangeEvents(events); - fireReloadEvent(reloadEvent); - } catch (RollbackBatchException e) { - ignore(); - } finally { - writeLock.unlock(); - } - } - - private Set keys(Map... maps) { - Set keys = new HashSet(); - for (Map map : maps) - keys.addAll(map.keySet()); - return keys; - } - - private void applyPropertyChangeEvents(List events) { - for (PropertyChangeEvent event : events) - performSetProperty(event.getPropertyName(), event.getNewValue()); - } - - private void fireReloadEvent(ReloadEvent reloadEvent) { - for (ReloadListener listener : reloadListeners) - listener.reloadPerformed(reloadEvent); - } - - private ReloadEvent fireBeforeReloadEvent(List events, Properties oldProperties, - Properties newProperties) throws RollbackBatchException { - ReloadEvent reloadEvent = new ReloadEvent(proxy, events, oldProperties, newProperties); - for (ReloadListener listener : reloadListeners) - if (listener instanceof TransactionalReloadListener) - ((TransactionalReloadListener) listener).beforeReload(reloadEvent); - return reloadEvent; - } - - - @Delegate - public void addReloadListener(ReloadListener listener) { - if (listener != null) - reloadListeners.add(listener); - } - - @Delegate - public void removeReloadListener(ReloadListener listener) { - if (listener != null) - reloadListeners.remove(listener); - } - - @Delegate - public void addPropertyChangeListener(PropertyChangeListener listener) { - if (listener != null) - propertyChangeListeners.add(listener); - } - - @Delegate - public void removePropertyChangeListener(PropertyChangeListener listener) { - if (listener != null) - propertyChangeListeners.remove(listener); - } - - @Delegate - public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { - if (propertyName == null || listener == null) return; - - final boolean transactional = listener instanceof TransactionalPropertyChangeListener; - propertyChangeListeners.add(new PropertyChangeListenerWrapper(propertyName, listener, transactional)); - } - - private static class PropertyChangeListenerWrapper implements TransactionalPropertyChangeListener, Serializable { - - private final String propertyName; - private final PropertyChangeListener listener; - private final boolean transactional; - - PropertyChangeListenerWrapper(String propertyName, PropertyChangeListener listener, - boolean transactional) { - this.propertyName = propertyName; - this.listener = listener; - this.transactional = transactional; - - } - - public void beforePropertyChange(PropertyChangeEvent event) throws RollbackOperationException, - RollbackBatchException { - if (transactional && propertyNameMatches(event)) - ((TransactionalPropertyChangeListener) listener).beforePropertyChange(event); - } - - private boolean propertyNameMatches(PropertyChangeEvent event) { - return propertyName.equals(event.getPropertyName()); - } - - public void propertyChange(PropertyChangeEvent event) { - if (propertyNameMatches(event)) - listener.propertyChange(event); - } - - @Override - public boolean equals(Object obj) { - return listener.equals(obj); - } - - @Override - public int hashCode() { - return listener.hashCode(); - } - } - - private Properties doLoad() { - return loadType.load(uris, loaders); - } - - private static void merge(Properties results, Map... inputs) { - for (Map input : inputs) - results.putAll(input); - } - - @Delegate - public String getProperty(String key) { - readLock.lock(); - try { - return properties.getProperty(key); - } finally { - readLock.unlock(); - } - } - - void syncReloadCheck() { - if (hotReloadLogic != null && hotReloadLogic.isSync()) - hotReloadLogic.checkAndReload(); - } - - @Delegate - public String getProperty(String key, String defaultValue) { - readLock.lock(); - try { - return properties.getProperty(key, defaultValue); - } finally { - readLock.unlock(); - } - } - - @Delegate - public void storeToXML(OutputStream os, String comment) throws IOException { - readLock.lock(); - try { - properties.storeToXML(os, comment); - } finally { - readLock.unlock(); - } - } - - @Delegate - public Set propertyNames() { - readLock.lock(); - try { - LinkedHashSet result = new LinkedHashSet(); - for (Enumeration propertyNames = properties.propertyNames(); propertyNames.hasMoreElements(); ) - result.add((String) propertyNames.nextElement()); - return result; - } finally { - readLock.unlock(); - } - } - - @Delegate - public void list(PrintStream out) { - readLock.lock(); - try { - properties.list(out); - } finally { - readLock.unlock(); - } - } - - @Delegate - public void list(PrintWriter out) { - readLock.lock(); - try { - properties.list(out); - } finally { - readLock.unlock(); - } - } - - @Delegate - public void store(OutputStream out, String comments) throws IOException { - readLock.lock(); - try { - properties.store(out, comments); - } finally { - readLock.unlock(); - } - } - - @Delegate - @SuppressWarnings("unchecked") - public void fill(Map map) { - readLock.lock(); - try { - for (String propertyName : propertyNames()) - map.put(propertyName, getProperty(propertyName)); - } finally { - readLock.unlock(); - } - } - - @Delegate - public String setProperty(String key, String newValue) { - writeLock.lock(); - try { - String oldValue = properties.getProperty(key); - try { - if (eq(oldValue, newValue)) return oldValue; - - PropertyChangeEvent event = new PropertyChangeEvent(proxy, key, oldValue, newValue); - fireBeforePropertyChange(event); - String result = performSetProperty(key, newValue); - firePropertyChange(event); - return result; - } catch (RollbackException e) { - return oldValue; - } - } finally { - writeLock.unlock(); - } - } - - private String performSetProperty(String key, Object value) { - return (value == null) ? - performRemoveProperty(key) : - asString(properties.setProperty(key, asString(value))); - } - - @Delegate - public String removeProperty(String key) { - writeLock.lock(); - try { - String oldValue = properties.getProperty(key); - PropertyChangeEvent event = new PropertyChangeEvent(proxy, key, oldValue, null); - fireBeforePropertyChange(event); - String result = performRemoveProperty(key); - firePropertyChange(event); - return result; - } catch (RollbackException e) { - return properties.getProperty(key); - } finally { - writeLock.unlock(); - } - } - - private String performRemoveProperty(String key) { - return asString(properties.remove(key)); - } - - @Delegate - public void clear() { - writeLock.lock(); - try { - List events = - fireBeforePropertyChangeEvents(keys(properties), properties, new Properties()); - applyPropertyChangeEvents(events); - firePropertyChangeEvents(events); - } catch (RollbackBatchException e) { - ignore(); - } finally { - writeLock.unlock(); - } - } - - @Delegate - public void load(InputStream inStream) throws IOException { - writeLock.lock(); - try { - Properties loaded = new Properties(); - loaded.load(inStream); - performLoad(keys(loaded), loaded); - } catch (RollbackBatchException ex) { - ignore(); - } finally { - writeLock.unlock(); - } - } - - private void performLoad(Set keys, Properties props) throws RollbackBatchException { - List events = fireBeforePropertyChangeEvents(keys, properties, props); - applyPropertyChangeEvents(events); - firePropertyChangeEvents(events); - } - - @Delegate - public void load(Reader reader) throws IOException { - writeLock.lock(); - try { - Properties loaded = new Properties(); - loaded.load(reader); - performLoad(keys(loaded), loaded); - } catch (RollbackBatchException ex) { - ignore(); - } finally { - writeLock.unlock(); - } - } - - void setProxy(Object proxy) { - this.proxy = proxy; - } - - @Delegate - @Override - public String toString() { - readLock.lock(); - try { - return properties.toString(); - } finally { - readLock.unlock(); - } - } - - boolean isLoading() { - return loading; - } - - private List fireBeforePropertyChangeEvents( - Set keys, Properties oldValues, Properties newValues) throws RollbackBatchException { - List events = new ArrayList(); - for (Object keyObject : keys) { - String key = (String) keyObject; - String oldValue = oldValues.getProperty(key); - String newValue = newValues.getProperty(key); - if (!eq(oldValue, newValue)) { - PropertyChangeEvent event = - new PropertyChangeEvent(proxy, key, oldValue, newValue); - try { - fireBeforePropertyChange(event); - events.add(event); - } catch (RollbackOperationException e) { - ignore(); - } - } - } - return events; - } - - private void firePropertyChangeEvents(List events) { - for (PropertyChangeEvent event : events) - firePropertyChange(event); - } - - private void fireBeforePropertyChange(PropertyChangeEvent event) throws RollbackBatchException, - RollbackOperationException { - for (PropertyChangeListener listener : propertyChangeListeners) - if (listener instanceof TransactionalPropertyChangeListener) - ((TransactionalPropertyChangeListener) listener).beforePropertyChange(event); - } - - private void firePropertyChange(PropertyChangeEvent event) { - for (PropertyChangeListener listener : propertyChangeListeners) - listener.propertyChange(event); - } - - @Delegate - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Proxy)) return false; - InvocationHandler handler = Proxy.getInvocationHandler(obj); - if (!(handler instanceof PropertiesInvocationHandler)) - return false; - PropertiesInvocationHandler propsInvocationHandler = (PropertiesInvocationHandler) handler; - PropertiesManager that = propsInvocationHandler.propertiesManager; - return this.equals(that); - } - - private boolean equals(PropertiesManager that) { - if (!this.isAssignationCompatibleWith(that)) - return false; - this.readLock.lock(); - try { - that.readLock.lock(); - try { - return this.properties.equals(that.properties); - } finally { - that.readLock.unlock(); - } - } finally { - this.readLock.unlock(); - } - } - - private boolean isAssignationCompatibleWith(PropertiesManager that) { - return this.clazz.isAssignableFrom(that.clazz) || that.clazz.isAssignableFrom(this.clazz); - } - - @Delegate - @Override - public int hashCode() { - readLock.lock(); - try { - return properties.hashCode(); - } finally { - readLock.unlock(); - } - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/PropertiesMapper.java b/owner/src/main/java/org/aeonbits/owner/PropertiesMapper.java deleted file mode 100644 index 5799d2ce6..000000000 --- a/owner/src/main/java/org/aeonbits/owner/PropertiesMapper.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.DefaultValue; -import org.aeonbits.owner.Config.EncryptedValue; -import org.aeonbits.owner.Config.Key; - -import java.lang.reflect.Method; -import java.util.Properties; - -/** - * Maps methods to properties keys and defaultValues. Maps a class to default property values. - * - * @author Luigi R. Viggiano - */ -final class PropertiesMapper { - - /** Don't let anyone instantiate this class */ - private PropertiesMapper() {} - - static boolean isEncryptedValue( Method method ) { - return ( method.getAnnotation( EncryptedValue.class ) ) != null; - } - - static String key(Method method) { - Key key = method.getAnnotation(Key.class); - return (key == null) ? method.getName() : key.value(); - } - - static String defaultValue(Method method) { - DefaultValue defaultValue = method.getAnnotation(DefaultValue.class); - return defaultValue != null ? defaultValue.value() : null; - } - - static void defaults(Properties properties, Class clazz) { - Method[] methods = clazz.getMethods(); - for (Method method : methods) { - String key = key(method); - String value = defaultValue(method); - if (value != null) - properties.put(key, value); - } - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/Reloadable.java b/owner/src/main/java/org/aeonbits/owner/Reloadable.java deleted file mode 100644 index e82e1704f..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Reloadable.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.event.ReloadListener; - -/** - *

Allows a Config object to implement the reloading of the properties at runtime.

- * - *

Example:

- * - *
- *     public interface MyConfig extends Config, Reloadable {
- *         int someProperty();
- *     }
- *
- *     public void doSomething() {
- *
- *         // loads the properties from the files for the first time.
- *         MyConfig cfg = ConfigFactory.create(MyConfig.class);
- *         int before = cfg.someProperty();
- *
- *         // after changing the local files...
- *         cfg.reload();
- *         int after = cfg.someProperty();
- *
- *         // before and after may differ now.
- *         if (before != after) { ... }
- *     }
- * 
- * - *

The reload method will reload the properties using the same sources used when it was instantiated the first time. - * This can be useful to programmatically reload the configuration after the configuration files were changed.

- * - * @author Luigi R. Viggiano - * @since 1.0.4 - */ -public interface Reloadable extends Config { - - /** - * Reloads the properties using the same logic as when the object was instantiated by {@link - * ConfigFactory#create(Class, java.util.Map[])}. - * - * @since 1.0.4 - */ - void reload(); - - /** - * Add a ReloadListener. - * @param listener the listener to be added - * - * @since 1.0.4 - */ - void addReloadListener(ReloadListener listener); - - /** - * Remove a ReloadListener. - * @param listener the listener to be removed - * - * @since 1.0.4 - */ - void removeReloadListener(ReloadListener listener); - -} diff --git a/owner/src/main/java/org/aeonbits/owner/SplitAndTrimTokenizer.java b/owner/src/main/java/org/aeonbits/owner/SplitAndTrimTokenizer.java deleted file mode 100644 index 1b28bf2c9..000000000 --- a/owner/src/main/java/org/aeonbits/owner/SplitAndTrimTokenizer.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -/** - * Tokenizer implementation based on {@link String#split(String, int)} and {@link String#trim()}. - * This class is used to implement tokenizers for the {@link Config.Separator} annotation. - * - * @since 1.0.4 - * @author Luigi R. Viggiano - */ -class SplitAndTrimTokenizer implements Tokenizer { - - private final String regex; - - public SplitAndTrimTokenizer(String regex) { - this.regex = regex; - } - - public String[] tokens(String values) { - String[] chunks = values.split(regex, -1); - for(int i = 0; i < chunks.length; i++) - chunks[i] = chunks[i].trim(); - return chunks; - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/StrSubstitutor.java b/owner/src/main/java/org/aeonbits/owner/StrSubstitutor.java deleted file mode 100644 index 78d6e8853..000000000 --- a/owner/src/main/java/org/aeonbits/owner/StrSubstitutor.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.io.Serializable; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static java.util.regex.Pattern.compile; - -/** - *

- * Substitutes variables within a string by values. - *

- *

- * This class takes a piece of text and substitutes all the variables within it. The definition of a variable is - * ${variableName}. - *

- *

- * Typical usage of this class follows the following pattern: First an instance is created and initialized with the - * values that contains the values for the available variables. If a prefix and/or suffix for variables should be used - * other than the default ones, the appropriate settings can be performed. After that the replace() method - * can be called passing in the source text for interpolation. In the returned text all variable references (as long as - * their values are known) will be resolved. The following example demonstrates this: - *

- *
- * Map valuesMap = new HashMap();
- * valuesMap.put("animal", "quick brown fox");
- * valuesMap.put("target", "lazy dog");
- * String templateString = "The ${animal} jumped over the ${target}.";
- * StrSubstitutor sub = new StrSubstitutor(valuesMap);
- * String resolvedString = sub.replace(templateString);
- * 
- * yielding: - *
- *      The quick brown fox jumped over the lazy dog.
- * 
- * - * @author Luigi R. Viggiano - */ -class StrSubstitutor implements Serializable { - - private final Properties values; - private static final Pattern PATTERN = compile("\\$\\{(.+?)\\}"); - - /** - * Creates a new instance and initializes it. Uses defaults for variable prefix and suffix and the escaping - * character. - * - * @param values the variables' values, may be null - */ - StrSubstitutor(Properties values) { - this.values = values; - } - - /** - * Replaces all the occurrences of variables with their matching values from the resolver using the given source - * string as a template. - * - * @param source the string to replace in, null returns null - * @return the result of the replace operation - */ - String replace(String source) { - if (source == null) - return null; - Matcher m = PATTERN.matcher(source); - StringBuffer sb = new StringBuffer(); - while (m.find()) { - String var = m.group(1); - String value = values.getProperty(var); - String replacement = (value != null) ? replace(value) : ""; - m.appendReplacement(sb, Matcher.quoteReplacement(replacement)); - } - m.appendTail(sb); - return sb.toString(); - } - - /** - * Returns a string modified in according to supplied source and arguments.
- * If the source string has pattern-replacement content like {@code "a.${var}.b"}, - * the pattern is replaced property value of "var".
- * Otherwise the return string is formatted by source and arguments as with {@link String#format(String, Object...)} - * - * @param source A source formatting format string. {@code null} returns {@code null} - * @param args Arguments referenced by the format specifiers in the source string. - * @return formatted string - */ - String replace(String source, Object... args) { - if (source == null) - return null; - Matcher m = PATTERN.matcher(source); - return m.find() ? replace(source) : String.format(source, args); - } -} diff --git a/owner/src/main/java/org/aeonbits/owner/Tokenizer.java b/owner/src/main/java/org/aeonbits/owner/Tokenizer.java deleted file mode 100644 index 0cd711dc4..000000000 --- a/owner/src/main/java/org/aeonbits/owner/Tokenizer.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -/** - * Tokenizer interface that specifies how to split a single value into tokens to be used as elements for arrays and - * collections. - * - * @author Luigi R. Viggiano - * @since 1.0.4 - */ -public interface Tokenizer { - - /** - * Splits the given string, into tokens that identify single elements. - * - * @since 1.0.4 - * @param values the string representation for the properties values - * @return the items identifying single elements to convert. - */ - String[] tokens(String values); - -} diff --git a/owner/src/main/java/org/aeonbits/owner/TokenizerResolver.java b/owner/src/main/java/org/aeonbits/owner/TokenizerResolver.java deleted file mode 100644 index b20d47427..000000000 --- a/owner/src/main/java/org/aeonbits/owner/TokenizerResolver.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.Separator; -import org.aeonbits.owner.Config.TokenizerClass; - -import java.lang.reflect.Method; - -import static org.aeonbits.owner.util.Util.newInstance; -import static org.aeonbits.owner.util.Util.unsupported; - -/** - * @author Luigi R. Viggiano - */ -final class TokenizerResolver { - - /** Don't let anyone instantiate this class */ - private TokenizerResolver() {} - - private static final Tokenizer DEFAULT_TOKENIZER = new SplitAndTrimTokenizer(","); - - static Tokenizer resolveTokenizer(Method targetMethod) { - Tokenizer methodLevelTokenizer = resolveTokenizerOnMethodLevel(targetMethod); - if (methodLevelTokenizer != null) - return methodLevelTokenizer; - - Tokenizer classLevelTokenizer = resolveTokenizerOnClassLevel(targetMethod.getDeclaringClass()); - if (classLevelTokenizer != null) - return classLevelTokenizer; - - return DEFAULT_TOKENIZER; - } - - private static Tokenizer resolveTokenizerOnClassLevel(Class declaringClass) { - Separator separatorAnnotationOnClassLevel = declaringClass.getAnnotation(Separator.class); - TokenizerClass tokenizerClassAnnotationOnClassLevel = declaringClass.getAnnotation(TokenizerClass.class); - - if (separatorAnnotationOnClassLevel != null && tokenizerClassAnnotationOnClassLevel != null) - throw unsupported( - "You cannot specify @Separator and @TokenizerClass both together on class level for '%s'", - declaringClass.getCanonicalName()); - - if (separatorAnnotationOnClassLevel != null) - return new SplitAndTrimTokenizer(separatorAnnotationOnClassLevel.value()); - - if (tokenizerClassAnnotationOnClassLevel != null) - return newInstance(tokenizerClassAnnotationOnClassLevel.value()); - - return null; - } - - private static Tokenizer resolveTokenizerOnMethodLevel(Method targetMethod) { - Separator separatorAnnotationOnMethodLevel = targetMethod.getAnnotation(Separator.class); - TokenizerClass tokenizerClassAnnotationOnMethodLevel = targetMethod.getAnnotation(TokenizerClass.class); - - if (separatorAnnotationOnMethodLevel != null && tokenizerClassAnnotationOnMethodLevel != null) - throw unsupported( - "You cannot specify @Separator and @TokenizerClass both together on method level for '%s'", - targetMethod); - - if (separatorAnnotationOnMethodLevel != null) - return new SplitAndTrimTokenizer(separatorAnnotationOnMethodLevel.value()); - - if (tokenizerClassAnnotationOnMethodLevel != null) - return newInstance(tokenizerClassAnnotationOnMethodLevel.value()); - - return null; - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/VariablesExpander.java b/owner/src/main/java/org/aeonbits/owner/VariablesExpander.java deleted file mode 100644 index e5294454e..000000000 --- a/owner/src/main/java/org/aeonbits/owner/VariablesExpander.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - - -import org.aeonbits.owner.util.Util; - -import java.io.Serializable; -import java.util.Properties; - -import static org.aeonbits.owner.util.Util.expandUserHome; - -/** - * This class is used to expand variables in the format ${variable}$, using values from - * {@link System#getenv()}, {@link System#getProperties()} and the Properties object specified in the - * constructor (in inverse order; first match is accepted). - * - * @author Luigi R. Viggiano - */ -class VariablesExpander implements Serializable { - - private final StrSubstitutor substitutor; - - VariablesExpander(Properties props) { - Properties variables = new Properties(); - variables.putAll(Util.system().getenv()); - variables.putAll(Util.system().getProperties()); - variables.putAll(props); - substitutor = new StrSubstitutor(variables); - } - - String expand(String path) { - String expanded = expandUserHome(path); - return substitutor.replace(expanded); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/crypto/AbstractDecryptor.java b/owner/src/main/java/org/aeonbits/owner/crypto/AbstractDecryptor.java deleted file mode 100644 index f55d3eadd..000000000 --- a/owner/src/main/java/org/aeonbits/owner/crypto/AbstractDecryptor.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.aeonbits.owner.crypto; - -/** - * An abstract implementation of Decryptor. - * It implements the decrypt( String, String ). - */ -public abstract class AbstractDecryptor -implements Decryptor { - @Override - public String decrypt( String value, String defaultValue ) { - try { - return this.decrypt( value ); - } catch ( IllegalArgumentException cause ) { - return defaultValue; - } - } -} diff --git a/owner/src/main/java/org/aeonbits/owner/crypto/AbstractEncryptor.java b/owner/src/main/java/org/aeonbits/owner/crypto/AbstractEncryptor.java deleted file mode 100644 index 2f6d7a882..000000000 --- a/owner/src/main/java/org/aeonbits/owner/crypto/AbstractEncryptor.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.aeonbits.owner.crypto; - -/** - * An abstract implementation of Encryptor. - */ -public abstract class AbstractEncryptor -extends AbstractDecryptor -implements Encryptor { -} diff --git a/owner/src/main/java/org/aeonbits/owner/crypto/Decryptor.java b/owner/src/main/java/org/aeonbits/owner/crypto/Decryptor.java deleted file mode 100644 index 6a74ed732..000000000 --- a/owner/src/main/java/org/aeonbits/owner/crypto/Decryptor.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.aeonbits.owner.crypto; - -import java.io.Serializable; - -/** - * A decryptor is a class which is able to decrypt a value. - *

- * This interface allows separation between API needed by OWNER at decription level and a implementation with a - * decription library, as javax.crypto or others. - */ -public interface Decryptor extends Serializable { - /** - * Decrypts a value. - * @param value the value to decrypt. - * @return the value decrypted - * @throws IllegalArgumentException on any failure, with the message and the original exception. - */ - String decrypt( String value ); - - /** - * Decrypts a value, and when the value can not be decrypted returns a default value. - * @param value the value to decrypt. - * @param defaultValue the value to return in case a failure occurst. - * @return the value decrypted or, in case a failure occurs, the default value. - */ - String decrypt( String value, String defaultValue ); -} diff --git a/owner/src/main/java/org/aeonbits/owner/crypto/Encryptor.java b/owner/src/main/java/org/aeonbits/owner/crypto/Encryptor.java deleted file mode 100644 index 7696522c2..000000000 --- a/owner/src/main/java/org/aeonbits/owner/crypto/Encryptor.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.aeonbits.owner.crypto; - -/** - * An encryptor is a class which is able to encrypt and decrypt a value. - *

- * This interface allows separation between API needed by OWNER at decription level and a implementation with a - * decription library, as javax.crypto or others. - */ -public interface Encryptor extends Decryptor { - /** - * Encrypts a value. - * @param value the value to encrypt. - * @return the value encrypted - * @throws IllegalArgumentException on any failure, with the message and the original exception. - */ - String encrypt( String value ) ; -} diff --git a/owner/src/main/java/org/aeonbits/owner/crypto/IdentityDecryptor.java b/owner/src/main/java/org/aeonbits/owner/crypto/IdentityDecryptor.java deleted file mode 100644 index 338cfb85b..000000000 --- a/owner/src/main/java/org/aeonbits/owner/crypto/IdentityDecryptor.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.aeonbits.owner.crypto; - -/** - * IdentityDecryptor is a (non) encryptor: it accepts a value and returns the same value for decripting and encripting. - * It is used as default value for {@link org.aeonbits.owner.Config.EncryptedValue} and {@link org.aeonbits.owner.Config.DecryptorClass}. - */ -public final class IdentityDecryptor -extends AbstractDecryptor { - @Override - public String decrypt( String value ) { - return value; - } -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/Event.java b/owner/src/main/java/org/aeonbits/owner/event/Event.java deleted file mode 100644 index 3ef94864b..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/Event.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import java.util.EventObject; - -/** - * The root event class for all OWNER events. - * - * @author Luigi R. Viggiano - * @since 1.0.4 - */ -public class Event extends EventObject { - - /** - * Constructs a prototypical Event. - * - * @param source The object on which the Event initially occurred. - * @throws IllegalArgumentException if source is null. - */ - public Event(Object source) { - super(source); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/ReloadEvent.java b/owner/src/main/java/org/aeonbits/owner/event/ReloadEvent.java deleted file mode 100644 index 275581068..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/ReloadEvent.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import java.beans.PropertyChangeEvent; -import java.util.List; -import java.util.Properties; - -import static java.util.Collections.unmodifiableList; - -/** - * A semantic event which indicates that a reload occurred. - * - * @author Luigi R. Viggiano - * @see ReloadListener - * @since 1.0.4 - */ -public class ReloadEvent extends Event { - - private final List events; - private final Properties oldProperties; - private final Properties newProperties; - - /** - * Constructs a prototypical Event. - * - * @param source The object on which the Event initially occurred. - * @param events The {@link PropertyChangeEvent change events} regarding which properties have been modified - * during the reload. - * @param oldProperties the properties before the reload. - * @param newProperties the properties after the reload. - * @throws IllegalArgumentException if source is null. - */ - public ReloadEvent(Object source, List events, Properties oldProperties, - Properties newProperties) { - super(source); - this.events = unmodifiableList(events); - this.oldProperties = new UnmodifiableProperties(oldProperties); - this.newProperties = new UnmodifiableProperties(newProperties); - } - - /** - * Returns The {@link PropertyChangeEvent change events} regarding which properties have been modified during the - * reload. - * - * @return The {@link PropertyChangeEvent change events} regarding which properties have been modified during the - * reload. - */ - public List getEvents() { - return events; - } - - /** - * Returns the properties before the reload. - * - * @return the properties before the reload. - */ - public Properties getOldProperties() { - return oldProperties; - } - - /** - * Returns the properties after the reload. - * - * @return the properties after the reload. - */ - public Properties getNewProperties() { - return newProperties; - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/ReloadListener.java b/owner/src/main/java/org/aeonbits/owner/event/ReloadListener.java deleted file mode 100644 index c7f976d20..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/ReloadListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import java.util.EventListener; - -/** - * The listener interface for receiving reload events. The class that is interested in processing a reload event - * implements this interface, and the object created with that class is registered with a component, using the - * component's addReloadListener method. When the reload event occurs, that object's - * reloadPerformed method is invoked. - * - * @author Luigi R. Viggiano - * @see ReloadEvent - * @since 1.0.4 - */ -public interface ReloadListener extends EventListener { - - /** - * This method is invoked after the property are reloaded. - * When this method is invoked we can assume that the changes are effective. - * - * @param event the {@link ReloadEvent event} of property reload. - */ - void reloadPerformed(ReloadEvent event); - -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/RollbackBatchException.java b/owner/src/main/java/org/aeonbits/owner/event/RollbackBatchException.java deleted file mode 100644 index 7e4f4e193..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/RollbackBatchException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -/** - * Indicates that whole batch of event must be rolled back. - * A batch is intended as a group of operations are executed in a row. - * For instance this happens when the whole list of properties is reloaded or cleared. - * - * @author Luigi R. Viggiano - * @since 1.0.5 - */ -public class RollbackBatchException extends RollbackException { - - public RollbackBatchException() { - super(); - } - - public RollbackBatchException(String message) { - super(message); - } - - public RollbackBatchException(Throwable cause) { - super(cause); - } - - public RollbackBatchException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/RollbackException.java b/owner/src/main/java/org/aeonbits/owner/event/RollbackException.java deleted file mode 100644 index c7fafade4..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/RollbackException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -/** - * Superclass for event rollback. - * - * @author Luigi R. Viggiano - * @since 1.0.5 - */ -public abstract class RollbackException extends Exception { - - public RollbackException() { - super(); - } - - public RollbackException(String msg) { - super(msg); - } - - public RollbackException(Throwable cause) { - super(cause); - } - - public RollbackException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/RollbackOperationException.java b/owner/src/main/java/org/aeonbits/owner/event/RollbackOperationException.java deleted file mode 100644 index b2016b415..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/RollbackOperationException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -/** - * Indicates that operation must be rolled back. - * - * @author Luigi R. Viggiano - * @since 1.0.5 - */ -public class RollbackOperationException extends RollbackException { - - public RollbackOperationException() { - super(); - } - - public RollbackOperationException(String message) { - super(message); - } - - public RollbackOperationException(Throwable cause) { - super(cause); - } - - public RollbackOperationException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/TransactionalPropertyChangeListener.java b/owner/src/main/java/org/aeonbits/owner/event/TransactionalPropertyChangeListener.java deleted file mode 100644 index 46e9c0e72..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/TransactionalPropertyChangeListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -/** - * A Listener that is aware of properties changes, with transactional capability. - * - * @since 1.0.5 - * @author Luigi R. Viggiano - */ -public interface TransactionalPropertyChangeListener extends PropertyChangeListener { - - /** - * This method is invoked before the property is changed. When this method is invoked we cannot assume that the - * change is effective, since some listener can ask to roll back the change operation. - * - * @param event the {@link PropertyChangeEvent event} of property change. - * @throws RollbackOperationException when the listener wants to rollback the change on the property intercepted - * @throws RollbackBatchException when the listener wants to rollback the entire set of changes if executed in - * the batch. - */ - void beforePropertyChange(PropertyChangeEvent event) throws RollbackOperationException, RollbackBatchException; - -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/TransactionalReloadListener.java b/owner/src/main/java/org/aeonbits/owner/event/TransactionalReloadListener.java deleted file mode 100644 index f531f7e0b..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/TransactionalReloadListener.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -/** - * A Listener that is aware of properties reloads, with transactional capability. - * - * @since 1.0.5 - * @author Luigi R. Viggiano - */ -public interface TransactionalReloadListener extends ReloadListener { - - /** - * This method is invoked before the property are reloaded. When this method is invoked we cannot assume that the - * changes are effective, since some listener can ask to roll back the change. - * - * @param event the {@link ReloadEvent event} of property reload. - * @throws RollbackBatchException when the listener wants to rollback the entire reload. - */ - void beforeReload(ReloadEvent event) throws RollbackBatchException; - -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/UnmodifiableProperties.java b/owner/src/main/java/org/aeonbits/owner/event/UnmodifiableProperties.java deleted file mode 100644 index 20e260462..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/UnmodifiableProperties.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; - -import static java.util.Collections.unmodifiableCollection; -import static java.util.Collections.unmodifiableSet; - -/** - * @author Luigi R. Viggiano - */ -class UnmodifiableProperties extends Properties { - - public UnmodifiableProperties(Properties properties) { - fill(properties); - } - - private void fill(Map t) { - for (Map.Entry e : t.entrySet()) - super.put(e.getKey(), e.getValue()); - } - - @Override - public synchronized Object put(Object key, Object value) { - throw new UnsupportedOperationException(); - } - - @Override - public synchronized Object remove(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public synchronized void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public Set keySet() { - return unmodifiableSet(super.keySet()); - } - - @Override - public Set> entrySet() { - return unmodifiableSet(super.entrySet()); - } - - @Override - public Collection values() { - return unmodifiableCollection(super.values()); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/event/package-info.java b/owner/src/main/java/org/aeonbits/owner/event/package-info.java deleted file mode 100644 index 697c679fb..000000000 --- a/owner/src/main/java/org/aeonbits/owner/event/package-info.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -/** - * Provides interfaces and classes for dealing with different types of events fired by OWNER components. - * - * See the {@link org.aeonbits.owner.event.Event} class. Events are fired by event sources. - * An event listener registers with an event source to receive notifications about the events of a - * particular type. This package defines events and event listeners, as well as event listener adapters, - * which are convenience classes to make easier the process of writing event listeners. - */ -package org.aeonbits.owner.event; diff --git a/owner/src/main/java/org/aeonbits/owner/loaders/Loader.java b/owner/src/main/java/org/aeonbits/owner/loaders/Loader.java deleted file mode 100644 index c76353307..000000000 --- a/owner/src/main/java/org/aeonbits/owner/loaders/Loader.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loaders; - -import java.io.IOException; -import java.io.Serializable; -import java.net.URI; -import java.util.Properties; - -/** - * Defines the interface of a generic Properties loader. - * - * @author Luigi R. Viggiano - * @since 1.0.5 - */ -public interface Loader extends Serializable { - - /** - * Indicates wether this Loader does accept the URL, guessing the content type from it. - * - * @since 1.1.0 - * @param uri the URI - * @return true, if the loader is able to handle the content of the URI. - */ - boolean accept(URI uri); - - /** - * Loads the given {@link URI uri} into the given {@link Properties result} - * - * @since 1.1.0 - * @param result the resulting properties where to load the {@link URI uri} - * @param uri the {@link URI} from where to load the properties. - * @throws java.io.IOException if there is some I/O error during the load. - */ - void load(Properties result, URI uri) throws IOException; - - /** - * Returns the default URI specification for a given url resource, that can be handled by this loader. - * - * @param uriPrefix the prefix identifying the url resource. - * @return the default URI specification for a given uri resource, that can be handled by this loader. - */ - String defaultSpecFor(String uriPrefix); -} diff --git a/owner/src/main/java/org/aeonbits/owner/loaders/PhileasSystemLoader.java b/owner/src/main/java/org/aeonbits/owner/loaders/PhileasSystemLoader.java deleted file mode 100644 index 5590b745c..000000000 --- a/owner/src/main/java/org/aeonbits/owner/loaders/PhileasSystemLoader.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2023 Philterd, LLC @ https://www.philterd.ai - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.aeonbits.owner.loaders; - -import java.io.IOException; -import java.net.URI; -import java.util.Properties; - -import static org.aeonbits.owner.util.Util.system; - -/** - * Allows specifying system:properties and system:env with the @Sources annotation. - * - * This class accesses Util.system() which is package accessible; for this reason this class cannot be moved - * inside the package loaders. - * - * I think this class should be split into two separate classes: - * one for system:properties and one for system:env. - */ -public class PhileasSystemLoader implements Loader { - - private static final String SYSTEM_PROPERTIES_URI = "system:properties"; - private static final String ENVIRONMENT_VARIABLES_URI = "system:env"; - - public boolean accept(URI uri) { - String path = uri.toString(); - return SYSTEM_PROPERTIES_URI.equals(path) || ENVIRONMENT_VARIABLES_URI.equals(path); - } - - public void load(Properties result, URI uri) throws IOException { - String path = uri.toString(); - if (SYSTEM_PROPERTIES_URI.equals(path)) - result.putAll(system().getProperties()); - if (ENVIRONMENT_VARIABLES_URI.equals(path)) { - for(String key : system().getenv().keySet()) { - final String name = key.toLowerCase().replace("philter_", "").replace("_", "."); - result.put(name, system().getenv().get(key)); - } - } - } - - public String defaultSpecFor(String uriPrefix) { - return null; - } -} - - diff --git a/owner/src/main/java/org/aeonbits/owner/loaders/PropertiesLoader.java b/owner/src/main/java/org/aeonbits/owner/loaders/PropertiesLoader.java deleted file mode 100644 index 8e1b3e01a..000000000 --- a/owner/src/main/java/org/aeonbits/owner/loaders/PropertiesLoader.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loaders; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.util.Properties; - -/** - * A {@link Loader loader} able to read properties from standard Java properties files. - * - * @since 1.0.5 - * @author Luigi R. Viggiano - */ -public class PropertiesLoader implements Loader { - - private static final long serialVersionUID = -1781643040589572341L; - private static final String DEFAULT_ENCODING = "UTF-8"; - - public boolean accept(URI uri) { - try { - uri.toURL(); - return true; - } catch (MalformedURLException ex) { - return false; - } - } - - public void load(Properties result, URI uri) throws IOException { - URL url = uri.toURL(); - InputStream input = url.openStream(); - try { - load(result, input); - } finally { - input.close(); - } - } - - void load(Properties result, InputStream input) throws IOException { - result.load(new InputStreamReader(input, DEFAULT_ENCODING)); - } - - public String defaultSpecFor(String uriPrefix) { - return uriPrefix + ".properties"; - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/loaders/SystemLoader.java b/owner/src/main/java/org/aeonbits/owner/loaders/SystemLoader.java deleted file mode 100644 index 027be4c47..000000000 --- a/owner/src/main/java/org/aeonbits/owner/loaders/SystemLoader.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2012-2018, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loaders; - -import java.io.IOException; -import java.net.URI; -import java.util.Properties; - -import static org.aeonbits.owner.util.Util.system; - -/** - * Allows specifying system:properties and system:env with the @Sources annotation. - * - * @author Ting-Kuan Wu - * @author Luigi R. Viggiano - * @since 1.0.10 - */ -public class SystemLoader implements Loader { -/* - * This class accesses Util.system() which is package accessible; for this reason this class cannot be moved - * inside the package loaders. - * - * I think this class should be splitted in two separate classes: - * one for system:properties and one for system:env. - */ - - private static final String SYSTEM_PROPERTIES_URI = "system:properties"; - private static final String ENVIRONMENT_VARIABLES_URI = "system:env"; - - - public boolean accept(URI uri) { - String path = uri.toString(); - return SYSTEM_PROPERTIES_URI.equals(path) || ENVIRONMENT_VARIABLES_URI.equals(path); - } - - public void load(Properties result, URI uri) throws IOException { - String path = uri.toString(); - if (SYSTEM_PROPERTIES_URI.equals(path)) - result.putAll(system().getProperties()); - if (ENVIRONMENT_VARIABLES_URI.equals(path)) { - result.putAll(system().getenv()); - } - } - - public String defaultSpecFor(String uriPrefix) { - return null; - } -} - - diff --git a/owner/src/main/java/org/aeonbits/owner/loaders/XMLLoader.java b/owner/src/main/java/org/aeonbits/owner/loaders/XMLLoader.java deleted file mode 100644 index f6f09c2c1..000000000 --- a/owner/src/main/java/org/aeonbits/owner/loaders/XMLLoader.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loaders; - -import org.xml.sax.Attributes; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.ext.DefaultHandler2; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.util.Properties; -import java.util.Stack; - -/** - * A {@link Loader loader} able to read properties from standard XML Java properties files, as well as user defined - * XML properties files. - * - * @since 1.0.5 - * @author Luigi R. Viggiano - */ -public class XMLLoader implements Loader { - - private static final long serialVersionUID = -894351666332018767L; - private transient SAXParserFactory factory = null; - - private synchronized SAXParserFactory factory() { - if (factory == null) { - factory = SAXParserFactory.newInstance(); - factory.setValidating(true); - factory.setNamespaceAware(true); - } - return factory; - } - - static class XmlToPropsHandler extends DefaultHandler2 { - - private static final String PROPS_DTD_URI = - "http://java.sun.com/dtd/properties.dtd"; - - private static final String PROPS_DTD = - "" + - "" + - "" + - "" + - "" + - "" + - ""; - - private boolean isJavaPropertiesFormat = false; - private final Properties props; - private final Stack paths = new Stack(); - private final Stack value = new Stack(); - - @Override - public InputSource resolveEntity(String name, String publicId, String baseURI, - String systemId) throws SAXException, IOException { - InputSource inputSource = null; - if (systemId.equals(PROPS_DTD_URI)) { - isJavaPropertiesFormat = true; - inputSource = new InputSource(new StringReader(PROPS_DTD)); - inputSource.setSystemId(PROPS_DTD_URI); - } - return inputSource; - } - - public XmlToPropsHandler(Properties props) { - this.props = props; - } - - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { - value.push(new StringBuilder()); - - if (isJavaPropertiesFormat) { - if ("entry".equals(qName)) - paths.push(attributes.getValue("key")); - else - paths.push(qName); - } else { - String path = (paths.size() == 0) ? qName : paths.peek() + "." + qName; - paths.push(path); - for (int i = 0; i < attributes.getLength(); i++) { - String attrName = attributes.getQName(i); - String attrValue = attributes.getValue(i); - props.setProperty(path + "." + attrName, attrValue); - } - } - } - - @Override - public void characters(char[] ch, int start, int length) throws SAXException { - value.peek().append(new String(ch, start, length)); - } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - String key = paths.peek(); - String propertyValue = this.value.peek().toString().trim(); - if (!propertyValue.isEmpty() && - !(isJavaPropertiesFormat && "comment".equals(key))) - props.setProperty(key, propertyValue); - value.pop(); - paths.pop(); - } - - @Override - public void error(SAXParseException e) throws SAXException { - if (isJavaPropertiesFormat) - throw e; - } - } - - public boolean accept(URI uri) { - try { - URL url = uri.toURL(); - return url.getFile().toLowerCase().endsWith(".xml"); - } catch (MalformedURLException ex) { - return false; - } - } - - public void load(Properties result, URI uri) throws IOException { - InputStream input = uri.toURL().openStream(); - try { - SAXParser parser = factory().newSAXParser(); - XmlToPropsHandler h = new XmlToPropsHandler(result); - parser.setProperty("http://xml.org/sax/properties/lexical-handler", h); - parser.parse(input, h); - } catch (ParserConfigurationException e) { - throw new IllegalArgumentException(e); - } catch (SAXException e) { - throw new IOException(e); - } finally { - input.close(); - } - } - - public String defaultSpecFor(String urlPrefix) { - return urlPrefix + ".xml"; - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/loaders/package-info.java b/owner/src/main/java/org/aeonbits/owner/loaders/package-info.java deleted file mode 100644 index 31fff988e..000000000 --- a/owner/src/main/java/org/aeonbits/owner/loaders/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -/** - * Provides interfaces and classes to allow OWNER to load properties from several file formats. - */ -package org.aeonbits.owner.loaders; diff --git a/owner/src/main/java/org/aeonbits/owner/package-info.java b/owner/src/main/java/org/aeonbits/owner/package-info.java deleted file mode 100644 index 5eb037dec..000000000 --- a/owner/src/main/java/org/aeonbits/owner/package-info.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -/** - *

- * The goal of OWNER API is to minimize the code required to handle application configuration through Java properties - * files. - *

- * - *

- * The approach used by OWNER APIs, is to define a Java interface associated to a properties file. - *

- * - * Suppose your properties file is defined as ServerConfig.properties: - * - *
- *  port=80
- *  hostname=foobar.com
- *  maxThreads=100
- *  
- * - * To access this property you need to define a convenient Java interface in ServerConfig.java: - * - *
- *  public interface ServerConfig extends Config {
- *      int port();
- *      String hostname();
- *
- *      @DefaultValue("42");
- *      int maxThreads();
- *  }
- *  
- * - *

- * We'll call this interface the Properties Mapping Interface or just Mapping Interface since its goal is to map - * Properties into a an easy to use piece of code. - *

- * - *

- * Owner has a lot of features and its behavior is fully customizable to your needs. - *

- *

- * Have a look at the full documentation from the OWNER website. - *

- */ -package org.aeonbits.owner; diff --git a/owner/src/main/java/org/aeonbits/owner/util/Base64.java b/owner/src/main/java/org/aeonbits/owner/util/Base64.java deleted file mode 100644 index e8930ce18..000000000 --- a/owner/src/main/java/org/aeonbits/owner/util/Base64.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2012-2017, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import java.lang.reflect.Method; - -import static org.aeonbits.owner.util.Reflection.forName; - -public class Base64 { - private static Method decoderMethod; - private static Method encoderMethod; - private static Object decoderObject; - private static Object encoderObject; - - // Suppresses default constructor, ensuring no one instantiate this class. - private Base64() {} - - static { - Class[] decodeParameterTypes = { String.class }; - Class[] encodeParameterTypes = { byte[].class }; - - // Java 8, Java 9 - Class javaUtilBase64Class = forName("java.util.Base64"); - if (javaUtilBase64Class != null) { - try { - decoderObject = javaUtilBase64Class.getMethod("getDecoder").invoke(null); - decoderMethod = decoderObject.getClass().getMethod("decode", decodeParameterTypes); - encoderObject = javaUtilBase64Class.getMethod("getEncoder").invoke(null); - encoderMethod = encoderObject.getClass().getMethod("encodeToString", encodeParameterTypes); - } catch (Exception e) { - reset(); - } - } - - // Java 6, 7 - if (decoderMethod == null) { - decoderObject = null; - encoderObject = null; - Class javaxXmlBindDatatypeConverterClass = forName("javax.xml.bind.DatatypeConverter"); - if (javaxXmlBindDatatypeConverterClass != null) { - try { - decoderMethod = javaxXmlBindDatatypeConverterClass.getMethod("parseBase64Binary", decodeParameterTypes); - encoderMethod = javaxXmlBindDatatypeConverterClass.getMethod("printBase64Binary", encodeParameterTypes); - } catch (NoSuchMethodException e) { - reset(); - } - } - } - } - - private static void reset() { - encoderObject = null; - encoderMethod = null; - decoderMethod = null; - decoderObject = null; - } - - - public static byte[] decode(String data) { - if (decoderMethod == null) throw new UnsupportedOperationException("Cannot find Base64 decoder."); - try { - return (byte[]) decoderMethod.invoke(decoderObject, data); - } catch (Exception e) { - throw new UnsupportedOperationException(e); - } - } - - public static String encode(byte[] data) { - if (encoderMethod == null) throw new UnsupportedOperationException("Cannot find Base64 encoder."); - try { - return (String) encoderMethod.invoke(encoderObject, data); - } catch (Exception e) { - throw new UnsupportedOperationException(e); - } - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/util/Collections.java b/owner/src/main/java/org/aeonbits/owner/util/Collections.java deleted file mode 100644 index 00545a66c..000000000 --- a/owner/src/main/java/org/aeonbits/owner/util/Collections.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import java.io.Serializable; -import java.util.AbstractMap; -import java.util.AbstractMap.SimpleEntry; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import static java.util.Arrays.asList; - -/** - * Utility class to create a maps, lists and sets - *

Examples of usage:

- *
- * import static org.aeonbits.owner.util.Collections.map;
- * import static org.aeonbits.owner.util.Collections.entry;
- * import static org.aeonbits.owner.util.Collections.set;
- * import static org.aeonbits.owner.util.Collections.list;
- *
- * Map<String, String> myMap = map("foo", "bar");
- * Map<String, String> myMap2 = map(entry("foo", "bar"), entry("baz", "qux");
- * Set<String> mySet = set("foo", "bar", "baz", "qux");
- * List<String> myList = list("foo", "bar", "baz", "qux");
- * 
- * - * @author Luigi R. Viggiano - * @since 1.0.6 - */ -public abstract class Collections { - - // Suppresses default constructor, ensuring no one instantiate this class. - private Collections() {} - - private static final class EntryMap extends AbstractMap implements Serializable { - private static final long serialVersionUID = -789853606407653214L; - private final Set> entries; - - private EntryMap(Entry... entries) { - this.entries = set(entries); - } - - @SuppressWarnings("unchecked") - @Override - public Set> entrySet() { - return (Set) entries; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - - EntryMap entryMap = (EntryMap) o; - - return entries.equals(entryMap.entries); - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + entries.hashCode(); - return result; - } - } - - public static Entry entry(K key, V value) { - return new SimpleEntry(key, value); - } - - @SuppressWarnings("unchecked") - public static Map map(K key, V value) { - return map(entry(key, value)); - } - - public static Map map(Map.Entry... entries) { - return new EntryMap(entries); - } - - public static Set set(E... elements) { - return new LinkedHashSet(list(elements)); - } - - public static List list(E... elements) { - return asList(elements); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/util/Reflection.java b/owner/src/main/java/org/aeonbits/owner/util/Reflection.java deleted file mode 100644 index 772d4d70e..000000000 --- a/owner/src/main/java/org/aeonbits/owner/util/Reflection.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import java.lang.reflect.Method; - -/** - * @author Luigi R. Viggiano - */ -public final class Reflection { - - // Suppresses default constructor, ensuring no one instantiate this class. - private Reflection() {} - - public static boolean isClassAvailable(String className) { - return forName(className) != null; - } - - public static Class forName(String className) { - try { - return Class.forName(className); - } catch (ClassNotFoundException e) { - return null; - } - } - - interface Java8Support { - boolean isDefault(Method method); - - Object invokeDefaultMethod(Object proxy, Method method, Object[] args) throws Throwable; - } - - private static final Java8Support JAVA_8_SUPPORT = getJava8Support(); - - private static Java8Support getJava8Support() { - try { - return (Java8Support) Class.forName("org.aeonbits.owner.util.Java8SupportImpl").newInstance(); - } catch (Exception e) { - return java8NotSupported(); - } - } - - private static Java8Support java8NotSupported() { - return new Java8Support() { - public boolean isDefault(Method method) { - return false; - } - - public Object invokeDefaultMethod(Object proxy, Method method, Object[] args) throws Throwable { - return null; - } - }; - } - - - public static boolean isDefault(Method method) { - return JAVA_8_SUPPORT.isDefault(method); - } - - public static Object invokeDefaultMethod(Object proxy, Method method, Object[] args) throws Throwable { - return JAVA_8_SUPPORT.invokeDefaultMethod(proxy, method, args); - } - -} diff --git a/owner/src/main/java/org/aeonbits/owner/util/Util.java b/owner/src/main/java/org/aeonbits/owner/util/Util.java deleted file mode 100644 index eae024c0b..000000000 --- a/owner/src/main/java/org/aeonbits/owner/util/Util.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (c) 2012-2018, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import org.aeonbits.owner.Config.DisableFeature; -import org.aeonbits.owner.Config.DisableableFeature; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Method; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.jar.JarOutputStream; -import java.util.regex.Matcher; -import java.util.zip.ZipEntry; - -import static java.io.File.createTempFile; -import static java.lang.String.format; -import static java.net.URLDecoder.decode; -import static java.util.Arrays.asList; - -/** - * This class contains utility methods used all over the library. - * - * @author Luigi R. Viggiano - */ -public abstract class Util { - - public interface TimeProvider { - long getTime(); - } - - public interface SystemProvider { - String getProperty(String key); - - Map getenv(); - - Properties getProperties(); - } - - static TimeProvider timeProvider = new TimeProvider() { - public long getTime() { - return System.currentTimeMillis(); - } - }; - - static SystemProvider system = new SystemProvider() { - public String getProperty(String key) { - return System.getProperty(key); - } - - public Map getenv() { - return System.getenv(); - } - - public Properties getProperties() { - return (Properties) System.getProperties().clone(); - } - }; - - /** Don't let anyone instantiate this class */ - private Util() {} - - public static List reverse(List src) { - List copy = new ArrayList(src); - Collections.reverse(copy); - return copy; - } - - @SuppressWarnings("unchecked") - public static T[] reverse(T[] array) { - T[] copy = array.clone(); - Collections.reverse(asList(copy)); - return copy; - } - - public static String expandUserHome(String text) { - if (text.equals("~")) - return getUserHome(); - if (text.indexOf("~/") == 0 || text.indexOf("file:~/") == 0 || text.indexOf("jar:file:~/") == 0) - return text.replaceFirst("~/", Matcher.quoteReplacement(getUserHome()) + "/"); - if (text.indexOf("~\\") == 0 || text.indexOf("file:~\\") == 0 || text.indexOf("jar:file:~\\") == 0) - return text.replaceFirst("~\\\\", Matcher.quoteReplacement(getUserHome()) + "\\\\"); - return text; - } - - private static String getUserHome() { - return system.getProperty("user.home"); - } - - public static String fixBackslashesToSlashes(String path) { - return path.replace('\\', '/'); - } - - public static String fixSpacesToPercentTwenty(String path) { - return path.replace(" ", "%20"); - } - - public static T ignoreAndReturnNull() { - // the ignoreAndReturnNull method does absolutely nothing, but it helps to shut up warnings by pmd and other reporting tools - // complaining about empty catch methods. - return null; - } - - /** - * no operation - */ - public static void ignore() { - } - - public static boolean isFeatureDisabled(Method method, DisableableFeature feature) { - Class annotation = DisableFeature.class; - return isFeatureDisabled(feature, method.getDeclaringClass().getAnnotation(annotation)) || - isFeatureDisabled(feature, method.getAnnotation(annotation)); - } - - private static boolean isFeatureDisabled(DisableableFeature feature, DisableFeature annotation) { - return annotation != null && asList(annotation.value()).contains(feature); - } - - public static UnsupportedOperationException unsupported(Throwable cause, String msg, Object... args) { - return new UnsupportedOperationException(format(msg, args), cause); - } - - public static UnsupportedOperationException unsupported(String msg, Object... args) { - return new UnsupportedOperationException(format(msg, args)); - } - - public static T unreachableButCompilerNeedsThis() { - throw new AssertionError("this code should never be reached"); - } - - public static String asString(Object result) { - if (result == null) return null; - return String.valueOf(result); - } - - public static long now() { - return timeProvider.getTime(); - } - - public static File fileFromURI(URI uri) { - if ("file".equalsIgnoreCase(uri.getScheme())) { - String path = uri.getSchemeSpecificPart(); - try { - path = decode(path, "utf-8"); - return new File(path); - } catch (UnsupportedEncodingException e) { - return unreachableButCompilerNeedsThis(/* utf-8 is supported in jre libraries */); - } - } else if ("jar".equalsIgnoreCase(uri.getScheme())) { - String path = uri.getSchemeSpecificPart(); - try { - return fileFromURI(path.substring(0, path.indexOf('!'))); - } catch (URISyntaxException e) { - return ignoreAndReturnNull(/* non critical */); - } - } - return null; - } - - public static File fileFromURI(String uriSpec) throws URISyntaxException { - try { - return fileFromURI(new URI(uriSpec)); - } catch (URISyntaxException e) { - // Perhaps the path contains backslashes - uriSpec = uriSpec.replace('\\', '/'); - return fileFromURI(new URI(uriSpec)); - } - } - - public static boolean eq(Object o1, Object o2) { - return o1 == o2 || o1 != null && o1.equals(o2); - } - - public static SystemProvider system() { - return system; - } - - public static void save(File target, Properties p) throws IOException { - File parent = target.getParentFile(); - parent.mkdirs(); - if (isWindows()) { - store(target, p); - } else { - File tempFile = createTempFile(target.getName(), ".temp", parent); - store(tempFile, p); - rename(tempFile, target); - } - - } - - private static boolean isWindows() { - return system.getProperty("os.name").toLowerCase().contains("win"); - } - - public static void delete(File target) { - target.delete(); - } - - private static void store(File target, Properties p) throws IOException { - OutputStream out = new FileOutputStream(target); - try { - store(out, p); - } finally { - out.close(); - } - } - - private static void store(OutputStream out, Properties p) throws IOException { - p.store(out, "saved for test"); - } - - public static void saveJar(File target, String entryName, Properties props) throws IOException { - File parent = target.getParentFile(); - parent.mkdirs(); - storeJar(target, entryName, props); - } - - private static void rename(File source, File target) throws IOException { - if (!source.renameTo(target)) - throw new IOException(format("Failed to overwrite %s to %s", source.toString(), target.toString())); - } - - private static void storeJar(File target, String entryName, Properties props) throws IOException { - byte[] bytes = toBytes(props); - InputStream input = new ByteArrayInputStream(bytes); - try { - FileOutputStream fileOutputStream = new FileOutputStream(target); - try { - JarOutputStream output = new JarOutputStream(fileOutputStream); - try { - ZipEntry entry = new ZipEntry(entryName); - output.putNextEntry(entry); - byte[] buffer = new byte[4096]; - int size; - while ((size = input.read(buffer)) != -1) - output.write(buffer, 0, size); - } finally { - output.close(); - } - } finally { - fileOutputStream.close(); - } - } finally { - input.close(); - } - } - - private static byte[] toBytes(Properties props) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - store(out, props); - return out.toByteArray(); - } finally { - out.close(); - } - } - - public static T newInstance(Class clazz) { - try { - return clazz.getDeclaredConstructor().newInstance(); - } catch (Exception e) { - throw unsupported(e, - "Class '%s' cannot be instantiated; see the cause below in the stack trace", - clazz.getCanonicalName()); - } - } - - public static List newInstance(Class[] classes, List result) { - for (Class clazz : classes) - result.add(newInstance(clazz)); - return result; - } -} diff --git a/owner/src/main/java/org/aeonbits/owner/util/package-info.java b/owner/src/main/java/org/aeonbits/owner/util/package-info.java deleted file mode 100644 index ca25c4fc1..000000000 --- a/owner/src/main/java/org/aeonbits/owner/util/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -/** - * Provides utility interfaces and classes. - */ -package org.aeonbits.owner.util; diff --git a/owner/src/test/java/org/aeonbits/owner/ConfigFactoryTest.java b/owner/src/test/java/org/aeonbits/owner/ConfigFactoryTest.java deleted file mode 100644 index 323aa292e..000000000 --- a/owner/src/test/java/org/aeonbits/owner/ConfigFactoryTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.Sources; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.util.Properties; - -import static org.aeonbits.owner.util.UtilTest.save; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - -/** - * @author Luigi R. Viggiano - */ -public class ConfigFactoryTest implements TestConstants { - - @Sources("file:${mypath}/myconfig.properties") - interface MyConfig extends Config { - @DefaultValue("defaultValue") - String someValue(); - } - - @Before - public void before() throws IOException { - ConfigFactory.setProperties(null); - save(new File(RESOURCES_DIR + "/myconfig.properties"), new Properties() {{ - setProperty("someValue", "foobar"); - }}); - } - - @Test - public void testSetProperty() { - ConfigFactory.setProperty("mypath", RESOURCES_DIR); - - MyConfig cfg = ConfigFactory.create(MyConfig.class); - - assertEquals("foobar", cfg.someValue()); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetPropertyNullKey() { - ConfigFactory.setProperty(null, "foobar"); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetPropertyEmptyKey() { - ConfigFactory.setProperty("", "foobar"); - } - - @Test - public void testSetPropertyTwice() { - assertNull(ConfigFactory.setProperty("mypath", RESOURCES_DIR)); - assertEquals(RESOURCES_DIR, ConfigFactory.setProperty("mypath", RESOURCES_DIR + "-2")); - assertEquals(RESOURCES_DIR + "-2", ConfigFactory.getProperty("mypath")); - } - - @Test - public void testGetProperties() { - ConfigFactory.getProperties().setProperty("mypath", RESOURCES_DIR); - - MyConfig cfg = ConfigFactory.create(MyConfig.class); - - assertEquals("foobar", cfg.someValue()); - } - - @Test - public void testSetProperties() { - ConfigFactory.setProperties(new Properties() {{ - setProperty("mypath", RESOURCES_DIR); - }}); - - MyConfig cfg = ConfigFactory.create(MyConfig.class); - - assertEquals("foobar", cfg.someValue()); - } - - @Test - public void testSetPropertiesNullObject() { - ConfigFactory.setProperties(null); - - MyConfig cfg = ConfigFactory.create(MyConfig.class); - - assertEquals("defaultValue", cfg.someValue()); - } - - @Test - public void testGetProperty() { - ConfigFactory.setProperty("mypath", RESOURCES_DIR); - assertEquals(RESOURCES_DIR, ConfigFactory.getProperty("mypath")); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetPropertyNullKey() { - ConfigFactory.getProperty(null); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetPropertiesEmptyKey() { - ConfigFactory.getProperty(""); - } - - @Test - public void testGetClearProperty() { - ConfigFactory.setProperty("mypath", RESOURCES_DIR); - assertEquals(RESOURCES_DIR, ConfigFactory.clearProperty("mypath")); - assertNull(ConfigFactory.getProperty("mypath")); - } - - @Test(expected = IllegalArgumentException.class) - public void testClearPropertyNullKey() { - ConfigFactory.clearProperty(null); - } - - @Test(expected = IllegalArgumentException.class) - public void testClearPropertyEmptyKey() { - ConfigFactory.clearProperty(""); - } - - @Sources("${myurl}") - interface MyConfigWithoutProtocol extends Config, Accessible { - @DefaultValue("defaultValue") - String someValue(); - } - - @Test - public void testSetPropertyWithoutProtocol() { - ConfigFactory.setProperty("mypath", RESOURCES_DIR); - ConfigFactory.setProperty("myurl", "file:${mypath}/myconfig.properties"); - - MyConfigWithoutProtocol cfg = ConfigFactory.create(MyConfigWithoutProtocol.class); - - assertEquals("foobar", cfg.someValue()); - } - - @Test - public void testSetPropertyWithoutProtocolWhenFileIsNotFound() { - ConfigFactory.setProperty("mypath", RESOURCES_DIR); - ConfigFactory.setProperty("myurl", "file:${mypath}/non-existent.properties"); - - MyConfigWithoutProtocol cfg = ConfigFactory.create(MyConfigWithoutProtocol.class); - - assertEquals("defaultValue", cfg.someValue()); - assertThat(cfg.propertyNames(), contains("someValue")); - assertThat(cfg.propertyNames().size(), is(1)); - } - - @After - public void after() { - ConfigFactory.setProperties(null); // clean up things. - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/ConfigInheritanceTest.java b/owner/src/test/java/org/aeonbits/owner/ConfigInheritanceTest.java deleted file mode 100644 index bd7a862ce..000000000 --- a/owner/src/test/java/org/aeonbits/owner/ConfigInheritanceTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.aeonbits.owner; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - - -/** - * Created by chengmingwang on 12/24/16. - */ -public class ConfigInheritanceTest { - @Config.Sources( - {"classpath:test.properties","classpath:org/aeonbits/owner/first.properties"} - ) - interface MyConfig extends Config { - @DefaultValue("favoriteColor") - String favoriteColor(); - } - - interface TheConfig1 extends MyConfig { - - } - - @Config.Sources( - {"classpath:org/aeonbits/owner/second.properties"} - ) - interface TheConfig2 extends MyConfig { - - } - - @Config.Sources( - {"classpath:org/aeonbits/owner/second.properties"} - ) - @Config.LoadPolicy(Config.LoadType.MERGE) - interface TheConfig3 extends MyConfig { - - } - - @Test - public void testSourcesInheritance() { - TheConfig1 theConfig1 = ConfigFactory.create(TheConfig1.class); - assertEquals("pink", theConfig1.favoriteColor()); - - TheConfig2 theConfig2 = ConfigFactory.create(TheConfig2.class); - assertEquals("favoriteColor", theConfig2.favoriteColor()); - - TheConfig3 theConfig3 = ConfigFactory.create(TheConfig3.class); - assertEquals("pink", theConfig3.favoriteColor()); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/ConfigTest.java b/owner/src/test/java/org/aeonbits/owner/ConfigTest.java deleted file mode 100644 index e5873cc13..000000000 --- a/owner/src/test/java/org/aeonbits/owner/ConfigTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * @author Luigi R. Viggiano - */ -@RunWith(MockitoJUnitRunner.class) -public class ConfigTest { - - @Mock - private ScheduledExecutorService scheduler; - - public interface SampleConfig extends Config { - String hello(String param); - - @DefaultValue("Bohemian Rapsody - Queen") - String favoriteSong(); - - String unspecifiedProperty(); - - @Key("server.http.port") - int httpPort(); - - @Key("salutation.text") - @DefaultValue("Good Morning") - String salutation(); - - @Key("password") - @DefaultValue("@#$%^&*()") - String password(); - - @DefaultValue("foo") - void voidMethodWithValue(); - - void voidMethodWithoutValue(); - } - - @Test - public void shouldNotReturnNull() { - SampleConfig config = ConfigFactory.create(SampleConfig.class); - assertNotNull(config); - } - - @Test - public void shouldDoReplacements() { - SampleConfig config = ConfigFactory.create(SampleConfig.class, new Properties()); - assertEquals("Hello Luigi.", config.hello("Luigi")); - } - - @Test(expected = UnsupportedOperationException.class) - public void testVoidMethodWithValue() { - SampleConfig cfg = ConfigFactory.create(SampleConfig.class); - cfg.voidMethodWithValue(); - } - - @Test - public void testVoidMethodWithoutValue() { - SampleConfig cfg = ConfigFactory.create(SampleConfig.class); - cfg.voidMethodWithoutValue(); - } - - static interface StringSubstitutionConfig extends Config { - @DefaultValue("Hello Mr. %s!") - String helloMr(String name); - } - - @Test - public void testDefaultStringValue() { - StringSubstitutionConfig config = ConfigFactory.create(StringSubstitutionConfig.class); - assertEquals("Hello Mr. Luigi!", config.helloMr("Luigi")); - } - - @Test - public void testDefaultPropertyOverridden() { - SampleConfig config = ConfigFactory.create(SampleConfig.class); - assertEquals("Speechless - Lady Gaga", config.favoriteSong()); - } - - @Test - public void testUnspecifiedProperty() { - SampleConfig config = ConfigFactory.create(SampleConfig.class); - assertNull(config.unspecifiedProperty()); - } - - @Test - public void testPropertyWithCustomizedKey() { - SampleConfig config = ConfigFactory.create(SampleConfig.class); - assertEquals(80, config.httpPort()); - } - - @Test - public void testPropertyWithKeyAndDefaultValue() { - SampleConfig config = ConfigFactory.create(SampleConfig.class); - assertEquals("Good Afternoon", config.salutation()); - } - - public static interface SubstituteAndFormat extends Config { - @DefaultValue("Hello ${mister}") - String salutation(String name); - - @DefaultValue("Mr. %s") - String mister(String name); - } - - @Test - public void testSubstitutionAndFormat() { - SubstituteAndFormat cfg = ConfigFactory.create(SubstituteAndFormat.class); - assertEquals("Hello Mr. Luigi", cfg.salutation("Luigi")); - assertEquals("Mr. Luigi", cfg.mister("Luigi")); - } - - /** - * When a property value contains a '%' character but is not a String format, - * we expect the property value to be returned as-is. Under the covers, the String.format - * method is used for property expansion. We want to verify a property value that - * contains a '%' character but is _not_ a format String is, indeed, supported. - */ - @Test - public void whenPropertyValueIsNotValidFormatString_thenPropertyValueShouldRemainIntact() { - SampleConfig config = ConfigFactory.create(SampleConfig.class); - - assertEquals ("@#$%^&*()", config.password()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/ConfigURIFactoryTest.java b/owner/src/test/java/org/aeonbits/owner/ConfigURIFactoryTest.java deleted file mode 100644 index f1467c841..000000000 --- a/owner/src/test/java/org/aeonbits/owner/ConfigURIFactoryTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.junit.Test; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Properties; - -import static org.junit.Assert.assertNotNull; - -/** - * @author Luigi R. Viggiano - */ -public class ConfigURIFactoryTest { - @Test - public void shouldReturnAnURI() throws URISyntaxException { - ConfigURIFactory h = new ConfigURIFactory(this.getClass().getClassLoader(), new VariablesExpander(new Properties())); - URI uri = h.newURI("classpath:test.properties"); - assertNotNull(uri); - } - - @Test - public void shouldReturnAUriWithEmptyFilePath() throws URISyntaxException { - ConfigURIFactory h = new ConfigURIFactory(this.getClass().getClassLoader(), new VariablesExpander(new Properties())); - URI uri = h.newURI("file:"); - assertNotNull(uri); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/ConfigWithSubstitutionTest.java b/owner/src/test/java/org/aeonbits/owner/ConfigWithSubstitutionTest.java deleted file mode 100644 index b7e2909c8..000000000 --- a/owner/src/test/java/org/aeonbits/owner/ConfigWithSubstitutionTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class ConfigWithSubstitutionTest { - - public interface ConfigWithSubstitutionFile extends Config { - String story(); - } - - @Test - public void testConfigWithSubstitutionFile() { - ConfigWithSubstitutionFile conf = ConfigFactory.create(ConfigWithSubstitutionFile.class); - assertEquals("The quick brown fox jumped over the lazy dog", conf.story()); - } - - @Test - public void testConfigWithSubstitutionAnnotation() { - ConfigWithSubstitutionAnnotations conf = ConfigFactory.create(ConfigWithSubstitutionAnnotations.class); - assertEquals("The quick brown fox jumped over the lazy dog", conf.story()); - } - - @Test - public void testSubInterface() { - ConfigWithSubtstitutionAnnotationsSubInterface conf = ConfigFactory.create - (ConfigWithSubtstitutionAnnotationsSubInterface.class); - assertEquals("Please grandma, tell me the story of 'The quick brown fox jumped over the lazy dog'", - conf.tellmeTheStory()); - } - - public static interface ConfigWithSubtstitutionAnnotationsSubInterface extends ConfigWithSubstitutionAnnotations { - @DefaultValue("grandma") - public String teller(); - - @DefaultValue("Please ${teller}, tell me the story of '${story}'") - public String tellmeTheStory(); - } - - public static interface ConfigWithSubstitutionAnnotations extends Config { - - @DefaultValue("The ${animal} jumped over the ${target}") - String story(); - - @DefaultValue("quick ${color} fox") - String animal(); - - @DefaultValue("${target.attribute} dog") - String target(); - - @Key("target.attribute") - @DefaultValue("lazy") - String targetAttribute(); - - @DefaultValue("brown") - String color(); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/DisableFeatureTest.java b/owner/src/test/java/org/aeonbits/owner/DisableFeatureTest.java deleted file mode 100644 index ef7c59dcd..000000000 --- a/owner/src/test/java/org/aeonbits/owner/DisableFeatureTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.DisableFeature; -import org.junit.Test; - -import static org.aeonbits.owner.Config.DisableableFeature.PARAMETER_FORMATTING; -import static org.aeonbits.owner.Config.DisableableFeature.VARIABLE_EXPANSION; -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class DisableFeatureTest { - public interface ConfigWithSubstitutionDisabledOnMethod extends Config { - @DefaultValue("Earth") - String world(); - - @DisableFeature(VARIABLE_EXPANSION) - @DefaultValue("Hello ${world}.") - String sayHelloDisabled(); - - @DefaultValue("Hello ${world}.") - String sayHelloEnabled(); - } - - @Test - public void shouldNotExpandWorldWhenDisabledOnMethodLevel() { - ConfigWithSubstitutionDisabledOnMethod cfg = ConfigFactory.create(ConfigWithSubstitutionDisabledOnMethod.class); - assertEquals("Hello ${world}.", cfg.sayHelloDisabled()); - assertEquals("Hello Earth.", cfg.sayHelloEnabled()); - } - - @DisableFeature(VARIABLE_EXPANSION) - public static interface ConfigWithSubstitutionDisabledOnClass extends Config { - @DefaultValue("Earth") - String world(); - - @DefaultValue("Hello ${world}.") - String sayHelloDisabled(); - - @DefaultValue("Hello ${world}.") - String sayHelloEnabled(); - } - - @Test - public void shouldNotExpandWorldWhenDisabledOnClassLevel() { - ConfigWithSubstitutionDisabledOnClass cfg = ConfigFactory.create(ConfigWithSubstitutionDisabledOnClass.class); - assertEquals("Hello ${world}.", cfg.sayHelloDisabled()); - assertEquals("Hello ${world}.", cfg.sayHelloEnabled()); - } - - public static interface ConfigWithDisabledFormattingOnMethod extends Config { - @DisableFeature(PARAMETER_FORMATTING) - @DefaultValue("Hello %s.") - public String helloDisabled(String name); - @DefaultValue("Hello %s.") - public String helloEnabled(String name); - } - - @Test - public void shouldNotFormatOnMethodLevel() { - ConfigWithDisabledFormattingOnMethod cfg = ConfigFactory.create(ConfigWithDisabledFormattingOnMethod.class); - assertEquals("Hello %s.", cfg.helloDisabled("world")); - assertEquals("Hello world.", cfg.helloEnabled("world")); - } - - @DisableFeature(PARAMETER_FORMATTING) - public static interface ConfigWithDisabledFormattingOnClass extends Config { - @DefaultValue("Hello %s.") - public String helloDisabled(String name); - @DefaultValue("Hello %s.") - public String helloEnabled(String name); - } - - @Test - public void shouldNotFormatOnClassLevel() { - ConfigWithDisabledFormattingOnClass cfg = ConfigFactory.create(ConfigWithDisabledFormattingOnClass.class); - assertEquals("Hello %s.", cfg.helloDisabled("world")); - assertEquals("Hello %s.", cfg.helloEnabled("world")); - } - - public static interface ConfigWithDisabledFormattingAndExpansionOnMethod extends Config { - @DefaultValue("Earth") - public String planet(); - - @DisableFeature({VARIABLE_EXPANSION, PARAMETER_FORMATTING}) - @DefaultValue("Hello %s, welcome on ${planet}!") - public String helloDisabled(String name); - - @DefaultValue("Hello %s, welcome on ${planet}!") - public String helloEnabled(String name); - } - - @Test - public void shouldNotFormatAndExpandOnMethod() { - ConfigWithDisabledFormattingAndExpansionOnMethod cfg = - ConfigFactory.create(ConfigWithDisabledFormattingAndExpansionOnMethod.class); - assertEquals("Hello Luigi, welcome on Earth!", cfg.helloEnabled("Luigi")); - assertEquals("Hello %s, welcome on ${planet}!", cfg.helloDisabled("Luigi")); - } - - @DisableFeature({VARIABLE_EXPANSION, PARAMETER_FORMATTING}) - public static interface ConfigWithDisabledFormattingAndExpansionOnClass extends Config { - @DefaultValue("Earth") - public String planet(); - - @DisableFeature({VARIABLE_EXPANSION, PARAMETER_FORMATTING}) - @DefaultValue("Hello %s, welcome on ${planet}!") - public String helloDisabled(String name); - - @DefaultValue("Hello %s, welcome on ${planet}!") - public String helloEnabled(String name); - } - - @Test - public void shouldNotFormatAndExpandOnClass() { - ConfigWithDisabledFormattingAndExpansionOnClass cfg = - ConfigFactory.create(ConfigWithDisabledFormattingAndExpansionOnClass.class); - assertEquals("Hello %s, welcome on ${planet}!", cfg.helloEnabled("Luigi")); - assertEquals("Hello %s, welcome on ${planet}!", cfg.helloDisabled("Luigi")); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/EqualsAndHashCodeTest.java b/owner/src/test/java/org/aeonbits/owner/EqualsAndHashCodeTest.java deleted file mode 100644 index 8ac38ed0a..000000000 --- a/owner/src/test/java/org/aeonbits/owner/EqualsAndHashCodeTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.junit.Test; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -/** - * @author Luigi R. Viggiano - */ -public class EqualsAndHashCodeTest { - - interface MyConfig extends Config { - @DefaultValue("foo") - String foo(); - @DefaultValue("bar") - String bar(); - } - - interface MySubConfig extends MyConfig { - } - - interface UnrelatedConfig extends Config { - @DefaultValue("foo") - String foo(); - @DefaultValue("bar") - String bar(); - } - - - @Test - public void testWhenTwoObjectsAreEqual() { - MyConfig cfg1 = ConfigFactory.create(MyConfig.class); - MyConfig cfg2 = ConfigFactory.create(MyConfig.class); - - assertEquals(cfg1, cfg2); - assertEquals(cfg2, cfg1); - assertEquals(cfg1.hashCode(), cfg2.hashCode()); - } - - @Test - public void testWhenTwoObjectsAreNotEqual() { - MyConfig cfg1 = ConfigFactory.create(MyConfig.class); - MyConfig cfg2 = ConfigFactory.create(MyConfig.class, new Properties() {{ - setProperty("bar", "baz"); - }}); - - assertNotEquals(cfg1, cfg2); - assertNotEquals(cfg2, cfg1); - assertNotEquals(cfg1.hashCode(), cfg2.hashCode()); - } - - @Test - public void testWhenObjectsAreNotRelated() { - MyConfig cfg1 = ConfigFactory.create(MyConfig.class); - Object unrelated = new Object(); - - assertNotEquals(cfg1, unrelated); - assertNotEquals(unrelated, cfg1); - } - - @Test - public void testWhenConfigsAreNotRelated() { - MyConfig cfg1 = ConfigFactory.create(MyConfig.class); - UnrelatedConfig cfg2 = ConfigFactory.create(UnrelatedConfig.class); - - assertNotEquals(cfg1, cfg2); - assertNotEquals(cfg2, cfg1); - - // hashCodes equality doesn't imply objects equality - assertEquals(cfg1.hashCode(), cfg2.hashCode()); - } - - @Test - public void testWhenTwoObjectsAreSimilarProxies() { - MyConfig cfg1 = ConfigFactory.create(MyConfig.class); - MyConfig cfg2 = (MyConfig) Proxy - .newProxyInstance(getClass().getClassLoader(), new Class[] { MyConfig.class }, new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return null; - } - }); - - assertNotEquals(cfg1, cfg2); - } - - @Test - public void testWhenObjectIsSubclass() { - MyConfig cfg1 = ConfigFactory.create(MyConfig.class); - MySubConfig cfg2 = ConfigFactory.create(MySubConfig.class); - - assertEquals(cfg1, cfg2); - assertEquals(cfg2, cfg1); - assertEquals(cfg1.hashCode(), cfg2.hashCode()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/LoaderManagerTest.java b/owner/src/test/java/org/aeonbits/owner/LoaderManagerTest.java deleted file mode 100644 index 0998c1489..000000000 --- a/owner/src/test/java/org/aeonbits/owner/LoaderManagerTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.loaders.Loader; -import org.aeonbits.owner.loaders.PropertiesLoader; -import org.aeonbits.owner.loaders.XMLLoader; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -import static org.aeonbits.owner.util.UtilTest.fileFromURI; -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class LoaderManagerTest implements TestConstants { - private static final String SPEC = "file:" + RESOURCES_DIR + "/LoaderManagerTest.properties"; - - @Mock - private ScheduledExecutorService scheduler; - private File target; - - @Sources(SPEC) - interface MyConfig extends Config { - String foo(); - } - - interface MyConfigDefaultSpec extends Config { - String foo(); - } - - @Before - public void before() throws URISyntaxException, IOException { - target = fileFromURI(SPEC); - target.getParentFile().mkdirs(); - target.createNewFile(); - } - - @After - public void after() { - target.delete(); - } - - @Test(expected = UnsupportedOperationException.class) - public void testProxyCreationWhenLoaderCantBeRisolvedForGivenURL() { - Factory factory = new DefaultFactory(scheduler, new Properties()) {{ - loadersManager.clear(); - }}; - factory.registerLoader(new XMLLoader()); - factory.create(MyConfig.class); - } - - - @Test - public void testProxyCreationInNormalSituation() { - Factory factory = new DefaultFactory(scheduler, new Properties()); - MyConfigDefaultSpec cfg = factory.create(MyConfigDefaultSpec.class); - assertEquals("bar", cfg.foo()); - } - - @Test - public void testProxyCreationWhenLoaderReturnsFooBarAsDefaultSpec() { - Factory factory = new DefaultFactory(scheduler, new Properties()) {{ - loadersManager.clear(); - }}; - - factory.registerLoader(new PropertiesLoader()); - factory.registerLoader(new PropertiesLoader() { - @Override - public String defaultSpecFor(String uriPrefix) { - return uriPrefix + ".foobar"; - } - }); - - MyConfigDefaultSpec cfg = factory.create(MyConfigDefaultSpec.class); - assertEquals("foobar", cfg.foo()); - } - - @Test - public void testProxyCreationWhenLoaderReturnsNullAsDefaultSpec() { - Factory factory = new DefaultFactory(scheduler, new Properties()) {{ - loadersManager.clear(); - }}; - - factory.registerLoader(new PropertiesLoader()); - factory.registerLoader(new PropertiesLoader() { - @Override - public String defaultSpecFor(String uriPrefix) { - return null; - } - }); - - MyConfigDefaultSpec cfg = factory.create(MyConfigDefaultSpec.class); - assertEquals("bar", cfg.foo()); - } - - @Test(expected = IllegalArgumentException.class) - public void testRegisterNull() { - Factory factory = ConfigFactory.newInstance(); - factory.registerLoader(null); - } - - @Test(expected = IllegalArgumentException.class) - public void testRegisterNullOnSingleton() { - ConfigFactory.registerLoader(null); - } - - @Test - public void testRegisterNonNullLoaderOnSingleton() { - ConfigFactory.registerLoader(new LoaderThatDoesNothing()); - } - - public static class LoaderThatDoesNothing implements Loader { - public boolean accept(URI uri) { - return false; - } - - public void load(Properties result, URI uri) throws IOException { - } - - public String defaultSpecFor(String urlPrefix) { - return null; - } - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/LoadersManagerForTest.java b/owner/src/test/java/org/aeonbits/owner/LoadersManagerForTest.java deleted file mode 100644 index 6c722b9c3..000000000 --- a/owner/src/test/java/org/aeonbits/owner/LoadersManagerForTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.loaders.Loader; - -import java.net.URI; - -/** - * @author Luigi R. Viggiano - */ -public class LoadersManagerForTest extends LoadersManager { - @Override - public Loader findLoader(URI uri) { - return super.findLoader(uri); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/PreprocessorTest.java b/owner/src/test/java/org/aeonbits/owner/PreprocessorTest.java deleted file mode 100644 index ce1265c53..000000000 --- a/owner/src/test/java/org/aeonbits/owner/PreprocessorTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.Config.PreprocessorClasses; -import org.junit.Test; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * Issue #120 - * - * @author Luigi R. Viggiano - */ -public class PreprocessorTest { - - @PreprocessorClasses({ SkipInlineComments.class, Trim.class }) - public interface ConfigWithPreprocessors extends Config { - @DefaultValue(" 300 ") - Integer pollingPeriod(); - - @PreprocessorClasses(ToLowerCase.class) - @DefaultValue(" HelloWorld ") - String helloWorld(); - - @DefaultValue(" This is the value ! this is an inline comment # this is the inline comment too") - String skipsInlineComments(); - - @PreprocessorClasses(ToLowerCase.class) - String nullValue(); - } - - @Test - public void shouldReturnTrimmedValue() { - ConfigWithPreprocessors cfg = ConfigFactory.create(ConfigWithPreprocessors.class); - assertEquals(new Integer(300), cfg.pollingPeriod()); - } - - @Test - public void shouldReturnLowercasedTrimmedHelloWorld() { - ConfigWithPreprocessors cfg = ConfigFactory.create(ConfigWithPreprocessors.class); - assertEquals("helloworld", cfg.helloWorld()); - } - - @Test - public void shouldSkipInlineComments() { - ConfigWithPreprocessors cfg = ConfigFactory.create(ConfigWithPreprocessors.class); - assertEquals("This is the value", cfg.skipsInlineComments()); - } - - @Test - public void shouldNotThrowExceptions() { - ConfigWithPreprocessors cfg = ConfigFactory.create(ConfigWithPreprocessors.class); - assertNull(cfg.nullValue()); - } - - - // preprocessors implementation - - public static class Trim implements Preprocessor { - public String process(String input) { - return input.trim(); - } - } - - public static class ToLowerCase implements Preprocessor { - public String process(String input) { - return input.toLowerCase(); - } - } - - public static class SkipInlineComments implements Preprocessor { - public String process(String input) { - int hashTagIndex = input.indexOf('#'); - int exclamationMarkIndex = input.indexOf("!"); - if (hashTagIndex == -1 && exclamationMarkIndex == -1) - return input; // comments not present. - - int commentIndex = min(hashTagIndex, exclamationMarkIndex); - if (commentIndex == -1) - commentIndex = max(hashTagIndex, exclamationMarkIndex); - - return input.substring(0, commentIndex); - } - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/PropertiesInvocationHandlerTest.java b/owner/src/test/java/org/aeonbits/owner/PropertiesInvocationHandlerTest.java deleted file mode 100644 index c84ba16f9..000000000 --- a/owner/src/test/java/org/aeonbits/owner/PropertiesInvocationHandlerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; - -/** - * @author Luigi R. Viggiano - */ -@RunWith(MockitoJUnitRunner.class) -public class PropertiesInvocationHandlerTest { - @Spy private final Properties properties = new Properties(); - @Mock private PrintStream printStream; - @Mock private PrintWriter printWriter; - @Mock private Object proxy; - private PropertiesInvocationHandler handler; - @Mock private ScheduledExecutorService scheduler; - private LoadersManager loaders = new LoadersManagerForTest(); - private final VariablesExpander expander = new VariablesExpander(new Properties()); - - - interface Dummy extends Config {} - - @Before - public void before() { - PropertiesManager loader = new PropertiesManager(Dummy.class, properties, scheduler, expander, loaders); - handler = new PropertiesInvocationHandler(loader, null); - } - - @Test - public void testListPrintStream() throws Throwable { - handler.invoke(proxy, MyConfig.class.getDeclaredMethod("list", PrintStream.class), printStream); - verify(properties).list(eq(printStream)); - } - - @Test - public void testListPrintWriter() throws Throwable { - handler.invoke(proxy, MyConfig.class.getDeclaredMethod("list", PrintWriter.class), printWriter); - verify(properties).list(eq(printWriter)); - } - - public interface MyConfig extends Config, Accessible { - void list(PrintStream out); - void list(PrintWriter out); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/PropertiesManagerForTest.java b/owner/src/test/java/org/aeonbits/owner/PropertiesManagerForTest.java deleted file mode 100644 index d4669c955..000000000 --- a/owner/src/test/java/org/aeonbits/owner/PropertiesManagerForTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.aeonbits.owner.event.ReloadListener; - -import java.beans.PropertyChangeListener; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -/** - * @author Luigi R. Viggiano - */ -public class PropertiesManagerForTest extends PropertiesManager { - public PropertiesManagerForTest(Class clazz, Properties properties, - ScheduledExecutorService scheduler, VariablesExpander expander, LoadersManager loaders, - Map... imports) { - super(clazz, properties, scheduler, expander, loaders, imports); - } - - @Override - public Properties load() { - return super.load(); - } - - public List getReloadListeners() { - return reloadListeners; - } - - public List getPropertyChangeListeners() { - return propertyChangeListeners; - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/StrSubstitutorTest.java b/owner/src/test/java/org/aeonbits/owner/StrSubstitutorTest.java deleted file mode 100644 index 49a3c0f9c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/StrSubstitutorTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.junit.Test; - -import java.util.Properties; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Luigi R. Viggiano - */ -public class StrSubstitutorTest { - - @Test - public void shouldReturnNullWhenNullIsProvided() { - Properties props = new Properties(); - StrSubstitutor substitutor = new StrSubstitutor(props); - assertNull(substitutor.replace(null)); - } - - @Test - public void shouldReplaceVariables() { - Properties values = new Properties(); - values.setProperty("animal", "quick brown fox"); - values.setProperty("target", "lazy dog"); - String templateString = "The ${animal} jumped over the ${target}."; - StrSubstitutor sub = new StrSubstitutor(values); - String resolvedString = sub.replace(templateString); - assertEquals("The quick brown fox jumped over the lazy dog.", resolvedString); - } - - @Test - public void shouldReplaceVariablesHavingBackslashes() { - Properties values = new Properties(); - values.setProperty("animal", "quick\\brown\\fox"); - values.setProperty("target", "lazy\\dog"); - String templateString = "The\\${animal}\\jumped\\over\\the\\${target}."; - StrSubstitutor sub = new StrSubstitutor(values); - String resolvedString = sub.replace(templateString); - assertEquals("The\\quick\\brown\\fox\\jumped\\over\\the\\lazy\\dog.", resolvedString); - } - - @Test - public void shouldReplaceVariablesWithBackSlashesAndShouldWorkWithRecursion() { - Properties values = new Properties(); - values.setProperty("color", "bro\\wn"); - values.setProperty("animal", "qui\\ck\\${color}\\fo\\x"); - values.setProperty("target.attribute", "la\\zy"); - values.setProperty("target.animal", "do\\g"); - values.setProperty("target", "${target.attribute}\\${target.animal}"); - values.setProperty("template", "The ${animal} jum\\ped over the ${target}."); - values.setProperty("wrapper", "\\foo\\${template}\\bar\\"); - values.setProperty("wrapper2", "\\baz\\${wrapper}\\qux\\"); - StrSubstitutor sub = new StrSubstitutor(values); - String resolvedString = sub.replace("${wrapper2}"); - assertEquals("\\baz\\\\foo\\The qui\\ck\\bro\\wn\\fo\\x jum\\ped over the la\\zy\\do\\g.\\bar\\\\qux\\", - resolvedString); - } - - @Test - public void testRecoursiveResolution() { - Properties values = new Properties(); - values.setProperty("color", "brown"); - values.setProperty("animal", "quick ${color} fox"); - values.setProperty("target.attribute", "lazy"); - values.setProperty("target.animal", "dog"); - values.setProperty("target", "${target.attribute} ${target.animal}"); - values.setProperty("template", "The ${animal} jumped over the ${target}."); - String templateString = "${template}"; - StrSubstitutor sub = new StrSubstitutor(values); - String resolvedString = sub.replace(templateString); - assertEquals("The quick brown fox jumped over the lazy dog.", resolvedString); - } - - @Test - public void testMissingPropertyIsReplacedWithEmptyString() { - Properties values = new Properties() {{ - setProperty("foo", "fooValue"); - setProperty("baz", "bazValue"); - }}; - String template = "Test: ${foo} ${bar} ${baz} :Test"; - String expected = "Test: fooValue bazValue :Test"; - String result = new StrSubstitutor(values).replace(template); - assertEquals(expected, result); - } - - @Test - public void testParametrization() { - Properties values = new Properties() {{ - setProperty("foo", "fooValue"); - setProperty("baz", "bazValue"); - }}; - - StrSubstitutor sub = new StrSubstitutor(values); - assertEquals("foo1", sub.replace("foo%d", 1)); - assertEquals("baz", sub.replace("baz")); - assertEquals("foo.1.sfx", sub.replace("foo.%d.%s", 1, "sfx")); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/SystemVariableExpanderTest.java b/owner/src/test/java/org/aeonbits/owner/SystemVariableExpanderTest.java deleted file mode 100644 index e49348579..000000000 --- a/owner/src/test/java/org/aeonbits/owner/SystemVariableExpanderTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.junit.Before; -import org.junit.Test; - -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class SystemVariableExpanderTest { - private VariablesExpander expander; - - @Before - public void before() { - expander = new VariablesExpander(new Properties()); - } - - @Test - public void shouldNotExpandTildesInTheMiddleOfTheString() { - String result = expander.expand("foo-~-bar-~-baz"); - String expected = "foo-~-bar-~-baz"; - assertEquals(expected, result); - } - - @Test - public void shouldExpandStringsComposedByOnlyTilde() { - String result = expander.expand("~"); - String expected = System.getProperty("user.home"); - assertEquals(expected, result); - } - - @Test - public void shouldExpandStringsComposedByTildeSlash() { - String result = expander.expand("~/"); - String expected = System.getProperty("user.home") + "/"; - assertEquals(expected, result); - } - - @Test - public void shouldNotExpandTildesInTheMiddle() { - String result = expander.expand("foo-~-bar-~-baz"); - String expected = "foo-~-bar-~-baz"; - assertEquals(expected, result); - } - - @Test - public void shouldExpandFileProtocol() { - String result = expander.expand("file:~/foo/bar"); - String expected = "file:" + System.getProperty("user.home") + "/foo/bar"; - assertEquals(expected, result); - } - - @Test - public void shouldExpandJarFileProtocol() { - String result = expander.expand("jar:file:~/foo/bar"); - String expected = "jar:file:" + System.getProperty("user.home") + "/foo/bar"; - assertEquals(expected, result); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/TestConstants.java b/owner/src/test/java/org/aeonbits/owner/TestConstants.java deleted file mode 100644 index 81e26bca9..000000000 --- a/owner/src/test/java/org/aeonbits/owner/TestConstants.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -/** - * @author luigi - */ -public interface TestConstants { - String RESOURCES_DIR = "target/test-generated-resources"; -} diff --git a/owner/src/test/java/org/aeonbits/owner/UndefinedPropertiesTest.java b/owner/src/test/java/org/aeonbits/owner/UndefinedPropertiesTest.java deleted file mode 100644 index 67b04203c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/UndefinedPropertiesTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import org.junit.Test; - -import static org.junit.Assert.assertNull; - -/** - * @author Luigi R. Viggiano - */ -public class UndefinedPropertiesTest { - - public interface Person extends Config { - String name(); - int age(); - Double weight(); - } - - @Test - public void testNoValue() { - Person config = ConfigFactory.create(Person.class); - assertNull(config.name()); - } - - @Test(expected = NullPointerException.class) - public void testNoValuePrimitive() { - Person config = ConfigFactory.create(Person.class); - config.age(); - } - - @Test - public void testNoValueDouble() { - Person config = ConfigFactory.create(Person.class); - assertNull(config.weight()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/VariablesExpanderForTest.java b/owner/src/test/java/org/aeonbits/owner/VariablesExpanderForTest.java deleted file mode 100644 index 35ceb7a02..000000000 --- a/owner/src/test/java/org/aeonbits/owner/VariablesExpanderForTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.util.Properties; - -/** - * @author Luigi R. Viggiano - */ -public class VariablesExpanderForTest extends VariablesExpander { - public VariablesExpanderForTest(Properties properties) { - super(properties); - } - - @Override - public String expand(String path) { - return super.expand(path); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/cache/CacheConfigTest.java b/owner/src/test/java/org/aeonbits/owner/cache/CacheConfigTest.java deleted file mode 100644 index c603de21b..000000000 --- a/owner/src/test/java/org/aeonbits/owner/cache/CacheConfigTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.cache; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigCache; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Factory; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentMatchers; - -import java.util.Map; -import java.util.Set; - -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; - -/** - * @author Luigi R. Viggiano - */ -public class CacheConfigTest { - - static interface MyConfig extends Config {} - - @Before - public void before() { - ConfigCache.clear(); - } - - @Test - public void testGetOrCreateFromCache() { - MyConfig first = ConfigCache.getOrCreate(MyConfig.class); - MyConfig second = ConfigCache.getOrCreate(MyConfig.class); - assertSame(first, second); - } - - @Test - public void testGetOrCreateWithFactory() { - Factory factory = ConfigFactory.newInstance(); - Factory spy = spy(factory); - MyConfig first = ConfigCache.getOrCreate(spy, MyConfig.class); - MyConfig second = ConfigCache.getOrCreate(spy, MyConfig.class); - MyConfig third = ConfigCache.getOrCreate(spy, MyConfig.class); - assertSame(first, second); - assertSame(second, third); - verify(spy, times(1)).create(eq(MyConfig.class), ArgumentMatchers.[]>any()); - } - - @Test - public void testGetOrCreateUsingNameKey() { - MyConfig first = ConfigCache.getOrCreate("MyConfig", MyConfig.class); - MyConfig second = ConfigCache.getOrCreate("MyConfig", MyConfig.class); - assertSame(first, second); - } - - @Test - public void testList() { - ConfigCache.getOrCreate("MyConfig1", MyConfig.class); - ConfigCache.getOrCreate("MyConfig2", MyConfig.class); - ConfigCache.getOrCreate("MyConfig3", MyConfig.class); - Set keys = ConfigCache.list(); - assertTrue(keys.contains("MyConfig1")); - assertTrue(keys.contains("MyConfig2")); - assertTrue(keys.contains("MyConfig3")); - assertTrue(3 == keys.size()); - } - - @Test - public void testRemoveUsingClassAsKey() { - MyConfig first = ConfigCache.getOrCreate(MyConfig.class); - Config removed = ConfigCache.remove(MyConfig.class); - assertNotNull(removed); - - MyConfig second = ConfigCache.getOrCreate(MyConfig.class); - MyConfig third = ConfigCache.getOrCreate(MyConfig.class); - - assertNotSame(first, second); - assertSame(second, third); - } - - @Test - public void testRemoveUsingNameKey() { - MyConfig first = ConfigCache.getOrCreate("foo", MyConfig.class); - - Config removed = ConfigCache.remove("foo"); - assertNotNull(removed); - - MyConfig second = ConfigCache.getOrCreate("foo", MyConfig.class); - MyConfig third = ConfigCache.getOrCreate("foo", MyConfig.class); - - assertNotSame(first, second); - assertSame(second, third); - } - - @Test - public void testRemove() { - MyConfig first = ConfigCache.getOrCreate("MyConfig", MyConfig.class); - Config removed = ConfigCache.remove("MyConfig"); - MyConfig second = ConfigCache.getOrCreate("MyConfig", MyConfig.class); - assertNotSame(first, second); - assertSame(first, removed); - } - - @Test - public void testClear() { - MyConfig first = ConfigCache.getOrCreate("MyConfig", MyConfig.class); - ConfigCache.clear(); - MyConfig second = ConfigCache.getOrCreate("MyConfig", MyConfig.class); - assertNotSame(first, second); - } - - @Test - public void testGetWhenInstanceDoesNotExists() { - MyConfig instance = ConfigCache.get(MyConfig.class); - assertNull(instance); - } - - @Test - public void testGetWhenInstanceExists() { - MyConfig created = ConfigCache.getOrCreate(MyConfig.class); - MyConfig got = ConfigCache.get(MyConfig.class); - assertSame(created, got); - } - - @Test - public void testAdd() { - MyConfig dummy = ConfigFactory.create(MyConfig.class); - MyConfig previous = ConfigCache.add("foo", dummy); - MyConfig cached = ConfigCache.getOrCreate("foo", MyConfig.class); - - assertNull(previous); - assertSame(dummy, cached); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/crypto/CryptoConfigTest.java b/owner/src/test/java/org/aeonbits/owner/crypto/CryptoConfigTest.java deleted file mode 100644 index 6fc755242..000000000 --- a/owner/src/test/java/org/aeonbits/owner/crypto/CryptoConfigTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.aeonbits.owner.crypto; - -import java.util.List; -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import static org.aeonbits.owner.Config.*; - -public class CryptoConfigTest { - public static final String SECRET_KEY = "ABCDEFGH12345678"; - public static final String PASSWORD_EXPECTED = "This is my key."; - public static final String SALUTATION_EXPECTED = "Good Morning"; - - @DecryptorClass(Decryptor1.class) - public interface SampleConfig extends Config { - String hello(String param); - - @DefaultValue("Bohemian Rapsody - Queen") - String favoriteSong(); - - String unspecifiedProperty(); - - @Key("server.http.port") - int httpPort(); - - @Key("salutation.text") - @DefaultValue("Good Morning") - String salutation(); - - @DefaultValue("foo") - void voidMethodWithValue(); - - void voidMethodWithoutValue(); - - @Key("crypto.password") - @EncryptedValue - @DefaultValue("tzH7IKLCVc0AC72fh5DiZA==") - String password(); - - @Key("crypto.list") - @EncryptedValue - @Separator(",") - @DefaultValue("Pfzoiet5E5zN2/7tfgrGLQ==") - List cryptoList(); - - @Key("encryptedValue") - @DefaultValue("tzH7IKLCVc0AC72fh5DiZA==") - String encryptedValue(); - - @Key("password.variable.expanded") - @EncryptedValue - @DefaultValue("${encryptedValue}") - String passwordVariableExpanded(); - } - - - /** - * We test that the decrypt works as expected. - */ - @Test - public void passwordDecryptedTest() { - SampleConfig config = ConfigFactory.create( SampleConfig.class ); - String decryptedPassword = config.password(); - assertEquals( "Property password wasn't decrypted.", PASSWORD_EXPECTED, decryptedPassword ); - } - - /** - * This test checks that the decrypted value is not cached. - * So we recover it twice. - */ - @Test - public void passwordDecryptedTwiceTest() { - SampleConfig config = ConfigFactory.create( SampleConfig.class ); - String decryptedPassword = config.password(); - decryptedPassword = config.password(); - assertEquals( "May be property password was decrypted twice.", PASSWORD_EXPECTED, decryptedPassword ); - } - - @Test - public void listDecryptedTest() { - SampleConfig config = ConfigFactory.create( SampleConfig.class ); - List decryptedList = config.cryptoList(); - List expectedList = Arrays.asList( "1", "2", "3", "4"); - assertEquals( "KKKK", expectedList, decryptedList ); - } - - /** - * We test the value of non encripted properties. - */ - @Test - public void salutationNotDecryptedTest() { - SampleConfig config = ConfigFactory.create( SampleConfig.class ); - String salutation = config.salutation(); - assertEquals( "Salutation value is not expected", SALUTATION_EXPECTED, salutation ); - } - - /** - * This test checks that the decrypted value is not cached. - * So we recover it twice. - */ - @Test - public void passwordDecryptedWhenVariableSubstitutionIsSet() { - SampleConfig config = ConfigFactory.create( SampleConfig.class ); - String decryptedPassword = config.passwordVariableExpanded(); - assertEquals( "May be property password was decrypted twice.", PASSWORD_EXPECTED, decryptedPassword ); - } - - public static class Decryptor1 extends SampleDecryptor { - public Decryptor1() { - super( "AES", SECRET_KEY ); - } - } - - public static class Decryptor2 extends SampleDecryptor { - public Decryptor2() { - super( "AES", SECRET_KEY + SECRET_KEY ); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/crypto/CryptoUtils.java b/owner/src/test/java/org/aeonbits/owner/crypto/CryptoUtils.java deleted file mode 100644 index e8c376833..000000000 --- a/owner/src/test/java/org/aeonbits/owner/crypto/CryptoUtils.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.aeonbits.owner.crypto; - - -public final class CryptoUtils { - public static StandardEncryptor newEncryptionSilently( String algorithm, String secretKey ) { - try { - return newEncryption( algorithm, secretKey ); - } catch ( Exception cause ) { - cause.printStackTrace(); - } - return null; - } - public static StandardEncryptor newEncryption( String algorithm, String secretKey ) - throws Exception { - return StandardEncryptor.newInstance( algorithm, secretKey ); - } - - public static Decryptor newDecryptor( String algorithm, String secretKey ) - throws Exception { - return StandardEncryptor.newInstance( algorithm, secretKey ); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/crypto/SampleDecryptor.java b/owner/src/test/java/org/aeonbits/owner/crypto/SampleDecryptor.java deleted file mode 100644 index b5841857f..000000000 --- a/owner/src/test/java/org/aeonbits/owner/crypto/SampleDecryptor.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.aeonbits.owner.crypto; - -public class SampleDecryptor extends AbstractEncryptor { - private final StandardEncryptor encrypter; - - public SampleDecryptor( String algorithm, String secretKey ) { - this.encrypter = StandardEncryptor.newInstance( "AES", secretKey ); - } - - @Override - public String decrypt( String value ) { - try { - return this.encrypter.decrypt( value ); - } catch ( Exception cause ) { - throw new IllegalArgumentException( cause.getMessage(), cause ); - } - } - - @Override - public String decrypt( String value, String defaultValue ) { - try { - return decrypt( value ); - } catch ( Exception cause ){ - return defaultValue; - } - } - - @Override - public String encrypt( String value ) { - try { - return this.encrypter.encrypt( value ); - } catch ( Exception cause ) { - throw new IllegalArgumentException( cause.getMessage(), cause ); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/crypto/StandardEncryptor.java b/owner/src/test/java/org/aeonbits/owner/crypto/StandardEncryptor.java deleted file mode 100644 index 457b761a3..000000000 --- a/owner/src/test/java/org/aeonbits/owner/crypto/StandardEncryptor.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.aeonbits.owner.crypto; - -import org.aeonbits.owner.util.Base64; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import java.io.UnsupportedEncodingException; -import java.security.Key; - -public class StandardEncryptor extends AbstractEncryptor { - private final String algorithm; - private final String encoding; - private final byte[] secretKey; - private final int secretKeySize; - - public StandardEncryptor( String algorithm, String secretKey, String encoding, int secretKeySize ) { - try { - this.secretKeySize = secretKeySize; - this.algorithm = algorithm; - this.encoding = encoding; - this.secretKey = secretKey.getBytes( encoding ); - } catch (UnsupportedEncodingException cause) { - throw new IllegalArgumentException( cause.getMessage(), cause); - } - } - - public String getAlgorithm() { - return this.algorithm; - } - - public String encrypt( String plainData ) { - try { - Key key = generateKey(); - Cipher c = Cipher.getInstance( this.algorithm ); - c.init(Cipher.ENCRYPT_MODE, key); - byte[] encVal = c.doFinal( plainData.getBytes( this.encoding ) ); - String encryptedValue = Base64.encode( encVal ); - return encryptedValue; - } catch ( Exception cause ) { - throw new IllegalArgumentException( cause.getMessage(), cause ); - } - } - - public String decrypt(String encryptedData) throws IllegalArgumentException { - try { - Key key = generateKey(); - Cipher c = Cipher.getInstance( this.algorithm ); - c.init(Cipher.DECRYPT_MODE, key); - byte[] decodedValue = Base64.decode(encryptedData); - byte[] decValue = c.doFinal(decodedValue); - String decryptedValue = new String(decValue, this.encoding ); - return decryptedValue; - } catch ( Exception cause ){ - throw new IllegalArgumentException( cause.getMessage(), cause ); - } - } - - private Key generateKey() throws Exception { - return new SecretKeySpec( this.secretKey, this.getAlgorithm() ); - } - - public static StandardEncryptor newInstance(String algorithm, String secretKey ) { - return newInstance( algorithm, secretKey, "UTF-8", secretKey.length() ); - } - - public static StandardEncryptor newInstance(String algorithm, String secretKey, String encoding, int secretKeySize ) { - return new StandardEncryptor( algorithm, secretKey, encoding, secretKeySize ); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/debugging/ToStringTest.java b/owner/src/test/java/org/aeonbits/owner/debugging/ToStringTest.java deleted file mode 100644 index 824c2c237..000000000 --- a/owner/src/test/java/org/aeonbits/owner/debugging/ToStringTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.debugging; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * @author Luigi R. Viggiano - */ -public class ToStringTest { - - interface MyConfig extends Config { - @Key("max.threads") - @DefaultValue("25") - int maxThreads(); - - @Key("max.folders") - @DefaultValue("99") - int maxFolders(); - - @Key("default.name") - @DefaultValue("untitled") - String defaultName(); - } - - @Test - public void toStringTest() { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - String toString = cfg.toString(); - assertTrue(toString.startsWith("{")); - assertTrue(toString.endsWith("}")); - assertTrue(toString.contains("default.name=untitled")); - assertTrue(toString.contains("max.folders=99")); - assertTrue(toString.contains("max.threads=25")); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/event/EventListenerOnReloadTest.java b/owner/src/test/java/org/aeonbits/owner/event/EventListenerOnReloadTest.java deleted file mode 100644 index 7197e3ea5..000000000 --- a/owner/src/test/java/org/aeonbits/owner/event/EventListenerOnReloadTest.java +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Mutable; -import org.aeonbits.owner.Reloadable; -import org.aeonbits.owner.TestConstants; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InOrder; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.beans.PropertyChangeEvent; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Properties; - -import static org.aeonbits.owner.util.UtilTest.fileFromURI; -import static org.aeonbits.owner.util.UtilTest.ignoreAndReturnNull; -import static org.aeonbits.owner.util.UtilTest.save; -import static org.aeonbits.owner.event.PropertyChangeMatcher.matches; -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.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; - -/** - * @author Luigi R. Viggiano - */ -@RunWith(MockitoJUnitRunner.class) -public class EventListenerOnReloadTest implements TestConstants { - private static final String SPEC = "file:" + RESOURCES_DIR + "/EventListenerOnReloadTest.properties"; - private File target; - @Mock - private TransactionalPropertyChangeListener propertyChangeListener; - @Mock - private TransactionalReloadListener reloadListener; - private MyConfig cfg; - - @Before - public void before() throws URISyntaxException { - target = fileFromURI(SPEC); - target.delete(); - cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - cfg.addReloadListener(reloadListener); - } - - @After - public void after() { - target.delete(); - } - - @Sources(SPEC) - interface MyConfig extends Mutable, Reloadable { - @DefaultValue("5") - Integer someInteger(); - - @DefaultValue("foobar") - String someString(); - - @DefaultValue("3.14") - Double someDouble(); - - String nullsByDefault(); - } - - @Test - public void testPropertyChangeListenerOnReloadWhenRollbackBatchException() throws Throwable { - - save(target, new Properties() {{ - setProperty("someInteger", "5"); - setProperty("someString", "bazbar"); - setProperty("someDouble", "2.718"); - setProperty("nullsByDefault", "NotNullNow"); - }}); - - doNothing().doNothing().doThrow(new RollbackBatchException()) - .when(propertyChangeListener).beforePropertyChange(any(PropertyChangeEvent.class)); - - cfg.reload(); - - assertEquals(new Integer(5), cfg.someInteger()); - assertEquals("foobar", cfg.someString()); - assertEquals(new Double("3.14"), cfg.someDouble()); - assertNull(cfg.nullsByDefault()); - } - - - @Test - public void testPropertyChangeListenerOnReloadWhenRollbackOperationException() throws Throwable { - - save(target, new Properties() {{ - setProperty("someString", "bazbar"); - setProperty("someDouble", "2.718"); - setProperty("nullsByDefault", "NotNullNow"); - }}); - - PropertyChangeEvent eventToRollback = new PropertyChangeEvent(cfg, "someString", "foobar", "bazbar"); - - doThrow(new RollbackOperationException()) - .when(propertyChangeListener).beforePropertyChange(argThat(matches(eventToRollback))); - - cfg.reload(); - - assertEquals(new Integer(5), cfg.someInteger()); - assertEquals("foobar", cfg.someString()); - assertEquals(new Double("2.718"), cfg.someDouble()); - assertEquals("NotNullNow", cfg.nullsByDefault()); - } - - @Test - public void testPropertyChangeListenerOnReloadWhenNoChangesHaveBeenMade() throws Throwable { - cfg.reload(); - verifyZeroInteractions(propertyChangeListener); - } - - @Test - public void testPropertyChangeListenerOnReloadWhenChangeHappen() throws Throwable { - save(target, new Properties() {{ - setProperty("someInteger", "5"); - setProperty("someString", "bazbar"); - setProperty("someDouble", "2.718"); - setProperty("nullsByDefault", "NotNullNow"); - }}); - - cfg.reload(); - - verify(propertyChangeListener, times(3)).beforePropertyChange(any(PropertyChangeEvent.class)); - verify(propertyChangeListener, times(3)).propertyChange(any(PropertyChangeEvent.class)); - - PropertyChangeEvent someStringChange = new PropertyChangeEvent(cfg, "someString", "foobar", "bazbar"); - PropertyChangeEvent someDoubleChange = new PropertyChangeEvent(cfg, "someDouble", "3.14", "2.718"); - PropertyChangeEvent nullByDefaultChange = new PropertyChangeEvent(cfg, "nullsByDefault", null, "NotNullNow"); - - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(someStringChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(someStringChange))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(someDoubleChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(someDoubleChange))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(nullByDefaultChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(nullByDefaultChange))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(someStringChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(someDoubleChange))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(someDoubleChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(someStringChange))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(someStringChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(nullByDefaultChange))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(someDoubleChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(nullByDefaultChange))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(nullByDefaultChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(someStringChange))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(nullByDefaultChange))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(someDoubleChange))); - - verifyNoMoreInteractions(propertyChangeListener); - } - - @Test - public void testReloadListenerIsInvokedOnReload() throws IOException, RollbackBatchException { - save(target, new Properties() {{ - setProperty("someInteger", "5"); - setProperty("someString", "bazbar"); - setProperty("someDouble", "2.718"); - setProperty("nullsByDefault", "NotNullNow"); - }}); - - cfg.reload(); - - InOrder inOrder = inOrder(reloadListener); - inOrder.verify(reloadListener, times(1)).beforeReload(any(ReloadEvent.class)); - inOrder.verify(reloadListener, times(1)).reloadPerformed(any(ReloadEvent.class)); - verifyNoMoreInteractions(reloadListener); - - assertEquals(new Integer(5), cfg.someInteger()); - assertEquals("bazbar", cfg.someString()); - assertEquals(new Double("2.718"), cfg.someDouble()); - assertEquals("NotNullNow", cfg.nullsByDefault()); - - } - - @Test - public void testReloadWhenRollbackBatchExceptionIsThrown() throws Throwable { - save(target, new Properties() {{ - setProperty("someInteger", "5"); - setProperty("someString", "bazbar"); - setProperty("someDouble", "2.718"); - setProperty("nullsByDefault", "NotNullNow"); - }}); - - doThrow(RollbackBatchException.class).when(reloadListener).beforeReload(any(ReloadEvent.class)); - - cfg.reload(); - - assertEquals(new Integer(5), cfg.someInteger()); - assertEquals("foobar", cfg.someString()); - assertEquals(new Double("3.14"), cfg.someDouble()); - assertNull(cfg.nullsByDefault()); - } - - @Test - public void testReloadEventIsNotModifiable() throws Throwable { - save(target, new Properties() {{ - setProperty("someInteger", "5"); - setProperty("someString", "bazbar"); - setProperty("someDouble", "2.718"); - setProperty("nullsByDefault", "NotNullNow"); - }}); - - final ReloadEvent[] beforeEvent = new ReloadEvent[1]; - final ReloadEvent[] afterEvent = new ReloadEvent[1]; - - cfg.addReloadListener(new TransactionalReloadListener() { - public void beforeReload(ReloadEvent event) throws RollbackBatchException { - beforeEvent[0] = event; - } - - public void reloadPerformed(ReloadEvent event) { - afterEvent[0] = event; - } - }); - - cfg.reload(); - - assertNotNull(beforeEvent[0]); - assertNotNull(afterEvent[0]); - assertSame(beforeEvent[0], afterEvent[0]); - - try { - beforeEvent[0].getEvents().clear(); - fail("it should return an unmodifiable collection"); - } catch (UnsupportedOperationException x) { - ignoreAndReturnNull(); - } - - try { - beforeEvent[0].getOldProperties().clear(); - fail("it should return an unmodifiable collection"); - } catch (UnsupportedOperationException x) { - ignoreAndReturnNull(); - } - - try { - beforeEvent[0].getNewProperties().clear(); - fail("it should return an unmodifiable collection"); - } catch (UnsupportedOperationException x) { - ignoreAndReturnNull(); - } - } - - @Test - public void testFullReloadCycle() throws IOException { - final boolean[] reloadPerformed = new boolean[] {false}; - cfg.addReloadListener(new TransactionalReloadListener() { - - public void beforeReload(ReloadEvent event) throws RollbackBatchException { - String notAllowedValue = "42"; - String newSomeInteger = event.getNewProperties().getProperty("someInteger"); - if (notAllowedValue.equals(newSomeInteger)) - throw new RollbackBatchException("42 is not allowed for property 'someInteger'"); - } - - public void reloadPerformed(ReloadEvent event) { - reloadPerformed[0] = true; - } - - }); - - save(target, new Properties() {{ - setProperty("someInteger", "41"); - setProperty("someString", "bazbar"); - setProperty("someDouble", "2.718"); - setProperty("nullsByDefault", "NotNullNow"); - }}); - - cfg.reload(); - - assertTrue(reloadPerformed[0]); - assertEquals(new Integer(41), cfg.someInteger()); - assertEquals("bazbar", cfg.someString()); - assertEquals(new Double("2.718"), cfg.someDouble()); - assertNotNull(cfg.nullsByDefault()); - - reloadPerformed[0] = false; - - save(target, new Properties() {{ - setProperty("someInteger", "42"); - setProperty("someString", "blahblah"); - setProperty("someDouble", "1.234"); - }}); - - cfg.reload(); - - assertFalse(reloadPerformed[0]); - assertEquals(new Integer(41), cfg.someInteger()); - assertEquals("bazbar", cfg.someString()); - assertEquals(new Double("2.718"), cfg.someDouble()); - assertNotNull(cfg.nullsByDefault()); - - } - - - @Test - public void testFullPropertyChangeCycleCycle() throws IOException { - final boolean[] reloadPerformed = new boolean[] {false}; - - cfg.addPropertyChangeListener("someInteger", - new TransactionalPropertyChangeListener() { - public void beforePropertyChange(PropertyChangeEvent event) - throws RollbackOperationException, RollbackBatchException { - String notAllowedValue = "88"; - String makesEverythingToRollback = "42"; - - String newSomeInteger = (String)event.getNewValue(); - if (notAllowedValue.equals(newSomeInteger)) - throw new RollbackOperationException("88 is not allowed for property 'someInteger', " + - "the single property someInteger is rolled back"); - - if (makesEverythingToRollback.equals(newSomeInteger)) - throw new RollbackBatchException("42 is not allowed for property 'someInteger', " + - "the whole event is rolled back"); - - } - - public void propertyChange(PropertyChangeEvent evt) { - reloadPerformed[0] = true; - } - }); - - save(target, new Properties() {{ - setProperty("someInteger", "41"); - setProperty("someString", "bazbar"); - setProperty("someDouble", "2.718"); - setProperty("nullsByDefault", "NotNullNow"); - }}); - - cfg.reload(); - - assertTrue(reloadPerformed[0]); - assertEquals(new Integer(41), cfg.someInteger()); - assertEquals("bazbar", cfg.someString()); - assertEquals(new Double("2.718"), cfg.someDouble()); - assertNotNull(cfg.nullsByDefault()); - - reloadPerformed[0] = false; - - cfg.setProperty("someInteger", "55"); - assertTrue(reloadPerformed[0]); - assertEquals(new Integer(55), cfg.someInteger()); - - reloadPerformed[0] = false; - - - cfg.setProperty("someInteger", "88"); - // 88 is rolled back. - assertFalse(reloadPerformed[0]); - assertEquals(new Integer(55), cfg.someInteger()); - - reloadPerformed[0] = false; - - save(target, new Properties() {{ - setProperty("someInteger", "42"); - setProperty("someString", "blahblah"); - setProperty("someDouble", "1.234"); - }}); - - cfg.reload(); - - assertFalse(reloadPerformed[0]); - assertEquals(new Integer(55), cfg.someInteger()); - assertEquals("bazbar", cfg.someString()); - assertEquals(new Double("2.718"), cfg.someDouble()); - assertNotNull(cfg.nullsByDefault()); - - - reloadPerformed[0] = false; - - save(target, new Properties() {{ - setProperty("someInteger", "88"); - setProperty("someString", "this is not rolled back"); - setProperty("someDouble", "1.2345"); - }}); - - cfg.reload(); - - assertFalse(reloadPerformed[0]); - // only someInteger=88 is rolled back - assertEquals(new Integer(55), cfg.someInteger()); - assertEquals("this is not rolled back", cfg.someString()); - assertEquals(new Double("1.2345"), cfg.someDouble()); - assertNull(cfg.nullsByDefault()); - - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/event/EventListenerTest.java b/owner/src/test/java/org/aeonbits/owner/event/EventListenerTest.java deleted file mode 100644 index 4e3c25462..000000000 --- a/owner/src/test/java/org/aeonbits/owner/event/EventListenerTest.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.LoadersManagerForTest; -import org.aeonbits.owner.Mutable; -import org.aeonbits.owner.PropertiesManagerForTest; -import org.aeonbits.owner.VariablesExpanderForTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InOrder; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; - -import java.beans.PropertyChangeEvent; -import java.io.ByteArrayInputStream; -import java.io.StringReader; -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -import static org.aeonbits.owner.event.PropertyChangeMatcher.matches; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.collection.IsEmptyCollection.empty; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - -/** - * @author Luigi R. Viggiano - */ -@RunWith(MockitoJUnitRunner.class) -public class EventListenerTest { - - @Mock - private TransactionalPropertyChangeListener propertyChangeListener; - - @Mock - private Properties props; - - @Mock - private ScheduledExecutorService scheduler; - - @Mock - private VariablesExpanderForTest expander; - - private LoadersManagerForTest loaders = new LoadersManagerForTest(); - - @Mock - private ReloadListener reloadListener; - private PropertiesManagerForTest propertiesManager; - - interface MyConfig extends Mutable { - @DefaultValue("13") - String primeNumber(); - } - - @Test - public void testSetProperty() throws Throwable { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - - assertEquals("13", cfg.primeNumber()); - - cfg.setProperty("primeNumber", "17"); - assertEquals("17", cfg.primeNumber()); - - PropertyChangeEvent expectedEvent = new PropertyChangeEvent(cfg, "primeNumber", "13", "17"); - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(expectedEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(expectedEvent))); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void testSetPropertyWhenValuesAreEqual() throws Throwable { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - assertEquals("13", cfg.primeNumber()); - - cfg.setProperty("primeNumber", "13"); - assertEquals("13", cfg.primeNumber()); - - verifyZeroInteractions(propertyChangeListener); - } - - @Test - public void testSetPropertyThrowingRollbackOperationException() throws Throwable { - doThrow(new RollbackOperationException()).when(propertyChangeListener).beforePropertyChange(any - (PropertyChangeEvent.class)); - MyConfig cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - - assertEquals("13", cfg.primeNumber()); - - cfg.setProperty("primeNumber", "17"); // is rolled back! - assertEquals("13", cfg.primeNumber()); - - PropertyChangeEvent expectedEvent = new PropertyChangeEvent(cfg, "primeNumber", "13", "17"); - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(expectedEvent))); - inOrder.verify(propertyChangeListener, never()).propertyChange(argThat(matches(expectedEvent))); - inOrder.verifyNoMoreInteractions(); - } - - - @Test - public void testRemoveProperty() throws Throwable { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - - assertEquals("13", cfg.primeNumber()); - - cfg.removeProperty("primeNumber"); - assertNull(cfg.primeNumber()); - - PropertyChangeEvent expectedEvent = new PropertyChangeEvent(cfg, "primeNumber", "13", null); - - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(expectedEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(expectedEvent))); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void testRemovePropertyThrowingRollbackOperationException() throws Throwable { - doThrow(new RollbackOperationException()).when(propertyChangeListener).beforePropertyChange(any - (PropertyChangeEvent.class)); - - MyConfig cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - - assertEquals("13", cfg.primeNumber()); - - cfg.removeProperty("primeNumber"); // rolled back! - thingsAreRolledBack(cfg); - } - - @Test - public void testRemovePropertyChangeListener() throws Throwable { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - - assertEquals("13", cfg.primeNumber()); - - cfg.setProperty("primeNumber", "17"); - assertEquals("17", cfg.primeNumber()); - - cfg.removePropertyChangeListener(propertyChangeListener); - - cfg.setProperty("primeNumber", "3"); - assertEquals("3", cfg.primeNumber()); - - PropertyChangeEvent expectedEvent = new PropertyChangeEvent(cfg, "primeNumber", "13", "17"); - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(expectedEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(expectedEvent))); - inOrder.verifyNoMoreInteractions(); - } - - - @Test - public void testClear() throws Throwable { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - - cfg.clear(); - - assertNull(cfg.primeNumber()); - - PropertyChangeEvent expectedEvent = new PropertyChangeEvent(cfg, "primeNumber", "13", null); - - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(expectedEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(expectedEvent))); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void testClearOnRollbackOperationException() throws Throwable { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - cfg.addPropertyChangeListener(propertyChangeListener); - - doThrow(new RollbackOperationException()).when(propertyChangeListener).beforePropertyChange(any - (PropertyChangeEvent.class)); - - cfg.clear(); - - thingsAreRolledBack(cfg); - } - - private void thingsAreRolledBack(MyConfig cfg) throws RollbackOperationException, RollbackBatchException { - - assertEquals("13", cfg.primeNumber()); - - PropertyChangeEvent expectedEvent = new PropertyChangeEvent(cfg, "primeNumber", "13", null); - - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(expectedEvent))); - inOrder.verify(propertyChangeListener, never()).propertyChange(argThat(matches(expectedEvent))); - inOrder.verifyNoMoreInteractions(); - } - - interface Server extends Mutable { - - @DefaultValue("localhost") - String hostname(); - - @DefaultValue("8080") - int port(); - - @DefaultValue("http") - String protocol(); - } - - @Test - public void testClearOnRollbackBatchException() throws Throwable { - Server cfg = ConfigFactory.create(Server.class); - cfg.addPropertyChangeListener(propertyChangeListener); - - doNothing().doNothing().doThrow(new RollbackBatchException()) - .when(propertyChangeListener).beforePropertyChange(any(PropertyChangeEvent.class)); - - cfg.clear(); - - assertEquals("localhost", cfg.hostname()); - assertEquals(8080, cfg.port()); - assertEquals("http", cfg.protocol()); - - verify(propertyChangeListener, times(3)).beforePropertyChange(any(PropertyChangeEvent.class)); - verify(propertyChangeListener, never()).propertyChange(any(PropertyChangeEvent.class)); - } - - - @Test - public void testLoadInputStream() throws Throwable { - Server server = ConfigFactory.create(Server.class); - server.addPropertyChangeListener(propertyChangeListener); - String properties = getPropertiesTextForLoad(); - server.load(new ByteArrayInputStream(properties.getBytes())); - verifyLoad(server); - } - - @Test - public void testLoadReader() throws Throwable { - Server server = ConfigFactory.create(Server.class); - server.addPropertyChangeListener(propertyChangeListener); - String properties = getPropertiesTextForLoad(); - server.load(new StringReader(properties)); - verifyLoad(server); - } - - private String getPropertiesTextForLoad() { - return "hostname = foobar\n" + - "port = 80\n" + - "protocol = http\n"; - } - - @Test - public void testPartialClearOnRollbackOperationException() throws Throwable { - Server server = ConfigFactory.create(Server.class); - - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - PropertyChangeEvent evt = (PropertyChangeEvent) invocation.getArguments()[0]; - if (evt.getPropertyName().equals("port")) - throw new RollbackOperationException(); - return null; - } - }).when(propertyChangeListener).beforePropertyChange(any(PropertyChangeEvent.class)); - - server.addPropertyChangeListener(propertyChangeListener); - - server.clear(); - - assertNull(server.hostname()); - assertNull(server.protocol()); - assertEquals(8080, server.port()); - - PropertyChangeEvent hostnameChangeEvent = new PropertyChangeEvent(server, "hostname", "localhost", null); - PropertyChangeEvent protocolChangeEvent = new PropertyChangeEvent(server, "protocol", "http", null); - - verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(hostnameChangeEvent))); - verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(protocolChangeEvent))); - verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(hostnameChangeEvent))); - verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(protocolChangeEvent))); - - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(hostnameChangeEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(hostnameChangeEvent))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(protocolChangeEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(protocolChangeEvent))); - - } - - @Test - public void testLoadReaderOnRollbackBatchException() throws Throwable { - Server server = prepareLoadForRollbackBatch(); - String properties = getPropertiesAsText(); - server.load(new StringReader(properties)); - verifyLoadIsRolledBackCompletely(server); - } - - @Test - public void testLoadInputStreamOnRollbackBatchException() throws Throwable { - Server server = prepareLoadForRollbackBatch(); - String properties = getPropertiesAsText(); - server.load(new ByteArrayInputStream(properties.getBytes())); - verifyLoadIsRolledBackCompletely(server); - } - - private void verifyLoadIsRolledBackCompletely(Server server) throws RollbackBatchException, - RollbackOperationException { - assertEquals("localhost", server.hostname()); - assertEquals(8080, server.port()); - assertEquals("http", server.protocol()); - verify(propertyChangeListener, times(3)).beforePropertyChange(any(PropertyChangeEvent.class)); - verify(propertyChangeListener, never()).propertyChange(any(PropertyChangeEvent.class)); - } - - private String getPropertiesAsText() { - return "hostname = foobar\n" + - "port = 80\n" + - "protocol = ftp\n"; - } - - private Server prepareLoadForRollbackBatch() throws RollbackOperationException, RollbackBatchException { - Server server = ConfigFactory.create(Server.class); - server.addPropertyChangeListener(propertyChangeListener); - - doNothing().doNothing().doThrow(new RollbackBatchException()) - .when(propertyChangeListener).beforePropertyChange(any(PropertyChangeEvent.class)); - return server; - } - - private void verifyLoad(Server server) throws RollbackOperationException, RollbackBatchException { - assertEquals("foobar", server.hostname()); - assertEquals(80, server.port()); - assertEquals("http", server.protocol()); - - PropertyChangeEvent hostnameChangeEvent = new PropertyChangeEvent(server, "hostname", "localhost", "foobar"); - PropertyChangeEvent portChangeEvent = new PropertyChangeEvent(server, "port", "8080", "80"); - - verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(hostnameChangeEvent))); - verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(portChangeEvent))); - verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(hostnameChangeEvent))); - verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(portChangeEvent))); - - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(hostnameChangeEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(hostnameChangeEvent))); - - inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(portChangeEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(portChangeEvent))); - } - - @Test - public void testAddPropertyChangeListenerWithPropertyName() throws Throwable { - - Server cfg = ConfigFactory.create(Server.class); - cfg.addPropertyChangeListener("hostname", propertyChangeListener); - - cfg.setProperty("protocol", "ssh"); - cfg.setProperty("hostname", "google.com"); - cfg.setProperty("port", "22"); - - PropertyChangeEvent expectedEvent = new PropertyChangeEvent(cfg, "hostname", "localhost", "google.com"); - InOrder inOrder = inOrder(propertyChangeListener); - inOrder.verify(propertyChangeListener, times(1)).beforePropertyChange(argThat(matches(expectedEvent))); - inOrder.verify(propertyChangeListener, times(1)).propertyChange(argThat(matches(expectedEvent))); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void testRemovePropertyChangeListenerWithPropertyName() throws Throwable { - Server cfg = ConfigFactory.create(Server.class); - cfg.addPropertyChangeListener("hostname", propertyChangeListener); - cfg.removePropertyChangeListener(propertyChangeListener); - - cfg.setProperty("protocol", "ssh"); - cfg.setProperty("hostname", "google.com"); - cfg.setProperty("port", "22"); - - verifyZeroInteractions(propertyChangeListener); - } - - @Before - public void before() { - propertiesManager = new PropertiesManagerForTest(Server.class, props, scheduler, - new VariablesExpanderForTest(new Properties()), loaders); - } - - @Test - public void testRemoveReloadListenerNull() throws Throwable { - propertiesManager.addReloadListener(reloadListener); - propertiesManager.removeReloadListener(null); // no nullpex should happen - assertEquals(1, propertiesManager.getReloadListeners().size()); - } - - @Test - public void testRemoveReloadListenerThatIsNotThere() throws Throwable { - assertThat(propertiesManager.getReloadListeners(), is(empty())); - propertiesManager.removeReloadListener(reloadListener); - assertThat(propertiesManager.getReloadListeners(), is(empty())); - } - - @Test - public void testRemovePropertyChangeListenerNull() throws Throwable { - propertiesManager.addPropertyChangeListener(propertyChangeListener); - propertiesManager.removePropertyChangeListener(null); - assertEquals(1, propertiesManager.getPropertyChangeListeners().size()); - } - - @Test - public void testRemovePropertyChangeThatIsNotThere() throws Throwable { - assertThat(propertiesManager.getPropertyChangeListeners(), is(empty())); - propertiesManager.removePropertyChangeListener(propertyChangeListener); - assertThat(propertiesManager.getPropertyChangeListeners(), is(empty())); - } - - @Test - public void testAddPropertyChangeListenerNull() throws Throwable { - propertiesManager.addPropertyChangeListener(null); - assertTrue(propertiesManager.getPropertyChangeListeners().isEmpty()); - } - - @Test - public void testAddReloadListenerNull() throws Throwable { - propertiesManager.addReloadListener(null); - assertTrue(propertiesManager.getReloadListeners().isEmpty()); - } - - @Test - public void testAddPropertyChangeListenerNullSomething() throws Throwable { - propertiesManager.addPropertyChangeListener(null, propertyChangeListener); - assertTrue(propertiesManager.getPropertyChangeListeners().isEmpty()); - } - - @Test - public void testAddPropertyChangeListenerSomethingNull() throws Throwable { - propertiesManager.addPropertyChangeListener("something", null); - assertTrue(propertiesManager.getPropertyChangeListeners().isEmpty()); - } - - @Test - public void testAddPropertyChangeListenerNullNull() throws Throwable { - propertiesManager.addPropertyChangeListener(null, null); - assertTrue(propertiesManager.getPropertyChangeListeners().isEmpty()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/event/ExceptionTests.java b/owner/src/test/java/org/aeonbits/owner/event/ExceptionTests.java deleted file mode 100644 index 6ca87c76f..000000000 --- a/owner/src/test/java/org/aeonbits/owner/event/ExceptionTests.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import org.junit.Test; - -/** - * @author Luigi R. Viggiano - */ -public class ExceptionTests { - - @Test - public void testRollbackBatchExceptionConstruction() { - // just ensure all constructors are available on the class and the hierarchy is correct - RollbackException ex = new RollbackBatchException(); - new RollbackBatchException("message"); - new RollbackBatchException(new Exception()); - new RollbackBatchException("message", new Exception()); - } - - @Test - public void testRollbackOperationExceptionConstruction() { - // just ensure all constructors are available on the class and the hierarchy is correct - RollbackException ex = new RollbackOperationException(); - new RollbackOperationException("message"); - new RollbackOperationException(new Exception()); - new RollbackOperationException("message", new Exception()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/event/PropertyChangeMatcher.java b/owner/src/test/java/org/aeonbits/owner/event/PropertyChangeMatcher.java deleted file mode 100644 index 532b6f45f..000000000 --- a/owner/src/test/java/org/aeonbits/owner/event/PropertyChangeMatcher.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import org.mockito.ArgumentMatcher; - -import java.beans.PropertyChangeEvent; - -import static org.aeonbits.owner.util.UtilTest.eq; - -/** - * @author Luigi R. Viggiano - */ -class PropertyChangeMatcher { - static ArgumentMatcher matches(final PropertyChangeEvent expectedEvent) { - return new ArgumentMatcher() { - @Override - public boolean matches(PropertyChangeEvent argument) { - return expectedEvent.getSource() == argument.getSource() && - eq(expectedEvent.getOldValue(), argument.getOldValue()) && - eq(expectedEvent.getNewValue(), argument.getNewValue()) && - eq(expectedEvent.getPropertyName(), argument.getPropertyName()); - } - - @Override - public String toString() { - return String.valueOf(expectedEvent); - } - }; - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/event/UnmodifiablePropertiesTest.java b/owner/src/test/java/org/aeonbits/owner/event/UnmodifiablePropertiesTest.java deleted file mode 100644 index 5f237222c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/event/UnmodifiablePropertiesTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.event; - -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.StringReader; -import java.util.Properties; - -import static org.junit.Assert.assertTrue; - -/** - * @author Luigi R. Viggiano - */ -public class UnmodifiablePropertiesTest { - private Properties props = new Properties() {{ - setProperty("foo", "bar"); - setProperty("baz", "qux"); - }}; - - private UnmodifiableProperties unmodifiable = new UnmodifiableProperties(props); - - @Test(expected = UnsupportedOperationException.class) - public void testSetProperty() { - unmodifiable.setProperty("blah", "blah"); - } - - @Test(expected = UnsupportedOperationException.class) - public void testPut() { - unmodifiable.put("blah", "blah"); - } - - @Test(expected = UnsupportedOperationException.class) - public void testRemove() { - unmodifiable.remove("foo"); - } - - @Test(expected = UnsupportedOperationException.class) - public void testClear() { - unmodifiable.clear(); - } - - @Test(expected = UnsupportedOperationException.class) - public void testKeySet() { - unmodifiable.keySet().clear(); - } - - @Test(expected = UnsupportedOperationException.class) - public void testEntrySet() { - unmodifiable.entrySet().clear(); - } - - @Test(expected = UnsupportedOperationException.class) - public void testValues() { - unmodifiable.values().clear(); - } - - @Test(expected = UnsupportedOperationException.class) - public void testLoadReader() throws IOException { - unmodifiable.load(new StringReader("someProperty=someValue")); - } - - @Test(expected = UnsupportedOperationException.class) - public void testLoadInputStream() throws IOException { - unmodifiable.load(new ByteArrayInputStream("someProperty=someValue".getBytes())); - } - - @Test - public void testContentIsSame() { - assertTrue(unmodifiable.entrySet().containsAll(props.entrySet())); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/examples/EncryptedPropertiesExample.java b/owner/src/test/java/org/aeonbits/owner/examples/EncryptedPropertiesExample.java deleted file mode 100644 index 27316162b..000000000 --- a/owner/src/test/java/org/aeonbits/owner/examples/EncryptedPropertiesExample.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.examples; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Converter; -import org.apache.commons.codec.binary.Base64; - -import java.lang.reflect.Method; - -/** - * To encrypt the password: - *
- *  System.out.println(Base64.encodeBase64String(xor("tiger".getBytes(), "secret".getBytes())));
- *  
- * @author Luigi R. Viggiano - */ -public class EncryptedPropertiesExample { - - interface EncryptedConfiguration extends Config { - @ConverterClass(DecryptConverter.class) - @DefaultValue("BwwEFxc=") - String scottPassword(); - } - - public static class DecryptConverter implements Converter { - public Object convert(Method method, String input) { - String key = System.getProperty("example.encryption.key"); - return new String(xor(Base64.decodeBase64(input), key.getBytes())); - } - } - - public static void main(String[] args) { - System.setProperty("example.encryption.key", "secret"); - EncryptedConfiguration example = ConfigFactory.create(EncryptedConfiguration.class); - System.out.println(example.scottPassword()); - } - - private static byte[] xor(final byte[] input, final byte[] secret) { - final byte[] output = new byte[input.length]; - if (secret.length == 0) { - throw new IllegalArgumentException("empty encryption key"); - } - int spos = 0; - for (int pos = 0; pos < input.length; ++pos) { - output[pos] = (byte) (input[pos] ^ secret[spos]); - ++spos; - if (spos >= secret.length) { - spos = 0; - } - } - return output; - } -} - diff --git a/owner/src/test/java/org/aeonbits/owner/examples/JMXExample.java b/owner/src/test/java/org/aeonbits/owner/examples/JMXExample.java deleted file mode 100644 index 3f869e588..000000000 --- a/owner/src/test/java/org/aeonbits/owner/examples/JMXExample.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.examples; - -import org.aeonbits.owner.Accessible; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Mutable; -import org.aeonbits.owner.Reloadable; -import org.aeonbits.owner.event.ReloadEvent; -import org.aeonbits.owner.event.ReloadListener; - -import javax.management.InstanceAlreadyExistsException; -import javax.management.MBeanRegistrationException; -import javax.management.MBeanServer; -import javax.management.MalformedObjectNameException; -import javax.management.NotCompliantMBeanException; -import javax.management.ObjectName; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.lang.management.ManagementFactory; - -/** - * @author Luigi R. Viggiano - */ -public class JMXExample { - - public interface MyConfig extends Mutable, Accessible, Reloadable { - - @Key("server.port.number") - @DefaultValue("80") - int port(); - - @Key("server.host.name") - @DefaultValue("localhost") - String hostname(); - - } - - public static void main(String[] args) throws InterruptedException, MalformedObjectNameException, - InstanceAlreadyExistsException, NotCompliantMBeanException, MBeanRegistrationException { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - - cfg.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - System.out.printf("prop change event [%s = %s -> %s]%n", evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }); - - cfg.addReloadListener(new ReloadListener() { - public void reloadPerformed(ReloadEvent event) { - System.out.printf("reload event detected%n"); - } - }); - - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - - mbs.registerMBean(cfg, new ObjectName("org.aeonbits.owner:type=configuration,name=MyConfig")); - - System.out.println("Now, launch jconsole and attach to the java process. Set a negative port number to exit."); - - while (cfg.port() >= 0) { - System.out.printf("\rport: %d hostname: %s \t\t\t\t", cfg.port(), cfg.hostname()); - Thread.sleep(500); - } - - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/examples/MapPropertyExample.java b/owner/src/test/java/org/aeonbits/owner/examples/MapPropertyExample.java deleted file mode 100644 index 5a38371fe..000000000 --- a/owner/src/test/java/org/aeonbits/owner/examples/MapPropertyExample.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.examples; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Converter; - -import java.lang.reflect.Method; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * @author Luigi R. Viggiano - */ -public class MapPropertyExample { - interface MyConfig extends Config { - @Separator(";") - @DefaultValue( - "name : Dante Alighieri, book : Divine Comedy, birth_year: 1265, death_year: 1321;" + - "name : Alessandro Manzoni, book : The Betrothed, birth_year: 1785, death_year: 1873") - @ConverterClass(MapPropertyConverter.class) - Map[] authors(); - } - - public static class MapPropertyConverter implements Converter> { - public Map convert(Method method, String input) { - Map result = new LinkedHashMap(); - String[] chunks = input.split(",", -1); - for (String chunk : chunks) { - String[] entry = chunk.split(":", -1); - String key = entry[0].trim(); - String value = entry[1].trim(); - result.put(key, value); - } - return result; - } - } - - public static void main(String[] args) { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - Map[] authors = cfg.authors(); - for (Map author : authors) { - for (Map.Entry entry : author.entrySet()) - System.out.printf("%s:\t%s\n", entry.getKey(), entry.getValue()); - System.out.println(); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/examples/ScheduledExecutorServiceSpike.java b/owner/src/test/java/org/aeonbits/owner/examples/ScheduledExecutorServiceSpike.java deleted file mode 100644 index f9f1f52a7..000000000 --- a/owner/src/test/java/org/aeonbits/owner/examples/ScheduledExecutorServiceSpike.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.examples; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -/** - * This spike is a learning test to understand how the asynchronous reload can be implemented. - * @author Luigi R. Viggiano - */ -public class ScheduledExecutorServiceSpike { - public static void main(String[] args) throws InterruptedException { - ThreadFactory tf = new ThreadFactory() { - public Thread newThread(Runnable r) { - try { - Thread result = new Thread(r); - result.setDaemon(true); - return result; - } finally { - System.out.println("new thread created"); - } - } - }; - ScheduledExecutorService stp = Executors.newSingleThreadScheduledExecutor(tf); - stp.scheduleAtFixedRate(new Runnable() { - int count = 0; - public void run() { - if ( count++ % 2 == 0) - System.out.printf("*"); - } - }, 500, 500, TimeUnit.MILLISECONDS); - - stp.scheduleAtFixedRate(new Runnable() { - int count = 0; - public void run() { - ++count; - if (count != 5 && count != 10) - System.out.printf("."); - if (count == 10) count = 0; - } - }, 100, 100, TimeUnit.MILLISECONDS); - stp.scheduleAtFixedRate(new Runnable() { - int count = 0; - public void run() { - System.out.print(++count); - } - }, 1000, 1000, TimeUnit.MILLISECONDS); - - Thread.sleep(10000L); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/importedprops/ImportConfigTest.java b/owner/src/test/java/org/aeonbits/owner/importedprops/ImportConfigTest.java deleted file mode 100644 index c4e0a303a..000000000 --- a/owner/src/test/java/org/aeonbits/owner/importedprops/ImportConfigTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.importedprops; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.TestConstants; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Properties; - -import static org.aeonbits.owner.util.UtilTest.fileFromURI; -import static org.aeonbits.owner.util.UtilTest.save; -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class ImportConfigTest implements TestConstants { - private static final String SPEC = "file:" + RESOURCES_DIR + "/ImportConfig.properties"; - - @Sources(SPEC) - public static interface ImportConfig extends Config { - - @DefaultValue("apple") - String foo(); - - @DefaultValue("pear") - String bar(); - - @DefaultValue("orange") - String baz(); - - } - - @Test - public void testImport() { - Properties props = new Properties(); - props.setProperty("foo", "pineapple"); - props.setProperty("bar", "lime"); - ImportConfig cfg = ConfigFactory.create(ImportConfig.class, props); // props imported! - assertEquals("pineapple", cfg.foo()); - assertEquals("lime", cfg.bar()); - assertEquals("orange", cfg.baz()); - } - - @Test - public void testImportOrder() { - Properties p1 = new Properties(); - p1.setProperty("foo", "pineapple"); - p1.setProperty("bar", "lime"); - - Properties p2 = new Properties(); - p2.setProperty("bar", "grapefruit"); - p2.setProperty("baz", "blackberry"); - - ImportConfig cfg = ConfigFactory.create(ImportConfig.class, p1, p2); // props imported! - - assertEquals("pineapple", cfg.foo()); - assertEquals("lime", cfg.bar()); // p1 prevails, so this is lime and not grapefruit - assertEquals("blackberry", cfg.baz()); - } - - @Test - public void testThatImportedPropertiesHaveHigherPriorityThanPropertiesLoadedBySources() - throws IOException, URISyntaxException { - File target = fileFromURI(SPEC); - - save(target, new Properties() {{ - setProperty("foo", "strawberries"); - }}); - - try { - Properties props = new Properties(); - props.setProperty("foo", "pineapple"); - props.setProperty("bar", "lime"); - ImportConfig cfg = ConfigFactory.create(ImportConfig.class, props); // props imported! - assertEquals("pineapple", cfg.foo()); - assertEquals("lime", cfg.bar()); - assertEquals("orange", cfg.baz()); - } finally { - target.delete(); - } - } - - interface ImportedPropertiesHaveHigherPriority extends Config { - Integer minAge(); - } - - @Test - public void testImportedPropertiesShouldOverrideSources() { - ImportedPropertiesHaveHigherPriority cfg = ConfigFactory.create(ImportedPropertiesHaveHigherPriority.class); - assertEquals(Integer.valueOf(18), cfg.minAge()); - - ImportedPropertiesHaveHigherPriority cfg2 = ConfigFactory.create(ImportedPropertiesHaveHigherPriority.class, - new Properties() {{ - setProperty("minAge", "21"); - }}, - - new Properties() {{ - setProperty("minAge", "22"); - }} - - ); - - assertEquals(Integer.valueOf(21), cfg2.minAge()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/importedprops/SystemPropertiesAndEnvTest.java b/owner/src/test/java/org/aeonbits/owner/importedprops/SystemPropertiesAndEnvTest.java deleted file mode 100644 index 78b8ede94..000000000 --- a/owner/src/test/java/org/aeonbits/owner/importedprops/SystemPropertiesAndEnvTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.importedprops; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import java.io.File; -import java.io.PrintStream; - -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class SystemPropertiesAndEnvTest { - interface SystemEnvProperties extends Config { - @Key("file.separator") - String fileSeparator(); - - @Key("java.home") - String javaHome(); - - @Key("HOME") - String home(); - - @Key("USER") - String user(); - - void list(PrintStream out); - } - - @Test - public void testSystemEnvProperties() { - SystemEnvProperties cfg = ConfigFactory.create(SystemEnvProperties - .class, System.getProperties(), System.getenv()); - assertEquals(File.separator, cfg.fileSeparator()); - assertEquals(System.getProperty("java.home"), cfg.javaHome()); - assertEquals(System.getenv().get("HOME"), cfg.home()); - assertEquals(System.getenv().get("USER"), cfg.user()); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/importedprops/WithImportedPropertiesTest.java b/owner/src/test/java/org/aeonbits/owner/importedprops/WithImportedPropertiesTest.java deleted file mode 100644 index 3ef1900a9..000000000 --- a/owner/src/test/java/org/aeonbits/owner/importedprops/WithImportedPropertiesTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.importedprops; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.util.SystemProviderForTest; -import org.aeonbits.owner.util.UtilTest; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class WithImportedPropertiesTest { - - @Test - public void testSubstituteWithImports() { - Properties propsFromTest = new Properties(); - propsFromTest.setProperty("external", "propsFromTest"); - WithImportedProperties conf = ConfigFactory.create - (WithImportedProperties.class, propsFromTest); - assertEquals("testing replacement from propsFromTest properties file.", conf.someValue()); - } - - @Test - public void testSystemProperty() { - String userHome = System.getProperty("user.home"); - WithImportedProperties conf = ConfigFactory.create(WithImportedProperties.class, System.getProperties()); - assertEquals(userHome, conf.userHome()); - } - - @Test - public void testSystemEnv() { - Object save = UtilTest.setSystem( - new SystemProviderForTest( - new Properties() {{ - setProperty("user.home", "/home/foobar"); - }}, - new HashMap() {{ - put("HOME", "/home/foobar"); - }} - )); - try { - String envHome = UtilTest.getenv("HOME"); - WithImportedProperties conf = ConfigFactory.create(WithImportedProperties.class, UtilTest.getenv()); - assertEquals(envHome, conf.envHome()); - } finally { - UtilTest.setSystem(save); - } - } - - @Test - public void testMultipleImports() { - Object save = UtilTest.setSystem( - new SystemProviderForTest( - new Properties() {{ - setProperty("user.home", "/home/foobar"); - }}, - new HashMap() {{ - put("HOME", "/home/foobar"); - }} - )); - try { - Properties propsFromTest = new Properties(); - propsFromTest.setProperty("external", "propsFromTest"); - - String userHome = UtilTest.getSystemProperty("user.home"); - String envHome = UtilTest.getenv("HOME"); - WithImportedProperties conf = - ConfigFactory.create(WithImportedProperties.class, - propsFromTest, UtilTest.getSystemProperties(), UtilTest.getenv()); - assertEquals(userHome, conf.userHome()); - assertEquals(envHome, conf.envHome()); - assertEquals("testing replacement from propsFromTest properties file.", conf.someValue()); - } finally { - UtilTest.setSystem(save); - } - } - - @Test - public void testBackSlash() { - Properties propsFromTest = new Properties(); - propsFromTest.setProperty("external", "propsFromTest"); - String winPath = "C:\\windows\\path"; - propsFromTest.setProperty("value.with.backslash", winPath); - - WithImportedProperties conf = - ConfigFactory.create(WithImportedProperties.class, - propsFromTest); - - assertEquals(winPath, conf.valueWithBackslash()); - } - - @Test - public void testPropertyComingFromExternalObject() { - Properties propsFromTest = new Properties(); - propsFromTest.setProperty("external", "propsFromTest"); - - WithImportedProperties conf = - ConfigFactory.create(WithImportedProperties.class, - propsFromTest); - - assertEquals("propsFromTest", conf.external()); - } - - public static interface WithImportedProperties extends Config { - String someValue(); - - @DefaultValue("${user.home}") - String userHome(); - - @DefaultValue("${HOME}") - String envHome(); - - @DefaultValue("${value.with.backslash}") - String valueWithBackslash(); - - String external(); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/interfaces/AccessibleConfigTest.java b/owner/src/test/java/org/aeonbits/owner/interfaces/AccessibleConfigTest.java deleted file mode 100644 index 67eb79b09..000000000 --- a/owner/src/test/java/org/aeonbits/owner/interfaces/AccessibleConfigTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.interfaces; - -import org.aeonbits.owner.Accessible; -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.LoadersManagerForTest; -import org.aeonbits.owner.PropertiesManagerForTest; -import org.aeonbits.owner.VariablesExpanderForTest; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ScheduledExecutorService; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -/** - * @author Luigi R. Viggiano - */ -@RunWith(MockitoJUnitRunner.class) -public class AccessibleConfigTest { - @Mock - private ScheduledExecutorService scheduler; - private LoadersManagerForTest loaders = new LoadersManagerForTest(); - - private final VariablesExpanderForTest expander = new VariablesExpanderForTest(new Properties()); - - public static interface AccessibleConfig extends Config, Accessible { - @DefaultValue("Bohemian Rapsody - Queen") - String favoriteSong(); - - @Key("salutation.text") - @DefaultValue("Good Morning") - String salutation(); - } - - @Test - public void testListPrintStream() throws IOException { - ByteArrayOutputStream expected = new ByteArrayOutputStream(); - PropertiesManagerForTest manager = - new PropertiesManagerForTest(AccessibleConfig.class, new Properties(), scheduler, expander, loaders); - manager.load().list(new PrintStream(expected, true)); - - AccessibleConfig config = ConfigFactory.create(AccessibleConfig.class); - ByteArrayOutputStream result = new ByteArrayOutputStream(); - config.list(new PrintStream(result, true)); - - assertEquals(expected.toString(), result.toString()); - } - - @Test - public void testListPrintWriter() throws IOException { - StringWriter expected = new StringWriter(); - PropertiesManagerForTest manager = - new PropertiesManagerForTest(AccessibleConfig.class, new Properties(), scheduler, expander, loaders); - manager.load().list(new PrintWriter(expected, true)); - - AccessibleConfig config = ConfigFactory.create(AccessibleConfig.class); - StringWriter result = new StringWriter(); - config.list(new PrintWriter(result, true)); - - assertEquals(expected.toString(), result.toString()); - } - - @Test - public void testStore() throws IOException { - AccessibleConfig cfg = ConfigFactory.create(AccessibleConfig.class); - File tmp = File.createTempFile("owner-", ".tmp"); - cfg.store(new FileOutputStream(tmp), "no comments"); - assertTrue(tmp.exists()); - assertTrue(tmp.length() > 0); - } - - @Test - public void testGetProperty() throws IOException { - AccessibleConfig cfg = ConfigFactory.create(AccessibleConfig.class); - assertEquals("Good Morning", cfg.getProperty("salutation.text")); - } - - @Test - public void testGetPropertyThatDoesNotExists() throws IOException { - AccessibleConfig cfg = ConfigFactory.create(AccessibleConfig.class); - assertNull(cfg.getProperty("foo.bar")); - } - - @Test - public void testGetPropertyWithDefault() throws IOException { - AccessibleConfig cfg = ConfigFactory.create(AccessibleConfig.class); - assertEquals("Good Morning", cfg.getProperty("salutation.text", "Hello")); - } - - @Test - public void testGetPropertyWithDefaultThatDoesNotExists() throws IOException { - AccessibleConfig cfg = ConfigFactory.create(AccessibleConfig.class); - assertEquals("Hello", cfg.getProperty("salutation.text.nonexistent", "Hello")); - } - - @Test - public void testStringPropertyNames() throws Throwable { - AccessibleConfig cfg = ConfigFactory.create(AccessibleConfig.class); - Set propNames = cfg.propertyNames(); - assertThat(propNames.size(), is(2)); - assertThat(propNames, containsInAnyOrder("favoriteSong", "salutation.text")); - } - - @Test - public void testFill() throws Throwable { - AccessibleConfig cfg = ConfigFactory.create(AccessibleConfig.class); - Properties props = new Properties(); - cfg.fill(props); - - assertEquals(2, props.size()); - assertEquals("Good Morning", props.getProperty("salutation.text")); - assertEquals("Bohemian Rapsody - Queen", props.getProperty("favoriteSong")); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/interfaces/MutableConfigTest.java b/owner/src/test/java/org/aeonbits/owner/interfaces/MutableConfigTest.java deleted file mode 100644 index 84eafa806..000000000 --- a/owner/src/test/java/org/aeonbits/owner/interfaces/MutableConfigTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.interfaces; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Mutable; -import org.aeonbits.owner.util.UtilTest; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Luigi R. Viggiano - */ -public class MutableConfigTest { - - private MutableConfig cfg; - - interface MutableConfig extends Config, Mutable { - @DefaultValue("18") - public Integer minAge(); - public Integer maxAge(); - } - - @Before - public void before() { - cfg = ConfigFactory.create(MutableConfig.class); - } - - @Test - public void testSetProperty() { - assertEquals(Integer.valueOf(18), cfg.minAge()); - String oldValue = cfg.setProperty("minAge", "21"); - assertEquals("18", oldValue); - assertEquals(Integer.valueOf(21), cfg.minAge()); - } - - @Test - public void testSetPropertyThatWasNull() { - assertNull(cfg.maxAge()); - String oldValue = cfg.setProperty("maxAge", "999"); - assertNull(oldValue); - assertEquals(Integer.valueOf(999), cfg.maxAge()); - } - - @Test - public void testSetPropertyWithNull() { - assertEquals(Integer.valueOf(18), cfg.minAge()); - String oldValue = cfg.setProperty("minAge", null); - assertEquals("18", oldValue); - assertNull(cfg.minAge()); - } - - @Test - public void testRemoveProperty() { - assertEquals(Integer.valueOf(18), cfg.minAge()); - String oldValue = cfg.removeProperty("minAge"); - assertEquals("18", oldValue); - assertNull(cfg.minAge()); - } - - @Test - public void testClear() { - assertEquals(Integer.valueOf(18), cfg.minAge()); - cfg.clear(); - assertNull(cfg.minAge()); - } - - @Test - public void testLoadInputStream() throws IOException { - File temp = File.createTempFile("MutableConfigTest", ".properties"); - UtilTest.save(temp, new Properties() {{ - setProperty("minAge", "19"); - setProperty("maxAge", "99"); - }}); - - cfg.load(new FileInputStream(temp)); - - assertEquals(Integer.valueOf(19), cfg.minAge()); - assertEquals(Integer.valueOf(99), cfg.maxAge()); - } - - @Test - public void testLoadReader() throws IOException { - File temp = File.createTempFile("MutableConfigTest", ".properties"); - UtilTest.save(temp, new Properties() {{ - setProperty("minAge", "19"); - setProperty("maxAge", "99"); - }}); - - cfg.load(new FileReader(temp)); - - assertEquals(Integer.valueOf(19), cfg.minAge()); - assertEquals(Integer.valueOf(99), cfg.maxAge()); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/issues/Issue123.java b/owner/src/test/java/org/aeonbits/owner/issues/Issue123.java deleted file mode 100644 index bd17269bd..000000000 --- a/owner/src/test/java/org/aeonbits/owner/issues/Issue123.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.issues; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.util.SystemProviderForTest; -import org.aeonbits.owner.util.UtilTest; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * @author Luigi R. Viggiano - */ -public class Issue123 { - - private Object save; - - @Sources({"file:~/bug.properties"}) - interface BugConfig extends Config { - } - - @Before - public void before() { - Properties dummySystemProperties = new Properties() {{ - setProperty("user.home", "c:\\user\\home"); - }}; - - Map dummySystemEnv = new HashMap(); - - SystemProviderForTest dummySystemForTest = new SystemProviderForTest(dummySystemProperties, dummySystemEnv); - - save = UtilTest.setSystem(dummySystemForTest); - } - - @After - public void after() { - UtilTest.setSystem(save); // restore System env and System props. - } - - @Test - public void testHomeWithTildeOnWindows() { - ConfigFactory.create(BugConfig.class); - // no exception is expected to be thrown. - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/issues/Issue184.java b/owner/src/test/java/org/aeonbits/owner/issues/Issue184.java deleted file mode 100644 index 861b16423..000000000 --- a/owner/src/test/java/org/aeonbits/owner/issues/Issue184.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.aeonbits.owner.issues; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class Issue184 { - - private static final String KEY = "a.key"; - - public interface MyConfig extends Config { - @Key(KEY) - @DefaultValue("1") - Integer getValue(); - } - - @Test - public void testConfigImportWithNullValue() throws Exception { - Map propsMapWithNullValue = new HashMap(); - propsMapWithNullValue.put(KEY, null); - - try { - ConfigFactory.create(Issue184.MyConfig.class, propsMapWithNullValue); - fail("A null value should result in an exception"); - } - catch(IllegalArgumentException e){ - assertTrue(e.getMessage().contains(KEY)); - } - } - - @Test - public void testConfigImportWithNullKey() throws Exception { - Map propsMapWithNullKey = new HashMap(); - propsMapWithNullKey.put(null, "smurf"); - - try { - ConfigFactory.create(Issue184.MyConfig.class, propsMapWithNullKey); - fail("A null key should result in an exception"); - } - catch(IllegalArgumentException e){ - assertTrue(e.getMessage().contains("null")); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/issues/Issue203.java b/owner/src/test/java/org/aeonbits/owner/issues/Issue203.java deleted file mode 100644 index 106fcbcc4..000000000 --- a/owner/src/test/java/org/aeonbits/owner/issues/Issue203.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.aeonbits.owner.issues; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; - -public class Issue203 { - interface SomeConfig extends Config { - // - } - - @Test - public void testCreateConfigInConcurrentSysPropModifying() throws Exception { - - - ExecutorService exe = Executors.newFixedThreadPool(2); - try { - final AtomicBoolean running = new AtomicBoolean(true); - Future createConfigFuture = exe.submit(new Callable() { - @Override - public Void call() { - for (int cnt = 0; cnt < 100; cnt++) { - System.out.println(cnt); - ConfigFactory.create(SomeConfig.class); - } - return null; - } - }); - - Future changeSystemPropertyFuture = exe.submit(new Callable() { - @Override - public Void call() { - while (running.get()) { - System.setProperty("Foo", "Bar"); - System.getProperties().remove("Foo"); - } - return null; - } - }); - createConfigFuture.get(); - running.set(false); - changeSystemPropertyFuture.get(); - } - finally { - exe.shutdown(); - } - } - - - -} diff --git a/owner/src/test/java/org/aeonbits/owner/issues/Issue268.java b/owner/src/test/java/org/aeonbits/owner/issues/Issue268.java deleted file mode 100644 index 7c8ed0d3b..000000000 --- a/owner/src/test/java/org/aeonbits/owner/issues/Issue268.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.aeonbits.owner.issues; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import static java.lang.Thread.sleep; -import static org.junit.Assert.assertFalse; - -/** - * See: https://github.com/lviggiano/owner/issues/268 - */ -public class Issue268 { - - interface MyConfig extends Config { - @DefaultValue("Pasha") - String firstName(); - - @DefaultValue("Bairov") - String lastName(); - } - - // A starter flag 🏁 to make sure a group of threads start at the same time - static class Starter { - private final int players; - private volatile int count = 0; - - Starter(int players) { - this.players = players; - } - - synchronized void ready() { - try { - count++; - wait(); - } catch (InterruptedException e) { - throw new IllegalStateException(e); - } - } - - void set() throws InterruptedException { - while (count != players) { - sleep(20); - } - } - - synchronized void go() { - notifyAll(); - } - - } - - @Test - public void testConcurrentAccess() throws InterruptedException { - final MyConfig cfg = ConfigFactory.create(MyConfig.class); - - final Starter starter = new Starter(2); - - final boolean[] nameMismatch = {false}; - final boolean[] lastNameMismatch = {false}; - final int iterations = 1000; - - Thread t1 = new Thread() { - @Override - public void run() { - starter.ready(); - for (int i = 0; i < iterations && !nameMismatch[0] && !lastNameMismatch[0]; i++) - if (!cfg.firstName().equals("Pasha")) - nameMismatch[0] = true; - } - }; - - Thread t2 = new Thread() { - @Override - public void run() { - starter.ready(); - for (int i = 0; i < iterations && !nameMismatch[0] && !lastNameMismatch[0]; i++) - if (!cfg.lastName().equals("Bairov")) - lastNameMismatch[0] = true; - } - }; - - t1.start(); - t2.start(); - - starter.set(); - starter.go(); - - t1.join(); - t2.join(); - - assertFalse("mismatch on name", nameMismatch[0]); - assertFalse("mismatch on lastName", lastNameMismatch[0]); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/issues/Issue87.java b/owner/src/test/java/org/aeonbits/owner/issues/Issue87.java deleted file mode 100644 index c50dfb828..000000000 --- a/owner/src/test/java/org/aeonbits/owner/issues/Issue87.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.issues; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -/** - * @author Luigi R. Viggiano - */ -public class Issue87 { - - public interface MyConfig extends Config { - - @DefaultValue("1, 2, foo, 4") - public Integer[] invalidValueArray(); - - @DefaultValue("1, 2, foo, 4") - public MyInteger[] myIntegerInvalidValueArray(); - - @DefaultValue("1, 2, foo, 4") - public List invalidValueList(); - - @DefaultValue("1, 2, foo, 4") - public List myIntegerInvalidValueList(); - } - - public class MyInteger { - private final Integer value; - - public MyInteger(String value) { - this.value = new Integer(value); - } - } - - private MyConfig cfg; - - @Before - public void before() { - cfg = ConfigFactory.create(MyConfig.class); - } - - - @Test(expected = UnsupportedOperationException.class) - public void testInvalidValueArray() throws Exception { - cfg.invalidValueArray(); - } - - @Test(expected = UnsupportedOperationException.class) - public void testMyIntegerInvalidValue() throws Exception { - cfg.myIntegerInvalidValueArray(); - } - - @Test(expected = UnsupportedOperationException.class) - public void testInvalidValueList() { - cfg.invalidValueList(); - } - - @Test(expected = UnsupportedOperationException.class) - public void testMyIntegerInvalidValueList() { - cfg.myIntegerInvalidValueList(); - } - - -} diff --git a/owner/src/test/java/org/aeonbits/owner/jmx/JMXMBeanTest.java b/owner/src/test/java/org/aeonbits/owner/jmx/JMXMBeanTest.java deleted file mode 100644 index 4a07c9be4..000000000 --- a/owner/src/test/java/org/aeonbits/owner/jmx/JMXMBeanTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.jmx; - -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Mutable; -import org.aeonbits.owner.Reloadable; -import org.junit.Test; - -import javax.management.Attribute; -import javax.management.AttributeList; -import javax.management.DynamicMBean; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import java.lang.management.ManagementFactory; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -/** - * @author Robin Meißner - */ -public class JMXMBeanTest { - - private static interface JMXConfigMutableReloadable extends DynamicMBean, Mutable, Reloadable { - @DefaultValue("8080") - int port(); - - @DefaultValue("http://localhost") - String hostname(); - - @DefaultValue("42") - int maxThreads(); - } - - /* - * Simple test case for JMX accessible mbeans. - * - * Registers a config of JMXConfigMutableReloadable.class - * under object name org.aeonbits.owner.jmx:type=testBeanHandling,id=JMXConfigMutableReloadable and - * tests getAttribute(s) methods and invokes setProperty actions with it. - */ - @Test - public void testBeanHandling() throws Throwable { - Properties props = new Properties(); - JMXConfigMutableReloadable config = ConfigFactory.create(JMXConfigMutableReloadable.class, props); - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName mbeanName = new ObjectName( - "org.aeonbits.owner.jmx:type=testBeanHandling,id=JMXConfigMutableReloadable"); - mbs.registerMBean(config, mbeanName); - - assertEquals("8080", mbs.getAttribute(mbeanName, "port")); - AttributeList attrList = new AttributeList(); - attrList.add(new Attribute("port", "8080")); - attrList.add(new Attribute("hostname", "http://localhost")); - attrList.add(new Attribute("maxThreads", "42")); - assertEquals(attrList, mbs.getAttributes(mbeanName, new String[] { "port", "hostname", "maxThreads"})); - - mbs.invoke(mbeanName, "setProperty", new String[] { "port", "7878" }, - null); - assertEquals("7878", mbs.getAttribute(mbeanName, "port")); - assertEquals("7878", mbs.invoke(mbeanName, "getProperty", new String[] { "port"}, null)); - - mbs.invoke(mbeanName, "reload", null, null); - assertEquals(attrList, mbs.getAttributes(mbeanName, new String[] { "port", "hostname", "maxThreads"})); - } - - /* - * Test case for registering multiple mbeans with same configuration object. - */ - @Test - public void testMultipleBeanHandling() throws Throwable { - Properties props = new Properties(); - - JMXConfigMutableReloadable config = ConfigFactory.create(JMXConfigMutableReloadable.class, props); - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName mbeanName1 = new ObjectName( - "org.aeonbits.owner.jmx:type=testMultipleBeanHandling,id=JMXConfigMutableReloadable"); - ObjectName mbeanName2 = new ObjectName( - "org.aeonbits.owner.jmx:type=testMultipleBeanHandling2,id=JMXConfigMutableReloadable"); - mbs.registerMBean(config, mbeanName1); - mbs.registerMBean(config, mbeanName2); - mbs.setAttribute(mbeanName1, new Attribute("port", "7878")); - assertEquals("7878", mbs.getAttribute(mbeanName1, "port")); - assertEquals(mbs.getAttribute(mbeanName2, "port"), mbs.getAttribute(mbeanName1, "port")); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/loaders/PropertiesLoaderTest.java b/owner/src/test/java/org/aeonbits/owner/loaders/PropertiesLoaderTest.java deleted file mode 100644 index eb02b0b9c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/loaders/PropertiesLoaderTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loaders; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import static org.junit.Assert.assertTrue; - -public class PropertiesLoaderTest { - - private PropertiesLoader loader = new PropertiesLoader(); - - private static final String UTF_KEY = "цвет"; - private static final String UTF_VALUE= "синий"; - private static final String UTF_KEY_VALUE = String.format("%s:%s", UTF_KEY, UTF_VALUE); - private InputStream keyValueStream; - - @Before - public void before() throws IOException { - keyValueStream = new ByteArrayInputStream(UTF_KEY_VALUE.getBytes("UTF-8")); - } - - @After - public void after() throws IOException { - keyValueStream.close(); - } - - @Test - public void testLoadingCyrillicInUTF8() throws IOException { - Properties result = new Properties(); - loader.load(result, keyValueStream); - - assertTrue(result.containsKey(UTF_KEY)); - assertTrue(result.getProperty(UTF_KEY).equals(UTF_VALUE)); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/loaders/SystemLoaderTest.java b/owner/src/test/java/org/aeonbits/owner/loaders/SystemLoaderTest.java deleted file mode 100644 index d8d9d273d..000000000 --- a/owner/src/test/java/org/aeonbits/owner/loaders/SystemLoaderTest.java +++ /dev/null @@ -1,140 +0,0 @@ -package org.aeonbits.owner.loaders; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.util.SystemProviderForTest; -import org.aeonbits.owner.util.UtilTest; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Properties; - -import static org.aeonbits.owner.Config.LoadType.FIRST; -import static org.aeonbits.owner.Config.LoadType.MERGE; -import static org.junit.Assert.*; - -public class SystemLoaderTest { - - @Config.Sources({"system:properties", - "system:env"}) - @Config.LoadPolicy(FIRST) - public interface FirstConfig extends Config { - @DefaultValue("this should be ignored") - String foo(); - - @DefaultValue("this should be ignored") - String bar(); - - @DefaultValue("user.home") - String userHome(); - - @Key("PATH") - String path(); - - String nullProp(); - - @DefaultValue("theDefaultValue") - String useDefault(); - } - - @Test - public void first_loadSystemProperties() { - - Object save = UtilTest.setSystem(new SystemProviderForTest( - new Properties() {{ - setProperty("foo", "FOO"); - setProperty("bar", "BAR"); - }}, - new HashMap() - )); - - try { - FirstConfig config = ConfigFactory.create(FirstConfig.class); - - assertEquals("FOO", config.foo()); - assertEquals("BAR", config.bar()); - - } finally { - UtilTest.setSystem(save); - } - } - - @Test - public void first_nullProp() { - FirstConfig config = ConfigFactory.create(FirstConfig.class); - assertNull(config.nullProp()); - } - - @Test - public void first_loadSysPropFirst_ignoreEnvVars() { - FirstConfig config = ConfigFactory.create(FirstConfig.class); - assertNull(config.path()); - } - - @Config.Sources({"system:properties", - "system:env"}) - @Config.LoadPolicy(MERGE) - public interface MergeConfig extends Config { - @DefaultValue("this should be ignored") - String foo(); - - @DefaultValue("this should be ignored") - String bar(); - - @DefaultValue("user.home") - String userHome(); - - @Key("PATH") - String path(); - - String nullProp(); - - @DefaultValue("theDefaultValue") - String useDefault(); - } - - @Test - public void merge_loadSystemProperties() { - Object save = UtilTest.setSystem(new SystemProviderForTest( - new Properties() {{ - setProperty("foo", "FOO"); - setProperty("bar", "BAR"); - }}, - new HashMap() - )); - - try { - MergeConfig config = ConfigFactory.create(MergeConfig.class); - - assertEquals("FOO", config.foo()); - assertEquals("BAR", config.bar()); - } finally { - UtilTest.setSystem(save); - } - } - - @Test - public void merge_includeDefaultSystemProperties() { - MergeConfig config = ConfigFactory.create(MergeConfig.class); - assertNotNull(config.userHome()); - } - - @Test - public void merge_defaultValueFromConfig() { - MergeConfig config = ConfigFactory.create(MergeConfig.class); - assertEquals("theDefaultValue", config.useDefault()); - } - - @Test - public void merge_nullProp() { - MergeConfig config = ConfigFactory.create(MergeConfig.class); - assertNull(config.nullProp()); - } - - @Test - public void merge_pathEnvVariable() { - MergeConfig config = ConfigFactory.create(MergeConfig.class); - assertNotNull(config.path()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest.java b/owner/src/test/java/org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest.java deleted file mode 100644 index 6a827aabc..000000000 --- a/owner/src/test/java/org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loadstrategies; - -import org.aeonbits.owner.*; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.IOException; -import java.net.URI; -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * @author Luigi R. Viggiano - */ -@RunWith(MockitoJUnitRunner.class) -public class DefaultLoadStrategyTest extends LoadStrategyTestBase { - @Mock - private ScheduledExecutorService scheduler; - @Spy - private final LoadersManagerForTest loaders = new LoadersManagerForTest(); - private final VariablesExpanderForTest expander = new VariablesExpanderForTest(new Properties()); - - static interface SampleConfig extends Config { - String testKey(); - } - - @Test - public void shouldReturnTheResourceForAClass() throws IOException { - PropertiesManagerForTest manager = - new PropertiesManagerForTest(SampleConfig.class, new Properties(), scheduler, expander, loaders); - - manager.load(); - - verify(loaders, times(1)).findLoader(any(URI.class)); - verify(loaders, times(1)).findLoader(argThat(uriMatches( - "org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest$SampleConfig.properties"))); - } - - @Test - public void shouldReturnTheValueFromTheAssociatedProperties() { - SampleConfig config = ConfigFactory.create(SampleConfig.class); - assertEquals("testValue", config.testKey()); - } - - @Test - public void shouldReturnThePropertiesForTheClass() { - PropertiesManagerForTest manager = - new PropertiesManagerForTest(SampleConfig.class, new Properties(), scheduler, expander, loaders); - Properties props = manager.load(); - assertNotNull(props); - assertEquals("testValue", props.getProperty("testKey")); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/loadstrategies/FirstLoadStrategyTest.java b/owner/src/test/java/org/aeonbits/owner/loadstrategies/FirstLoadStrategyTest.java deleted file mode 100644 index 4e103a51b..000000000 --- a/owner/src/test/java/org/aeonbits/owner/loadstrategies/FirstLoadStrategyTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loadstrategies; - -import static org.aeonbits.owner.Config.LoadType.FIRST; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.LoadPolicy; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.LoadersManagerForTest; -import org.aeonbits.owner.PropertiesManagerForTest; -import org.aeonbits.owner.VariablesExpanderForTest; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; - -/** - * @author Luigi R. Viggiano - */ -@RunWith(MockitoJUnitRunner.class) -public class FirstLoadStrategyTest extends LoadStrategyTestBase { - @Mock - private ScheduledExecutorService scheduler; - @Spy - private final LoadersManagerForTest loaders = new LoadersManagerForTest(); - private final VariablesExpanderForTest expander = new VariablesExpanderForTest(new Properties()); - - - @Sources({"classpath:foo/bar/baz.properties", - "file:~/.testfoobar.blahblah", - "file:/etc/testfoobar.blahblah", - "classpath:org/aeonbits/owner/FooBar.properties", // it will be loaded from here - "file:~/blahblah.properties"}) - public static interface SampleConfigWithSource extends Config { - String helloWorld(); - } - - @Test - public void firstIsTheDefaultLoadStrategy() throws Exception { - SampleConfigWithSource sample = ConfigFactory.create(SampleConfigWithSource.class); - assertEquals("Hello World!", sample.helloWorld()); - } - - @Sources({"classpath:foo/bar/baz.properties", - "file:~/.testfoobar.blahblah", - "file:/etc/testfoobar.blahblah", - "classpath:org/aeonbits/owner/FooBar.properties", // it will be loaded from here - "file:~/blahblah.properties"}) - @LoadPolicy(FIRST) - public static interface SampleConfigrationWithFirstLoadStrategy extends Config { - String helloWorld(); - } - - @Test - public void shouldLoadFromTheFirstAvailableResource() throws Exception { - SampleConfigrationWithFirstLoadStrategy sample = ConfigFactory.create(SampleConfigrationWithFirstLoadStrategy.class); - assertEquals("Hello World!", sample.helloWorld()); - } - - - @Sources("httpz://foo.bar.baz") - interface InvalidURLConfig extends Config { - - } - - @Test(expected = UnsupportedOperationException.class) - public void testWhenURLIsInvalid() { - ConfigFactory.create(InvalidURLConfig.class); - } - - @Sources("classpath:foo/bar/thisDoesntExists.properties") - public static interface InvalidSourceConfig extends Config { - public String someProperty(); - } - - @Test - public void shouldReturnNullProperty() { - InvalidSourceConfig config = ConfigFactory.create(InvalidSourceConfig.class); - assertNull(config.someProperty()); - } - - @Test - public void shouldLoadURLFromSpecifiedSource() throws IOException { - Properties props = new Properties(); - PropertiesManagerForTest manager = - new PropertiesManagerForTest(SampleConfigWithSource.class, props, - scheduler, expander, loaders); - manager.load(); - verify(loaders, times(1)).findLoader(argThat(uriMatches("org/aeonbits/owner/FooBar.properties"))); - assertEquals("Hello World!", props.getProperty("helloWorld")); - } - - @Test - public void shouldLoadPropertiesFromSpecifiedSource() throws Exception { - SampleConfigWithSource sample = ConfigFactory.create(SampleConfigWithSource.class); - assertEquals("Hello World!", sample.helloWorld()); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/loadstrategies/LoadPathsWithSpacesTest.java b/owner/src/test/java/org/aeonbits/owner/loadstrategies/LoadPathsWithSpacesTest.java deleted file mode 100644 index bdfcda1bc..000000000 --- a/owner/src/test/java/org/aeonbits/owner/loadstrategies/LoadPathsWithSpacesTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.aeonbits.owner.loadstrategies; - -import static org.junit.Assert.assertEquals; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.LoadersManagerForTest; -import org.aeonbits.owner.VariablesExpanderForTest; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.Properties; -import java.util.concurrent.ScheduledExecutorService; - -@RunWith(MockitoJUnitRunner.class) -public class LoadPathsWithSpacesTest extends LoadStrategyTestBase { - - @Mock - private ScheduledExecutorService scheduler; - @Spy - private final LoadersManagerForTest loaders = new LoadersManagerForTest(); - private final VariablesExpanderForTest expander = new VariablesExpanderForTest(new Properties()); - - - @Config.Sources({ - "file:${user.dir}/src/test/resources/org/aeonbits/owner/directory with spaces/simple.properties"}) - public static interface FileConfigWithSource extends Config { - String helloWorld(); - } - - @Config.Sources({ - "classpath:org/aeonbits/owner/directory with spaces/simple.properties"}) - public static interface ClasspathConfigWithSource extends Config { - String helloWorld(); - } - - @Test - public void shouldLoadFromFile() throws Exception { - FileConfigWithSource sample = ConfigFactory.create(FileConfigWithSource.class); - assertEquals("Hello World!", sample.helloWorld()); - } - - @Test - public void shouldLoadFromClasspath() throws Exception { - ClasspathConfigWithSource sample = ConfigFactory.create(ClasspathConfigWithSource.class); - assertEquals("Hello World!", sample.helloWorld()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/loadstrategies/LoadStrategyTestBase.java b/owner/src/test/java/org/aeonbits/owner/loadstrategies/LoadStrategyTestBase.java deleted file mode 100644 index 4af6ba1b7..000000000 --- a/owner/src/test/java/org/aeonbits/owner/loadstrategies/LoadStrategyTestBase.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loadstrategies; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.mockito.ArgumentMatcher; -import org.mockito.internal.hamcrest.HamcrestArgumentMatcher; - -import java.net.URI; - -/** - * @author Luigi R. Viggiano - */ -public class LoadStrategyTestBase { - ArgumentMatcher uriMatches(final String path) { - return new HamcrestArgumentMatcher( - new BaseMatcher(){ - public URI uri; - - public boolean matches(Object o) { - uri = (URI)o; - return uri.toString().endsWith(path); - } - - public void describeTo(Description description) { - description.appendText("expected <" + (uri != null ? uri : "uri") + "> ending with " + path); - } - }); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/loadstrategies/MergeLoadStrategyTest.java b/owner/src/test/java/org/aeonbits/owner/loadstrategies/MergeLoadStrategyTest.java deleted file mode 100644 index 6fd3a7c38..000000000 --- a/owner/src/test/java/org/aeonbits/owner/loadstrategies/MergeLoadStrategyTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.loadstrategies; - -import static org.aeonbits.owner.Config.LoadType.MERGE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.LoadPolicy; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -/** - * @author Luigi R. Viggiano - */ -public class MergeLoadStrategyTest { - @Test - public void testPropertyMerge() { - MergeConfig cfg = ConfigFactory.create(MergeConfig.class); - assertEquals("first", cfg.foo()); - assertEquals("second", cfg.bar()); - assertEquals("first", cfg.foo()); - assertEquals("third", cfg.qux()); - assertNull(cfg.quux()); - assertEquals("theDefaultValue", cfg.fubar()); - } - - @Sources({"classpath:org/aeonbits/owner/first.properties", - "classpath:foo/bar/thisDoesntExists.properties", - "classpath:org/aeonbits/owner/second.properties", - "file:${user.dir}/src/test/resources/foo/bar/thisDoesntExists.properties", - "file:${user.dir}/src/test/resources/org/aeonbits/owner/third.properties"}) - @LoadPolicy(MERGE) - public static interface MergeConfig extends Config { - @DefaultValue("this should be ignored") - String foo(); - @DefaultValue("this should be ignored") - String bar(); - @DefaultValue("this should be ignored") - String baz(); - @DefaultValue("this should be ignored") - String qux(); - - String quux(); // this should return null; - @DefaultValue("theDefaultValue") - String fubar(); - } - - @Sources("httpz://foo.bar.baz") - @LoadPolicy(MERGE) - interface InvalidURLConfig extends Config { - - } - - @Test(expected = UnsupportedOperationException.class) - public void testWhenURLIsInvalid() { - ConfigFactory.create(InvalidURLConfig.class); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/multithread/MultiThreadReloadTest.java b/owner/src/test/java/org/aeonbits/owner/multithread/MultiThreadReloadTest.java deleted file mode 100644 index 3c56cf8f2..000000000 --- a/owner/src/test/java/org/aeonbits/owner/multithread/MultiThreadReloadTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.multithread; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Reloadable; -import org.aeonbits.owner.TestConstants; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.net.URISyntaxException; -import java.util.Properties; - -import static org.aeonbits.owner.util.UtilTest.fileFromURI; -import static org.aeonbits.owner.util.UtilTest.newArray; -import static org.aeonbits.owner.util.UtilTest.save; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * @author Luigi R. Viggiano - */ -public class MultiThreadReloadTest extends MultiThreadTestBase implements TestConstants { - private static final String SPEC = "file:" + RESOURCES_DIR + "/ReloadableConfig.properties"; - private static File target; - private ReloadableConfig reloadableConfig; - - @BeforeClass - public static void beforeClass() throws URISyntaxException { - target = fileFromURI(SPEC); - } - - @Before - public void before() throws Throwable { - synchronized (target) { - save(target, new Properties() {{ - setProperty("someValue", "10"); - }}); - - reloadableConfig = ConfigFactory.create(ReloadableConfig.class); - } - } - - @Sources(SPEC) - public interface ReloadableConfig extends Config, Reloadable { - Integer someValue(); - } - - @Test - public void multiThreadedReloadTest() throws Throwable { - Object lock = new Object(); - - ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100)); - WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70)); - - start(readers, writers); - - notifyAll(lock); - - join(readers, writers); - - assertNoErrors(readers); - assertNoErrors(writers); - } - - private class ReaderThread extends ThreadBase { - ReaderThread(ReloadableConfig cfg, Object lock, int loops) { - super(cfg, lock, loops); - } - - @Override - void execute() throws Throwable { - Thread.yield(); - Integer value = cfg.someValue(); - assertNotNull(value); - assertTrue(value == 10 || value == 20); - } - - @Override - public Object clone() throws CloneNotSupportedException { - return new ReaderThread(cfg, lock, loops); - } - } - - private class WriterThread extends ThreadBase { - public WriterThread(ReloadableConfig cfg, Object lock, int loops) { - super(cfg, lock, loops); - } - - @Override - void execute() throws Throwable { - synchronized (target) { - save(target, new Properties() {{ - setProperty("someValue", "20"); - }}); - - cfg.reload(); - } - Thread.yield(); - - synchronized (target) { - save(target, new Properties() {{ - setProperty("someValue", "10"); - }}); - - cfg.reload(); - } - Thread.yield(); - } - - @Override - public Object clone() throws CloneNotSupportedException { - return new WriterThread(cfg, lock, loops); - } - } - - @After - public void after() throws Throwable { - synchronized (target) { - target.delete(); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/multithread/MultiThreadTestBase.java b/owner/src/test/java/org/aeonbits/owner/multithread/MultiThreadTestBase.java deleted file mode 100644 index f0bdcfc6f..000000000 --- a/owner/src/test/java/org/aeonbits/owner/multithread/MultiThreadTestBase.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.multithread; - -import org.aeonbits.owner.Config; - -import java.lang.Thread.State; -import java.util.List; - -/** - * @author Luigi R. Viggiano - */ -abstract class MultiThreadTestBase { - void join(ThreadBase[]... args) throws InterruptedException { - for (ThreadBase[] threads : args) - for (Thread thread : threads) - thread.join(); - } - - void start(ThreadBase[]... args) throws InterruptedException { - for (ThreadBase[] threads : args) - for (Thread thread : threads) { - thread.start(); - while (thread.getState() != State.WAITING) - // waits for all threads to be started and ready to rush - // when lock.notifyAll() is issued - thread.join(1); - } - } - - void assertNoErrors(ThreadBase[] threads) throws Throwable { - for (int i = 0; i < threads.length; i++) { - ThreadBase thread = threads[i]; - - int errorCount = thread.errors.size(); - - if (errorCount > 0) - System.err.printf("There are %d exception collected by %s#%d\n", errorCount, - thread.getClass().getName(), i); - - List errors = thread.errors; - for (Throwable error : errors) { - System.err.printf("%s#%d thrown an exception: %s\n", thread.getClass().getName(), i, - error.getMessage()); - error.printStackTrace(System.err); - throw error; - } - } - } - - void notifyAll(Object lock) { - synchronized (lock) { - lock.notifyAll(); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/multithread/ThreadBase.java b/owner/src/test/java/org/aeonbits/owner/multithread/ThreadBase.java deleted file mode 100644 index 8d02ec7e0..000000000 --- a/owner/src/test/java/org/aeonbits/owner/multithread/ThreadBase.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.multithread; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.util.UtilTest.MyCloneable; - -import java.util.ArrayList; -import java.util.List; - -import static org.aeonbits.owner.util.UtilTest.debug; - -abstract class ThreadBase extends Thread implements MyCloneable { - private static long counter = 0; - private final long uniqueThreadId = ++counter; - final T cfg; - final Object lock; - final int loops; - final List errors = new ArrayList(); - - ThreadBase(T cfg, Object lock, int loops) { - this.cfg = cfg; - this.lock = lock; - this.loops = loops; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - @Override - public void run() { - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } - } - for (int i = 0; i < loops; i++) { - debug("%s[%d] started loop #%d.\n", getClass().getName(), uniqueThreadId, i); - try { - execute(); - } catch (Throwable throwable) { - debug("%s[%d] thrown an error in loop #%d.\n", getClass().getName(), uniqueThreadId, i); - errors.add(throwable); - } - Thread.yield(); - debug("%s[%d] completed loop #%d.\n", getClass().getName(), uniqueThreadId, i); - } - } - - abstract void execute() throws Throwable; -} diff --git a/owner/src/test/java/org/aeonbits/owner/reload/AsyncAutoReloadTest.java b/owner/src/test/java/org/aeonbits/owner/reload/AsyncAutoReloadTest.java deleted file mode 100644 index 90f334a80..000000000 --- a/owner/src/test/java/org/aeonbits/owner/reload/AsyncAutoReloadTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.reload; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.HotReload; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Reloadable; -import org.aeonbits.owner.TestConstants; -import org.aeonbits.owner.event.ReloadEvent; -import org.aeonbits.owner.event.ReloadListener; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.net.URISyntaxException; -import java.util.Properties; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.aeonbits.owner.Config.HotReloadType.ASYNC; -import static org.aeonbits.owner.util.UtilTest.delete; -import static org.aeonbits.owner.util.UtilTest.fileFromURI; -import static org.aeonbits.owner.util.UtilTest.save; -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class AsyncAutoReloadTest extends AsyncReloadSupport implements TestConstants { - private static final String PROPERTY_FILE_NAME = "AsyncAutoReloadConfig.properties"; - private static final int DELAY = 1000; - - private static final String SPEC = "file:"+ RESOURCES_DIR + "/" + PROPERTY_FILE_NAME; - - private static File target; - - @BeforeClass - public static void beforeClass() throws URISyntaxException { - target = fileFromURI(SPEC); - } - - @Sources(SPEC) - @HotReload(value=10, unit = MILLISECONDS, type = ASYNC) - interface AsyncAutoReloadConfig extends Config, Reloadable { - @DefaultValue("5") - Integer someValue(); - } - - @Test - public void testReload() throws Throwable { - - save(target, new Properties() {{ - setProperty("someValue", "10"); - }}); - - AsyncAutoReloadConfig cfg = ConfigFactory.create(AsyncAutoReloadConfig.class); - final int[] reloadCount = {0}; - cfg.addReloadListener(new ReloadListener() { - public void reloadPerformed(ReloadEvent event) { - reloadCount[0]++; - } - }); - cfg.addReloadListener(new ReloadListener() { - public void reloadPerformed(ReloadEvent event) { - notifyReload(); - } - }); - - assertEquals(Integer.valueOf(10), cfg.someValue()); - - assertEquals(0, reloadCount[0]); - assertEquals(Integer.valueOf(10), cfg.someValue()); - - delete(target); - waitForReload(DELAY); - - assertEquals(1, reloadCount[0]); - assertEquals(Integer.valueOf(5), cfg.someValue()); - - save(target, new Properties() {{ - setProperty("someValue", "20"); - }}); - waitForReload(DELAY); - - assertEquals(2, reloadCount[0]); - assertEquals(Integer.valueOf(20), cfg.someValue()); - - delete(target); - waitForReload(DELAY); - - assertEquals(3, reloadCount[0]); - assertEquals(Integer.valueOf(5), cfg.someValue()); - - save(target, new Properties() {{ - setProperty("someValue", "30"); - }}); - waitForReload(DELAY); - - assertEquals(4, reloadCount[0]); - assertEquals(Integer.valueOf(30), cfg.someValue()); - } - - @HotReload(value=10, unit = MILLISECONDS, type = ASYNC) - interface OnlyHotReloadAnnotationIsSpecified extends Config, Reloadable { - @DefaultValue("5") - Integer someValue(); - } - - @Test - public void testShouldNotCauseNullPex() { - OnlyHotReloadAnnotationIsSpecified cfg = ConfigFactory.create(OnlyHotReloadAnnotationIsSpecified.class); - assertEquals(Integer.valueOf(5), cfg.someValue()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/reload/AsyncReloadSupport.java b/owner/src/test/java/org/aeonbits/owner/reload/AsyncReloadSupport.java deleted file mode 100644 index 86d3793ae..000000000 --- a/owner/src/test/java/org/aeonbits/owner/reload/AsyncReloadSupport.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.reload; - - -/** - * @author luigi - */ -class AsyncReloadSupport { - private final Object reloadLock = new Object(); - - void waitForReload(final long timeout) throws InterruptedException { - synchronized (reloadLock) { - reloadLock.wait(timeout); - } - } - - void notifyReload() { - synchronized (reloadLock) { - reloadLock.notifyAll(); - } - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/reload/HotReloadWhenURLContainsVariablesTest.java b/owner/src/test/java/org/aeonbits/owner/reload/HotReloadWhenURLContainsVariablesTest.java deleted file mode 100644 index 255530b4c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/reload/HotReloadWhenURLContainsVariablesTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.reload; - -import org.aeonbits.owner.Config.HotReload; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Reloadable; -import org.aeonbits.owner.TestConstants; -import org.aeonbits.owner.VariablesExpanderForTest; -import org.aeonbits.owner.event.ReloadEvent; -import org.aeonbits.owner.event.ReloadListener; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.util.Properties; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.aeonbits.owner.Config.HotReloadType.ASYNC; -import static org.aeonbits.owner.util.UtilTest.fileFromURI; -import static org.aeonbits.owner.util.UtilTest.save; -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class HotReloadWhenURLContainsVariablesTest extends AsyncReloadSupport implements TestConstants { - private static final String SPEC = "file:${user.dir}/" + RESOURCES_DIR + "/AutoReloadExample.properties"; - private static File target; - - @Sources(SPEC) - @HotReload(value=10, unit = MILLISECONDS, type = ASYNC) - interface AutoReloadConfig extends Reloadable { - @DefaultValue("5") - Integer someValue(); - } - - @Before - public void before() throws Throwable { - - // here I need to expand SPEC manually to create the file for the test - String spec = new VariablesExpanderForTest(new Properties()).expand(SPEC); - - target = fileFromURI(spec); - save(target, new Properties() {{ - setProperty("someValue", "10"); - }}); - - // 1-Jan-1970 (so, the file it's old enough to need reload - target.setLastModified(0); - } - - @Test - public void testReloadWorksWhenURLContainsVariablesToExpand() - throws Throwable { - - AutoReloadConfig cfg = ConfigFactory.create(AutoReloadConfig.class); - cfg.addReloadListener(new ReloadListener() { - public void reloadPerformed(ReloadEvent event) { - notifyReload(); - } - }); - - assertEquals(new Integer(10), cfg.someValue()); - - save(target, new Properties() {{ - setProperty("someValue", "20"); - }}); - - waitForReload(1000); - - assertEquals(new Integer(20), cfg.someValue()); - - } - - @After - public void after() throws Throwable { - target.delete(); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/reload/ReloadTest.java b/owner/src/test/java/org/aeonbits/owner/reload/ReloadTest.java deleted file mode 100644 index 8d37e8168..000000000 --- a/owner/src/test/java/org/aeonbits/owner/reload/ReloadTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.reload; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Reloadable; -import org.aeonbits.owner.TestConstants; -import org.aeonbits.owner.event.ReloadEvent; -import org.aeonbits.owner.event.ReloadListener; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatcher; -import org.mockito.Mock; -import org.mockito.internal.hamcrest.HamcrestArgumentMatcher; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.File; -import java.net.URISyntaxException; -import java.util.Properties; - -import static org.aeonbits.owner.util.UtilTest.fileFromURI; -import static org.aeonbits.owner.util.UtilTest.save; -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * @author Luigi R. Viggiano - */ -@RunWith(MockitoJUnitRunner.class) -public class ReloadTest implements TestConstants { - private static final String SPEC = "file:" + RESOURCES_DIR + "/ReloadableConfig.properties"; - private static File target; - @Mock - ReloadListener listener; - - @BeforeClass - public static void beforeClass() throws URISyntaxException { - target = fileFromURI(SPEC); - } - - @Before - public void before() throws Throwable { - save(target, new Properties() {{ - setProperty("minimumAge", "18"); - }}); - } - - @Sources(SPEC) - public interface ReloadableConfig extends Config, Reloadable { - Integer minimumAge(); - } - - @Test - public void testReload() throws Throwable { - ReloadableConfig cfg = ConfigFactory.create(ReloadableConfig.class); - - assertEquals(Integer.valueOf(18), cfg.minimumAge()); - - save(target, new Properties() {{ - setProperty("minimumAge", "21"); - }}); - - cfg.reload(); - assertEquals(Integer.valueOf(21), cfg.minimumAge()); - } - - public interface ReloadImportConfig extends Config, Reloadable { - Integer minimumAge(); - } - - @Test - public void testReloadWithImportedProperties() throws Throwable { - Properties props = new Properties() {{ - setProperty("minimumAge", "18"); - }}; - - ReloadImportConfig cfg = ConfigFactory.create(ReloadImportConfig.class, props); - assertEquals(Integer.valueOf(18), cfg.minimumAge()); - - props.setProperty("minimumAge", "21"); // changing props doesn't reflect to cfg immediately - assertEquals(Integer.valueOf(18), cfg.minimumAge()); - - cfg.reload(); // the config gets reloaded, so the change in props gets reflected - assertEquals(Integer.valueOf(21), cfg.minimumAge()); - } - - @After - public void after() throws Throwable { - target.delete(); - } - - @Test - public void testReloadListener() throws Throwable { - ReloadableConfig cfg = ConfigFactory.create(ReloadableConfig.class); - cfg.addReloadListener(listener); - cfg.reload(); - cfg.reload(); - cfg.reload(); - verify(listener, times(3)).reloadPerformed(argThat(isReloadListnerWithSource(cfg))); - } - - @Test - public void testReloadListenerRemoved() throws Throwable { - ReloadableConfig cfg = ConfigFactory.create(ReloadableConfig.class); - cfg.addReloadListener(listener); - cfg.reload(); - cfg.reload(); - cfg.removeReloadListener(listener); - cfg.reload(); - verify(listener, times(2)).reloadPerformed(argThat(isReloadListnerWithSource(cfg))); - } - - private ArgumentMatcher isReloadListnerWithSource(final ReloadableConfig cfg) { - return new HamcrestArgumentMatcher( - new BaseMatcher() { - public boolean matches(Object o) { - ReloadEvent given = (ReloadEvent) o; - return given.getSource() == cfg; - } - - public void describeTo(Description description) { - description.appendText("does not match"); - } - }); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/reload/SyncAutoReloadTest.java b/owner/src/test/java/org/aeonbits/owner/reload/SyncAutoReloadTest.java deleted file mode 100644 index dcbd69952..000000000 --- a/owner/src/test/java/org/aeonbits/owner/reload/SyncAutoReloadTest.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.reload; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.HotReload; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.TestConstants; -import org.aeonbits.owner.util.TimeProviderForTest; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Properties; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.aeonbits.owner.util.UtilTest.fileFromURI; -import static org.aeonbits.owner.util.UtilTest.save; -import static org.aeonbits.owner.util.UtilTest.saveJar; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * @author Luigi R. Viggiano - */ -public class SyncAutoReloadTest implements TestConstants { - - private static final String PROPERTY_FILE_NAME = "SyncAutoReloadConfig.properties"; - private static final String JAR_FILE = RESOURCES_DIR + "/SyncAutoReloadTest.jar"; - - private static final String SPEC = "file:"+ RESOURCES_DIR + "/" + PROPERTY_FILE_NAME; - private static final String SPEC_JAR = "jar:file:" + JAR_FILE + "!/" + PROPERTY_FILE_NAME; - - private static File target; - private static File jarTarget; - - private static TimeProviderForTest time; - - @BeforeClass - public static void beforeClass() throws URISyntaxException { - target = fileFromURI(SPEC); - jarTarget = new File(JAR_FILE); - } - - @Before - public void before() { - time = new TimeProviderForTest(); - time.setup(); // become owner of time (now I can control the elapse of time in this test) - } - - @Sources(SPEC) - @HotReload(5) - interface SyncAutoReloadConfig extends Config { - @DefaultValue("5") - Integer someValue(); - } - - @Test - public void testAutoReload() throws IOException, InterruptedException { - save(target, new Properties() {{ - setProperty("someValue", "10"); - }}); - boolean success = target.setLastModified(target.lastModified() - 15000); // make the file 15 seconds older. - assertTrue(success); - time.setTime(target.lastModified()); // set the time for this test to match the file creation. - - SyncAutoReloadConfig cfg = ConfigFactory.create(SyncAutoReloadConfig.class); - assertEquals(Integer.valueOf(10), cfg.someValue()); - - save(target, new Properties() {{ // file updated, the update time is reflected in target.lastModified(). - setProperty("someValue", "20"); - }}); - - time.elapse(4, SECONDS); // make 4 seconds elapse for the test. - assertEquals(Integer.valueOf(10), cfg.someValue()); // change is not reflected yet since interval is 5 secs. - - time.elapse(1, SECONDS); // another second is elapsed for the test. - assertEquals(Integer.valueOf(20), cfg.someValue()); // the changed file should be reloaded now. - } - - @Sources(SPEC_JAR) - @HotReload(5) - interface AutoReloadJarConfig extends Config { - Integer someValue(); - } - - @Test - public void testAutoReloadOnJarFile() throws Throwable { - saveJar(jarTarget, PROPERTY_FILE_NAME, - new Properties() {{ - setProperty("someValue", "10"); - }}); - - boolean success = jarTarget.setLastModified(jarTarget.lastModified() - 15000); // make the file 15 seconds older - assertTrue(success); - - time.setTime(jarTarget.lastModified()); // set the time for this test to match the file creation - - AutoReloadJarConfig cfg = ConfigFactory.create(AutoReloadJarConfig.class); - assertEquals(Integer.valueOf(10), cfg.someValue()); - - saveJar(jarTarget, PROPERTY_FILE_NAME, // file updated, the update time is reflected in target.lastModified(). - new Properties() {{ - setProperty("someValue", "20"); - }}); - - time.elapse(4, SECONDS); // make 4 seconds elapse for the test. - assertEquals(Integer.valueOf(10), cfg.someValue()); // change is not reflected yet since interval is 5 secs. - - time.elapse(1, SECONDS); // another second is elapsed for the test. - assertEquals(Integer.valueOf(20), cfg.someValue()); // the changed file should be reloaded now. - } - - @Test - public void testAutoReloadWhenFileGetsDeleted() throws IOException, InterruptedException { - save(target, new Properties() {{ - setProperty("someValue", "10"); - }}); - boolean success = target.setLastModified(target.lastModified() - 15000); // make the file 15 seconds older. - assertTrue(success); - time.setTime(target.lastModified()); // set the time for this test to match the file creation. - - SyncAutoReloadConfig cfg = ConfigFactory.create(SyncAutoReloadConfig.class); - assertEquals(Integer.valueOf(10), cfg.someValue()); - - boolean deleted = target.delete(); - assertTrue(deleted); - - time.elapse(4, SECONDS); // make 4 seconds elapse for the test. - assertEquals(Integer.valueOf(10), cfg.someValue()); // change is not reflected yet since interval is 5 secs. - - time.elapse(1, SECONDS); // another second is elapsed for the test. - assertEquals(Integer.valueOf(5), cfg.someValue()); // the deleted file should be noted now, - // the default value is returned. - } - - @HotReload(5) - interface SyncAutoReloadConfigFromClasspath extends Config { - @DefaultValue("5") - Integer someValue(); - } - - @Test - public void testAutoReloadFromClasspath() throws IOException, InterruptedException { - File classpathTarget = - new File("target/test-classes/" + - "org/aeonbits/owner/reload/" + - "SyncAutoReloadTest$SyncAutoReloadConfigFromClasspath.properties"); - classpathTarget.deleteOnExit(); - - save(classpathTarget, new Properties() {{ - setProperty("someValue", "10"); - }}); - - boolean success = classpathTarget.setLastModified(classpathTarget.lastModified() - 15000); // make the file 15 seconds older. - assertTrue(success); - time.setTime(classpathTarget.lastModified()); // set the time for this test to match the file creation. - - SyncAutoReloadConfigFromClasspath cfg = ConfigFactory.create(SyncAutoReloadConfigFromClasspath.class); - assertEquals(Integer.valueOf(10), cfg.someValue()); - - save(classpathTarget, new Properties() {{ // file updated, the update time is reflected in target.lastModified(). - setProperty("someValue", "20"); - }}); - - time.elapse(4, SECONDS); // make 4 seconds elapse for the test. - assertEquals(Integer.valueOf(10), cfg.someValue()); // change is not reflected yet since interval is 5 secs. - - time.elapse(1, SECONDS); // another second is elapsed for the test. - assertEquals(Integer.valueOf(20), cfg.someValue()); // the changed file should be reloaded now. - } - - - @After - public void after() { - time.tearDown(); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/reload/SystemPropertiesReloadTest.java b/owner/src/test/java/org/aeonbits/owner/reload/SystemPropertiesReloadTest.java deleted file mode 100644 index 945b16326..000000000 --- a/owner/src/test/java/org/aeonbits/owner/reload/SystemPropertiesReloadTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.aeonbits.owner.reload; - -import org.aeonbits.owner.*; -import org.aeonbits.owner.Config.HotReload; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.event.ReloadEvent; -import org.aeonbits.owner.event.ReloadListener; -import org.aeonbits.owner.util.SystemProviderForTest; -import org.aeonbits.owner.util.UtilTest; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Properties; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.aeonbits.owner.Config.HotReloadType.ASYNC; -import static org.junit.Assert.assertEquals; - -public class SystemPropertiesReloadTest extends AsyncReloadSupport { - private SystemProviderForTest systemForTest = new SystemProviderForTest(new Properties(), new HashMap()); - private Object save; - - @Sources("system:properties") - @HotReload(value = 1, unit = MILLISECONDS, type = ASYNC) - interface AsyncAutoReloadConfig extends Config, Reloadable { - @DefaultValue("5") - Integer someValue(); - } - - @Before - public void before() { - this.save = UtilTest.setSystem(systemForTest); - } - - @After - public void after() { - UtilTest.setSystem(save); - } - - @Test - public void testReload() throws Throwable { - - AsyncAutoReloadConfig cfg = ConfigFactory.create(AsyncAutoReloadConfig.class); - - cfg.addReloadListener(new ReloadListener() { - public void reloadPerformed(ReloadEvent event) { - notifyReload(); - } - }); - - assertEquals(Integer.valueOf(5), cfg.someValue()); - - String propKey = "someValue"; - systemForTest.setProperty(propKey, "5"); - waitForReload(10); - assertEquals(Integer.valueOf(5), cfg.someValue()); - - systemForTest.setProperty(propKey, "20"); - waitForReload(10); - assertEquals(Integer.valueOf(20), cfg.someValue()); - - systemForTest.remove(propKey); - waitForReload(10); - assertEquals(Integer.valueOf(5), cfg.someValue()); - - systemForTest.setProperty(propKey, "30"); - waitForReload(10); - assertEquals(Integer.valueOf(30), cfg.someValue()); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/serializable/TestSerialization.java b/owner/src/test/java/org/aeonbits/owner/serializable/TestSerialization.java deleted file mode 100644 index c3a19173c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/serializable/TestSerialization.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.serializable; - -import org.aeonbits.owner.Config.HotReload; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Mutable; -import org.aeonbits.owner.TestConstants; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import static java.io.File.createTempFile; -import static org.aeonbits.owner.util.Collections.map; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class TestSerialization implements TestConstants { - private static final String PROPERTY_FILE_NAME = "AsyncAutoReloadConfig.properties"; - - private static final String SPEC = "file:"+ RESOURCES_DIR + "/" + PROPERTY_FILE_NAME; - - private File target; - - @HotReload - @Sources(SPEC) - public static interface MyConfig extends Mutable { - @DefaultValue("someText") - public String someText(); - - @DefaultValue("some,array") - public String[] someArray(); - } - - @Before - public void before() throws IOException { - File parent = new File(RESOURCES_DIR); - parent.mkdirs(); - target = createTempFile("TestSerialization", ".ser", parent); - } - - @After - public void after() throws IOException { - target.delete(); - } - - @Test - public void testSerialization() throws IOException, ClassNotFoundException { - MyConfig cfg = ConfigFactory.create(MyConfig.class, map("foo", "bar")); - assertEquals("someText", cfg.someText()); - assertArrayEquals(new String[] {"some", "array"}, cfg.someArray()); - cfg.addPropertyChangeListener("someText", new MyPropertyChangeListener()); - - serialize(cfg, target); - - MyConfig deserialized = deserialize(target); - - assertEquals(cfg, deserialized); - } - - private MyConfig deserialize(File target) throws IOException, ClassNotFoundException { - FileInputStream fin = new FileInputStream(target); - try { - ObjectInputStream oin = new ObjectInputStream(fin); - try { - return (MyConfig) oin.readObject(); - } finally { - oin.close(); - } - } finally { - fin.close(); - } - } - - private void serialize(MyConfig cfg, File target) throws IOException { - FileOutputStream fout = new FileOutputStream(target); - try { - ObjectOutputStream oout = new ObjectOutputStream(fout); - try { - oout.writeObject(cfg); - oout.flush(); - } finally { - oout.close(); - } - } finally { - fout.close(); - } - } - - private static class MyPropertyChangeListener implements PropertyChangeListener, Serializable { - public void propertyChange(PropertyChangeEvent evt) { - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterClassTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterClassTest.java deleted file mode 100644 index a51b19815..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterClassTest.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Converter; -import org.junit.Before; -import org.junit.Test; - -import java.lang.reflect.Method; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -/** - * @author Luigi R. Viggiano - */ -public class ConverterClassTest { - private MyConfig cfg; - static class Server { - private final String name; - private final Integer port; - - public Server(String name, Integer port) { - this.name = name; - this.port = port; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Server server = (Server) o; - - if (!name.equals(server.name)) return false; - if (!port.equals(server.port)) return false; - - return true; - } - - @Override - public String toString() { - return name + ":" + port; - } - } - - public static class ServerConverter implements Converter { - public Server convert(Method targetMethod, String text) { - String[] split = text.split(":", -1); - String name = split[0]; - Integer port = 80; - if (split.length >= 2) - port = Integer.valueOf(split[1]); - return new Server(name, port); - } - } - - public static class ReturningNullConverter implements Converter { - public Server convert(Method method, String input) { - return null; - } - } - - public static class ReturningUnsupportedOperationException implements Converter { - public Server convert(Method method, String input) { - throw new UnsupportedOperationException(String.format("Cannot convert %s to %s", input, Server.class)); - } - } - - public static class ReturningNullPointerException implements Converter { - public Server convert(Method method, String input) { - throw new NullPointerException(); - } - } - - public abstract static class CantBeInstantiated implements Converter { // abstract - public Server convert(Method method, String input) { - return null; - } - } - - private static class CantBeAccessed implements Converter { // private - public Server convert(Method method, String input) { - return null; - } - } - - interface MyConfig extends Config { - @DefaultValue("foobar.com:8080") - @ConverterClass(ServerConverter.class) - Server server(); - - @DefaultValue("google.com, yahoo.com:8080, owner.aeonbits.org:4000") - @ConverterClass(ServerConverter.class) - Server[] servers(); - - @DefaultValue("foobar:80") - @ConverterClass(ReturningNullConverter.class) - Server returningNull(); - - @DefaultValue("foobar:80") - @ConverterClass(ReturningUnsupportedOperationException.class) - Server returningUnsupportedOperationException(); - - @DefaultValue("foobar:80") - @ConverterClass(ReturningNullPointerException.class) - Server returningNullPointerException(); - - @DefaultValue("foobar:80") - @ConverterClass(CantBeInstantiated.class) - Server converterClassCantBeInstantiated(); - - @DefaultValue("foobar:80") - @ConverterClass(CantBeAccessed.class) - Server converterClassCantBeAccessed(); - - @DefaultValue("10") - @ConverterClass(OverridesIntegerConversion.class) - int overridden(); - } - - @Before - public void before() { - this.cfg = ConfigFactory.create(MyConfig.class); - } - - @Test - public void testOverriddenConversion() { - assertEquals(42, cfg.overridden()); - } - - - @Test - public void testSingleObject() { - assertEquals(new Server("foobar.com", 8080), cfg.server()); - } - - @Test - public void testArrayObject() { - Server[] expected = new Server[] { - new Server("google.com", 80), - new Server("yahoo.com", 8080), - new Server("owner.aeonbits.org", 4000) - }; - assertArrayEquals(expected, cfg.servers()); - } - - @Test - public void testReturningNull() { - assertNull(cfg.returningNull()); - } - - @Test(expected = UnsupportedOperationException.class) - public void testReturningUnsupportedOperationException() { - cfg.returningUnsupportedOperationException(); - } - - @Test(expected = NullPointerException.class) - public void testReturningNullPointerException() { - cfg.returningNullPointerException(); - } - - @Test - public void testConverterCantBeInstantiated() { - try { - cfg.converterClassCantBeInstantiated(); - fail("exception expected"); - } catch (UnsupportedOperationException ex) { - assertEquals(InstantiationException.class, ex.getCause().getClass()); - } - } - - @Test - public void testConverterCantBeAccessed() { - try { - cfg.converterClassCantBeAccessed(); - fail("exception expected"); - } catch (UnsupportedOperationException ex) { - assertEquals(IllegalAccessException.class, ex.getCause().getClass()); - } - } - - public static class OverridesIntegerConversion implements Converter { - public Object convert(Method method, String input) { - return 42; - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterRegistryTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterRegistryTest.java deleted file mode 100644 index 7b6d4178c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterRegistryTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.aeonbits.owner.typeconversion; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Converter; -import org.junit.Test; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * Created by stefan on 7.9.2016. - */ -public class ConverterRegistryTest { - private static final String LEET_SPEEK = "1'm 50 l337"; - private static final String LEET_TRANSLATION = "I'm so leet"; - private static final String FOOBAR_RESPONSE = "FooBar"; - - public static class LeetTranslatorConverter implements Converter { - Map lookup = new HashMap(); - public LeetTranslatorConverter(){ - lookup.put('1', 'I'); - lookup.put('5', 's'); - lookup.put('0', 'o'); - lookup.put('3', 'e'); - lookup.put('7', 't'); - } - - public String convert(Method targetMethod, String text) { - StringBuilder sb = new StringBuilder(text); - for( int i=0 ; i { - public String convert(Method method, String input) { - return FOOBAR_RESPONSE; - } - } - - interface MyConfig extends Config { - @DefaultValue(LEET_SPEEK) - String leetSpeek(); - - @DefaultValue(LEET_SPEEK) - @ConverterClass(FooBarConverter.class) - String leetSpeekWithConverterClassAnnotation(); - } - - @Test - public void testBasicConverterRegistry(){ - MyConfig cfg = ConfigFactory.create(MyConfig.class); - assertEquals("Converter class has not been registered yet.", LEET_SPEEK, cfg.leetSpeek()); - ConfigFactory.setTypeConverter(String.class, LeetTranslatorConverter.class); - assertEquals("Registered converter class should have been used but wasn't.", LEET_TRANSLATION, cfg.leetSpeek()); - ConfigFactory.removeTypeConverter(String.class); - assertEquals("Converter class should have been removed.", LEET_SPEEK, cfg.leetSpeek()); - } - - @Test - public void testConverterClassAnnotationOverride(){ - MyConfig cfg = ConfigFactory.create(MyConfig.class); - assertEquals("Expected a response from the annotated converter class.", FOOBAR_RESPONSE, cfg.leetSpeekWithConverterClassAnnotation()); - ConfigFactory.setTypeConverter(String.class, LeetTranslatorConverter.class); - assertEquals("Still expecting a response from the annotated converter class", FOOBAR_RESPONSE, cfg.leetSpeekWithConverterClassAnnotation()); - ConfigFactory.removeTypeConverter(String.class); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/PrimitiveTypesTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/PrimitiveTypesTest.java deleted file mode 100644 index 8b034619e..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/PrimitiveTypesTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class PrimitiveTypesTest { - - public static interface PrimitiveTypesConfig extends Config { - @DefaultValue("42") - int answerToLifeUniverseAndEverything(); - - @DefaultValue("3.141592653589793") - double pi(); - - @DefaultValue("0.5") - float half(); - - @DefaultValue("false") - boolean worldIsFlat(); - - @DefaultValue("7") - Integer daysInWeek(); - - @DefaultValue("invalid") - Integer invalid(); - } - - @Test - public void testDefaultIntValue() { - PrimitiveTypesConfig config = ConfigFactory.create(PrimitiveTypesConfig.class); - assertEquals(42, config.answerToLifeUniverseAndEverything()); - } - - @Test - public void testDefautDoubleValue() { - PrimitiveTypesConfig config = ConfigFactory.create(PrimitiveTypesConfig.class); - assertEquals(3.141592653589793D, config.pi(), 0.000000000000001D) ; - } - - @Test - public void testDefautFloatValue() { - PrimitiveTypesConfig config = ConfigFactory.create(PrimitiveTypesConfig.class); - assertEquals(0.5f, config.half(), 0.01f); - } - - @Test - public void testDefautBooleanValue() { - PrimitiveTypesConfig config = ConfigFactory.create(PrimitiveTypesConfig.class); - assertEquals(false, config.worldIsFlat()); - } - - @Test - public void testDefaultIntegerValue() { - PrimitiveTypesConfig config = ConfigFactory.create(PrimitiveTypesConfig.class); - assertEquals(new Integer(7), config.daysInWeek()); - } - - @Test(expected = UnsupportedOperationException.class) - public void testInvalid() { - PrimitiveTypesConfig config = ConfigFactory.create(PrimitiveTypesConfig.class); - config.invalid(); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/SpecialTypesTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/SpecialTypesTest.java deleted file mode 100644 index 61068818c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/SpecialTypesTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import java.io.File; -import java.net.URL; -import java.sql.Driver; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * @author Luigi R. Viggiano - */ -public class SpecialTypesTest { - - public static class InvalidCustomType { - } - - public static class InvalidValueOf { - private final String text; - - private InvalidValueOf(String text) { - this.text = text; - } - - public InvalidValueOf valueOf(String text) { - return new InvalidValueOf(text); - } - } - - public static class ValueOf { - private String text; - - private ValueOf() { - } - - public static ValueOf valueOf(String text) { - ValueOf result = new ValueOf(); - result.text = text; - return result; - } - - @Override - public String toString() { - return text; - } - } - - public static interface SpecialTypes extends Config { - @DefaultValue("foobar.txt") - File sampleFile(); - - @DefaultValue("~") - File home(); - - @DefaultValue("http://owner.aeonbits.org") - URL sampleURL(); - - @DefaultValue("test") - CustomType customType(); - - @DefaultValue("Hello %s!") - CustomType salutation(String name); - - @DefaultValue("this should raise an exception") - InvalidCustomType invalid(); - - @DefaultValue("FOO") - EnumType enumType(); - - @DefaultValue("java.sql.Driver") - Class jdbcDriver(); - - @DefaultValue("foo.bar.UnexistentClass") - Class nonExistentClass(); - - @DefaultValue("foobar") - Reference reference(); - - @DefaultValue("invalidValueOf") - InvalidValueOf invalidValueOf(); - - @DefaultValue("valueOf") - ValueOf valueOf(); - - @DefaultValue("obj") - Object object(); - } - - @Test - public void testFileReturnType() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - File f = config.sampleFile(); - assertNotNull(f); - assertEquals("foobar.txt", f.getName()); - } - - @Test - public void testURLReturnType() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - URL u = config.sampleURL(); - assertNotNull(u); - assertEquals("http://owner.aeonbits.org", u.toString()); - } - - public static class CustomType { - private final String text; - - public CustomType(String text) { - this.text = text; - } - - public String getText() { - return text; - } - } - - @Test - public void testClassWithStringConstructor() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - CustomType custom = config.customType(); - assertNotNull(custom); - assertEquals("test", custom.getText()); - } - - public static class Reference { - private final Object object; - - public Reference(Object object) { - this.object = object; - } - - @Override - public String toString() { - return object.toString(); - } - } - - @Test - public void testClassWithObjectConstructor() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - Reference reference = config.reference(); - assertNotNull(reference); - assertEquals("foobar", reference.toString()); - } - - @Test - public void testCustomTypeWithParameter() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - CustomType custom = config.salutation("Luigi"); - assertNotNull(custom); - assertEquals("Hello Luigi!", custom.getText()); - } - - @Test(expected = UnsupportedOperationException.class) - public void testInvalidCustomType() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - config.invalid(); - } - - public static enum EnumType { - FOO, BAR, BAZ - } - - @Test - public void testEnumType() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - EnumType enumType = config.enumType(); - assertNotNull(enumType); - assertEquals(EnumType.FOO, enumType); - } - - @Test - public void testClassType() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - Class driver = config.jdbcDriver(); - assertNotNull(driver); - assertEquals(Driver.class, driver); - } - - @Test(expected = UnsupportedOperationException.class) - public void testClassTypeWhenClassIsNotFound() throws Throwable { - SpecialTypes config = ConfigFactory.create(SpecialTypes.class); - Class nonExistent = config.nonExistentClass(); - assertNull(nonExistent); - } - - @Test(expected = UnsupportedOperationException.class) - public void testClassWithInvalidValueOfMethod() throws Throwable { - SpecialTypes cfg = ConfigFactory.create(SpecialTypes.class); - cfg.invalidValueOf(); - } - - @Test - public void testClassWithValueOfMethod() throws Throwable { - SpecialTypes cfg = ConfigFactory.create(SpecialTypes.class); - ValueOf valueOf = cfg.valueOf(); - assertNotNull(valueOf); - assertEquals("valueOf", valueOf.toString()); - } - - @Test - public void testHome() throws Throwable { - SpecialTypes cfg = ConfigFactory.create(SpecialTypes.class); - File home = cfg.home(); - assertNotNull(home); - assertEquals(new File(System.getProperty("user.home")), home); - } - - @Test(expected = UnsupportedOperationException.class) - public void testObject() throws Throwable { - SpecialTypes cfg = ConfigFactory.create(SpecialTypes.class); - cfg.object(); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ArraySupportTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ArraySupportTest.java deleted file mode 100644 index 62bcb03e4..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ArraySupportTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; - -/** - * @author Luigi R. Viggiano - * @author Dmytro Chyzhykov - */ -public class ArraySupportTest { - - private ArrayConfig cfg; - - @Before - public void before() { - cfg = ConfigFactory.create(ArrayConfig.class); - } - - /** - emptyProperty= - unsupported=dummy value: this is unsupported - */ - public static interface ArrayConfig extends Config { - @DefaultValue("apple, pear, orange") - public String[] fruit(); - - @DefaultValue("") - public String[] emptyProperty(); - public String[] missedProperty(); - - @DefaultValue("1, 2, 3") - public Integer[] integers(); - - @DefaultValue("${emptyProperty}") - public Integer[] emptyIntegers(); - - @DefaultValue("${integers}") - public int[] primitiveIntArray(); - - @DefaultValue("${emptyIntegers}") - public int[] primitiveEmptyIntegers(); - - @DefaultValue("dummy value: this is unsupported") - public UnsupportedType[] unsupported(); - - public static class UnsupportedType {} - } - - @Test - public void itShouldReadStringArray() throws Exception { - assertThat(cfg.fruit(), is(new String[]{"apple", "pear", "orange"})); - } - - @Test - public void itShouldReturnNullForMissedStringArray() throws Exception { - assertThat(cfg.missedProperty(), is(nullValue())); - } - - @Test - public void itShouldReturnEmptyStringArray() throws Exception { - assertThat(cfg.emptyProperty(), is(new String[]{})); - } - - @Test - public void itShouldReturnIntegerArray() throws Exception { - assertThat(cfg.integers(), is(new Integer[]{1, 2, 3})); - } - - @Test - public void itShouldReturnEmptyIntegerArray() throws Exception { - assertThat(cfg.emptyIntegers(), is(new Integer[]{})); - } - - @Test - public void itShouldReturnIntArray() throws Exception { - assertThat(cfg.primitiveIntArray(), is(new int[]{1, 2, 3})); - } - - @Test - public void itShouldReturnEmptyIntArray() throws Exception { - assertThat(cfg.primitiveEmptyIntegers(), is(new int[]{})); - } - - @Test(expected = UnsupportedOperationException.class) - public void testUnsupportedArrayType() throws Exception { - cfg.unsupported(); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/BasicArrayWithAnnotationTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/BasicArrayWithAnnotationTest.java deleted file mode 100644 index aa41a7027..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/BasicArrayWithAnnotationTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -/** - * @author Luigi R. Viggiano - */ -public class BasicArrayWithAnnotationTest { - private BasicArrayWithAnnotationConfig cfg; - - @Before - public void before() { - cfg = ConfigFactory.create(BasicArrayWithAnnotationConfig.class); - } - - public static interface BasicArrayWithAnnotationConfig extends Config { - @Separator(";") - @DefaultValue("0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55") - public int[] fibonacci(); - - @TokenizerClass(CustomDashTokenizer.class) - @DefaultValue("foo-bar-baz") - public String[] withSeparatorClass(); - } - - @Test - public void testSeparatorAnnotation() throws Exception { - assertThat(cfg.fibonacci(), is(new int[]{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55})); - } - - @Test - public void testTokenizerClass() throws Exception { - assertThat(cfg.withSeparatorClass(), is(new String[]{"foo", "bar", "baz"})); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationResolutionTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationResolutionTest.java deleted file mode 100644 index e0bc595be..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationResolutionTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.Separator; -import org.aeonbits.owner.Config.TokenizerClass; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -/** - * @author Luigi R. Viggiano - */ -public class ConflictingAnnotationResolutionTest { - - private ConflictingAnnotationsResolved cfg; - - // as we know specifying both @TokenizerClass and Separator on the same level (class level) generates a conflict - @TokenizerClass(CustomCommaTokenizer.class) - @Separator("!") - public static interface ConflictingAnnotationsResolved extends Config { - - // but since @Separator on method level takes precedence, the conflict is resolved. - @Separator(",") - @DefaultValue("1, 2, 3, 4") - public int[] commaSeparated(); - - // but since @TokenizerClass on method level takes precedence, the conflict is resolved. - @TokenizerClass(CustomDashTokenizer.class) - @DefaultValue("1-2-3-4") - public int[] semicolonSeparated(); - } - - @Before - public void before() { - cfg = ConfigFactory.create(ConflictingAnnotationsResolved.class); - } - - @Test - public void testSeparatorAnnotationOnMethodLevelResolveTheConflictOnClassLevel() { - assertThat(cfg.commaSeparated(), is(new int[]{1, 2, 3, 4})); - } - - @Test - public void testTokenizerClassAnnotationOnMethodLevelResolveTheConflictOnClassLevel() { - assertThat(cfg.semicolonSeparated(), is(new int[]{1, 2, 3, 4})); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationsOnClassLevelTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationsOnClassLevelTest.java deleted file mode 100644 index 863a8acae..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationsOnClassLevelTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.Separator; -import org.aeonbits.owner.Config.TokenizerClass; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -/** - * @author Luigi R. Viggiano - */ -public class ConflictingAnnotationsOnClassLevelTest { - private ConflictingAnnotationsOnClassLevel cfg; - - @Before - public void before() { - cfg = ConfigFactory.create(ConflictingAnnotationsOnClassLevel.class); - } - - // should throw an exception when the first array conversion is invoked: @Tokenizer and @Separator annotations - // cannot be used together on class level. - @TokenizerClass(CustomCommaTokenizer.class) - @Separator(",") - public static interface ConflictingAnnotationsOnClassLevel extends Config { - @DefaultValue("1, 2, 3, 4") - public int[] commaSeparated(); - } - - @Test - public void testConflictingAnnotationsOnClassLevel() throws Throwable { - try { - cfg.commaSeparated(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException ex) { - assertThat(ex.getMessage(), - equalTo("You cannot specify @Separator and @TokenizerClass both together on class level for 'org" + - ".aeonbits.owner.typeconversion.arrays.ConflictingAnnotationsOnClassLevelTest" + - ".ConflictingAnnotationsOnClassLevel'")); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationsOnMethodLevelTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationsOnMethodLevelTest.java deleted file mode 100644 index 355587f85..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/ConflictingAnnotationsOnMethodLevelTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -/** - * @author Luigi R. Viggiano - */ -public class ConflictingAnnotationsOnMethodLevelTest { - private ConflictingAnnotationsOnMethodLevelConfig cfg; - - @Before - public void before() { - cfg = ConfigFactory.create(ConflictingAnnotationsOnMethodLevelConfig.class); - } - - public static interface ConflictingAnnotationsOnMethodLevelConfig extends Config { - // should throw an exception when invoked: cannot use both @Separator and @Tokenizer on method level - @Separator(";") - @TokenizerClass(CustomDashTokenizer.class) - @DefaultValue("0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55") - public int[] conflictingAnnotationsOnMethodLevel(); - } - - @Test - public void testConflictingAnnotationsOnMethodLevel() throws Exception { - try { - cfg.conflictingAnnotationsOnMethodLevel(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException ex) { - assertThat(ex.getMessage(), - equalTo("You cannot specify @Separator and @TokenizerClass both together on method level for " + - "'public abstract int[] org.aeonbits.owner.typeconversion.arrays" + - ".ConflictingAnnotationsOnMethodLevelTest$ConflictingAnnotationsOnMethodLevelConfig" + - ".conflictingAnnotationsOnMethodLevel()'")); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/CustomCommaTokenizer.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/CustomCommaTokenizer.java deleted file mode 100644 index 664176135..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/CustomCommaTokenizer.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Tokenizer; - -/** - * @author Luigi R. Viggiano - */ -public class CustomCommaTokenizer implements Tokenizer { - public String[] tokens(String values) { - return values.split(",", -1); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/CustomDashTokenizer.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/CustomDashTokenizer.java deleted file mode 100644 index 93c8d7330..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/CustomDashTokenizer.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Tokenizer; - -/** - * @author Luigi R. Viggiano - */ -public class CustomDashTokenizer implements Tokenizer { - public String[] tokens(String values) { - return values.split("-", -1); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/InvalidAnnotationTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/InvalidAnnotationTest.java deleted file mode 100644 index 33f6d6222..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/InvalidAnnotationTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.aeonbits.owner.Tokenizer; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * @author Luigi R. Viggiano - */ -public class InvalidAnnotationTest { - private InvalidAnnotationConfig cfg; - - @Before - public void before() { - cfg = ConfigFactory.create(InvalidAnnotationConfig.class); - } - - public static interface InvalidAnnotationConfig extends Config { - // it throws an exception since the Tokenizer class is declared as private - @TokenizerClass(NonInstantiableTokenizer.class) - @DefaultValue("1,2,3") - public int[] nonInstantiableTokenizer(); - } - - // it's private, it cannot be instantiated by the OWNER library - private static class NonInstantiableTokenizer extends CustomCommaTokenizer implements Tokenizer { - } - - @Test - public void testNonInstantiableTokenizer() throws Exception { - try { - cfg.nonInstantiableTokenizer(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException ex) { - // since NonInstantiableTokenizer is private and IllegalAccessException is expected. - assertTrue(ex.getCause() instanceof IllegalAccessException); - } - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/SeparatorAnnotationOnClassLevelTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/SeparatorAnnotationOnClassLevelTest.java deleted file mode 100644 index 81194d1c6..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/SeparatorAnnotationOnClassLevelTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.Separator; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -/** - * @author Luigi R. Viggiano - */ -public class SeparatorAnnotationOnClassLevelTest { - private ArrayConfigWithSeparatorAnnotationOnClassLevel cfg; - - @Before - public void before() { - cfg = ConfigFactory.create(ArrayConfigWithSeparatorAnnotationOnClassLevel.class); - } - - @Separator(";") - public static interface ArrayConfigWithSeparatorAnnotationOnClassLevel extends Config { - - @Separator(",") //should override the class-level @Separator - @DefaultValue("1, 2, 3, 4") - public int[] commaSeparated(); - - @DefaultValue("1; 2; 3; 4") - public int[] semicolonSeparated(); //should take the class level @Separator - - @TokenizerClass(CustomDashTokenizer.class) //should take the class level @Separator - @DefaultValue("1-2-3-4") - public int[] dashSeparated(); - } - - @Test - public void testSeparatorAnnotationOnMethodOverridingSeparatorAnnotationOnClassLevel() { - assertThat(cfg.commaSeparated(), is(new int[]{1, 2, 3, 4})); - } - - @Test - public void testSeparatorAnnotationOnClassLevelAndNoOverridingOnMethodLevel() { - assertThat(cfg.semicolonSeparated(), is(new int[]{1, 2, 3, 4})); - } - - @Test - public void testTokenClassAnnotationOnMethodLevelOverridingSeparatorOnClassLevel() { - assertThat(cfg.dashSeparated(), is(new int[]{1, 2, 3, 4})); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/TokenizerAnnotationOnClassLevelTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/TokenizerAnnotationOnClassLevelTest.java deleted file mode 100644 index eac51de7b..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/arrays/TokenizerAnnotationOnClassLevelTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.arrays; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.TokenizerClass; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -/** - * @author Luigi R. Viggiano - */ -public class TokenizerAnnotationOnClassLevelTest { - - private ArrayConfigWithTokenizerAnnotationOnClassLevel cfg; - - @Before - public void before() { - cfg = ConfigFactory.create(ArrayConfigWithTokenizerAnnotationOnClassLevel.class); - } - - @TokenizerClass(CustomDashTokenizer.class) - public static interface ArrayConfigWithTokenizerAnnotationOnClassLevel extends Config { - - @TokenizerClass(CustomCommaTokenizer.class) //should override the class-level @TokenizerClass - @DefaultValue("1,2,3,4") - public int[] commaSeparated(); - - @Separator(";") // overrides class level @TokenizerClass - @DefaultValue("1; 2; 3; 4") - public int[] semicolonSeparated(); - - @DefaultValue("1-2-3-4") - public int[] dashSeparated(); // class level @TokenizerClass applies - } - - @Test - public void testTokenizerClassAnnotationOnMethodLevelOverridingTokenizerClassAnnotationOnClassLevel() { - assertThat(cfg.commaSeparated(), is(new int[]{1, 2, 3, 4})); - } - - @Test - public void testSeparatorAnnotationOnMethodLevelOverridingTokenizerClassAnnotationOnClassLevel() { - assertThat(cfg.semicolonSeparated(), is(new int[]{1, 2, 3, 4})); - } - - @Test - public void testTokenizerClassAnnotationOnClassLevelAndNoOverridingOnMethodLevel() { - assertThat(cfg.dashSeparated(), is(new int[]{1, 2, 3, 4})); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/collections/CollectionSupportTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/collections/CollectionSupportTest.java deleted file mode 100644 index 03a5ffa0d..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/collections/CollectionSupportTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.collections; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.SortedSet; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -/** - * @author Dmytro Chyzhykov - */ -public class CollectionSupportTest { - private CollectionConfig cfg; - - public interface CollectionConfig extends Config { - String COLORS = "pink,black"; - String INTEGERS = "1, 2, 3"; - - @DefaultValue(COLORS) - Collection colors(); - - @DefaultValue(COLORS) - Set colorSet(); - - @DefaultValue(INTEGERS) - SortedSet integerSortedSet(); - - @DefaultValue(INTEGERS) - List integerList(); - - @DefaultValue(COLORS) - LinkedHashSet colorLinkedHashSet(); - - @DefaultValue(INTEGERS) - LinkedList integerLinkedList(); - - @DefaultValue(INTEGERS) - Collection rawCollection(); - - @DefaultValue(INTEGERS) - CollectionWithoutDefaultConstructor badCollection(); - } - - static class CollectionWithoutDefaultConstructor extends ArrayList { - public CollectionWithoutDefaultConstructor(int size) { - super(size); - } - } - - @Before - public void setUp() throws Exception { - cfg = ConfigFactory.create(CollectionConfig.class); - } - - @Test - public void itShouldReadCollectionOfStrings() throws Exception { - assertThat(cfg.colors(), containsInAnyOrder("pink", "black")); - } - - @Test - public void itShouldReadSetOfStrings() throws Exception { - assertThat(cfg.colorSet(), containsInAnyOrder("pink", "black")); - } - - @Test - public void itShouldReadSortedSetOfIntegers() throws Exception { - assertThat(cfg.integerSortedSet(), contains(1, 2, 3)); - } - - @Test - public void itShouldReadListOfIntegers() throws Exception { - assertThat(cfg.integerList(), contains(1, 2, 3)); - } - - @Test - public void itShouldReadConcreteSetImplementation() throws Exception { - assertThat(cfg.colorLinkedHashSet(), instanceOf(LinkedHashSet.class)); - assertThat(cfg.colorLinkedHashSet(), contains("pink", "black")); - } - - @Test - public void itShouldReadConcreteListImplementation() throws Exception { - assertThat(cfg.integerLinkedList(), instanceOf(LinkedList.class)); - assertThat(cfg.integerLinkedList(), contains(1, 2, 3)); - } - - @Test(expected = UnsupportedOperationException.class) - public void itShouldThrowExceptionWithCollectionWithoutDefaultConstructor() throws Exception { - cfg.badCollection(); - } - - @Test - public void itShouldWorkWithRawCollectionAsWithCollectionOfStrings() throws Exception { - assertEquals(Arrays.asList("1", "2", "3"), cfg.rawCollection()); - } - -} - diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorNotAvailable.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorNotAvailable.java deleted file mode 100644 index e17b2f0b2..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorNotAvailable.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.editor; - -import org.aeonbits.owner.typeconversion.PrimitiveTypesTest; -import org.junit.After; -import org.junit.Before; - -import static org.aeonbits.owner.typeconversion.editor.PropertyEditorTestUtil.PROPERTY_EDITOR_DISABLED; - -/** - * @author Luigi R. Viggiano - */ -public class PropertyEditorNotAvailable extends PrimitiveTypesTest { - - private String save; - - @Before - public void before() { - save = System.getProperty(PROPERTY_EDITOR_DISABLED); - System.setProperty(PROPERTY_EDITOR_DISABLED, "true"); - } - - @After - public void after() { - if (save == null) - System.getProperties().remove(PROPERTY_EDITOR_DISABLED); - else - System.setProperty(PROPERTY_EDITOR_DISABLED, save); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorTest.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorTest.java deleted file mode 100644 index d0c009b7f..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.editor; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Before; -import org.junit.Test; - -import java.beans.PropertyEditorManager; -import java.util.List; - -import static org.aeonbits.owner.typeconversion.editor.PropertyEditorTestUtil.assumePropertyEditorIsEnabled; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; - -/** - * @author Luigi R. Viggiano - */ -public class PropertyEditorTest { - - private MyAppConfig cfg; - - public interface MyAppConfig extends Config { - @DefaultValue("admin") - User user(); - - @DefaultValue("admin,root") - List users(); - } - - @Before - public void setUp() { - assumePropertyEditorIsEnabled(); - PropertyEditorManager.registerEditor(User.class, UserPropertyEditor.class); - cfg = ConfigFactory.create(MyAppConfig.class); - } - - @Test - public void testPropertyEditor() { - assertEquals("admin", cfg.user().getUsername()); - } - - @Test - public void testPropertyEditorWithList() { - List users = cfg.users(); - assertEquals("admin", users.get(0).getUsername()); - assertEquals("root", users.get(1).getUsername()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorTestUtil.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorTestUtil.java deleted file mode 100644 index 8e713ef24..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/PropertyEditorTestUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.editor; - -import org.aeonbits.owner.util.Reflection; - -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; - -/** - * @author Luigi R. Viggiano - */ -public class PropertyEditorTestUtil { - - public static final String PROPERTY_EDITOR_DISABLED = "org.aeonbits.owner.property.editor.disabled"; - - static void assumePropertyEditorIsEnabled() { - assumeFalse(Boolean.getBoolean(PROPERTY_EDITOR_DISABLED)); - assumeTrue(Reflection.isClassAvailable("java.beans.PropertyEditorManager")); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/User.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/User.java deleted file mode 100644 index a73a6cca5..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/User.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.editor; - -/** - * @author Luigi R. Viggiano - */ -public class User { - private String username; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/UserPropertyEditor.java b/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/UserPropertyEditor.java deleted file mode 100644 index 6111a3131..000000000 --- a/owner/src/test/java/org/aeonbits/owner/typeconversion/editor/UserPropertyEditor.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.typeconversion.editor; - -import java.beans.PropertyEditorSupport; - -/** - * @author Luigi R. Viggiano - */ -public class UserPropertyEditor extends PropertyEditorSupport { - @Override - public void setAsText(String text) throws IllegalArgumentException { - User user = new User(); - user.setUsername(text); - setValue(user); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/util/Base64Test.java b/owner/src/test/java/org/aeonbits/owner/util/Base64Test.java deleted file mode 100644 index dbe8f9524..000000000 --- a/owner/src/test/java/org/aeonbits/owner/util/Base64Test.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2012-2017, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import org.junit.Test; - -import java.util.Date; -import java.util.Random; - -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class Base64Test { - - @Test - public void testEncode() { - String input = "Hello World!"; - String result = Base64.encode(input.getBytes()); - assertEquals("SGVsbG8gV29ybGQh", result); - } - - @Test - public void testDecode() throws Exception { - String input = "SGVsbG8gV29ybGQh"; - byte[] result = Base64.decode(input); - assertEquals("Hello World!", new String(result)); - } - - @Test - public void encodeAndDecode() { - String input = "The date is: " + new Date() + ", a random number is: " + new Random().nextLong(); - - String encoded = Base64.encode(input.getBytes()); - byte[] result = Base64.decode(encoded); - - assertEquals(input, new String(result)); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/util/ReflectionTest.java b/owner/src/test/java/org/aeonbits/owner/util/ReflectionTest.java deleted file mode 100644 index f44b6cf94..000000000 --- a/owner/src/test/java/org/aeonbits/owner/util/ReflectionTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Luigi R. Viggiano - */ -public class ReflectionTest { - - @Test - public void testAvailableWithNonExistentClass() { - boolean available = Reflection.isClassAvailable("foo.bar.baz.FooBar"); - assertFalse(available); - } - - @Test - public void testAvailableWithExistentClass(){ - boolean available = Reflection.isClassAvailable("java.lang.String"); - assertTrue(available); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/util/SystemProviderForTest.java b/owner/src/test/java/org/aeonbits/owner/util/SystemProviderForTest.java deleted file mode 100644 index ff698580b..000000000 --- a/owner/src/test/java/org/aeonbits/owner/util/SystemProviderForTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2018, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import org.aeonbits.owner.util.Util.SystemProvider; - -import java.util.Map; -import java.util.Properties; - -/** - * @author Luigi R. Viggiano - */ -public class SystemProviderForTest implements SystemProvider { - - private final Properties system; - private final Map env; - - public SystemProviderForTest(Properties system, Map env) { - this.system = system; - this.env = env; - } - - public String getProperty(String key) { - return system.getProperty(key); - } - - public Map getenv() { - return env; - } - - public Properties getProperties() { - return system; - } - - public void setProperty(String key, String value) { - system.setProperty(key, value); - } - - public void remove(String key) { - system.remove(key); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/util/TimeProviderForTest.java b/owner/src/test/java/org/aeonbits/owner/util/TimeProviderForTest.java deleted file mode 100644 index 822759e0f..000000000 --- a/owner/src/test/java/org/aeonbits/owner/util/TimeProviderForTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2018, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import org.aeonbits.owner.util.Util.TimeProvider; - -import java.util.concurrent.TimeUnit; - -/** - * @author Luigi R. Viggiano - */ -public class TimeProviderForTest implements TimeProvider { - - private TimeProvider backup; - - private long time; - - public TimeProviderForTest() { - this.time = System.currentTimeMillis(); - } - - public void elapse(long interval, TimeUnit unit) { - time += unit.toMillis(interval); - } - - public long getTime() { - return time; - } - - public void setup() { - backup = Util.timeProvider; - Util.timeProvider = this; - } - - public void tearDown() { - Util.timeProvider = backup; - } - - public void setTime(long time) { - this.time = time; - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/util/UtilTest.java b/owner/src/test/java/org/aeonbits/owner/util/UtilTest.java deleted file mode 100644 index 6b5d442d9..000000000 --- a/owner/src/test/java/org/aeonbits/owner/util/UtilTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2012-2018, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.util; - -import org.aeonbits.owner.util.Util.SystemProvider; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Array; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import static org.aeonbits.owner.util.Util.ignore; -import static org.aeonbits.owner.util.Util.unreachableButCompilerNeedsThis; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * This class contains tests for the {@link Util} class as well utility methods used for test classes. - * - * @author Luigi R. Viggiano - */ -public class UtilTest { - - public static SystemProvider setSystem(Object system) { - SystemProvider save = Util.system; - Util.system = (SystemProvider)system; - return save; - } - - public static Properties getSystemProperties() { - return Util.system().getProperties(); - } - - public SystemProvider system() { - return Util.system(); - } - - @Test - public void testReverse() { - Integer[] i = {1, 2, 3, 4, 5}; - Integer[] result = Util.reverse(i); - assertTrue(Arrays.equals(new Integer[] {1, 2, 3, 4, 5}, i)); - assertTrue(Arrays.equals(new Integer[] {5, 4, 3, 2, 1}, result)); - } - - @Test - public void testIgnoreAndReturnNull() { - Object result = ignoreAndReturnNull(); - assertNull(result); - } - - @Test - public void testIgnore() { - ignore(); - } - - @Test - public void testUnreachable() { - try { - unreachableButCompilerNeedsThis(); - } catch (AssertionError err) { - assertEquals("this code should never be reached", err.getMessage()); - } - } - - public static void save(File target, Properties p) throws IOException { - Util.save(target, p); - } - - public static void delete(File target) { - Util.delete(target); - } - - public static void saveJar(File target, String entryName, Properties props) throws IOException { - Util.saveJar(target, entryName, props); - } - - public static void debug(String format, Object... args) { - if (Boolean.getBoolean("debug")) - System.out.printf(format, args); - } - - public static T ignoreAndReturnNull() { - return Util.ignoreAndReturnNull(); - } - - public static File fileFromURI(String spec) throws URISyntaxException { - return Util.fileFromURI(spec); - } - - public static String getSystemProperty(String key) { - return Util.system().getProperty(key); - } - - public static String getenv(String home) { - return Util.system().getenv().get(home); - } - - public static Map getenv() { - return Util.system().getenv(); - } - - public interface MyCloneable extends Cloneable { - // for some stupid reason java.lang.Cloneable doesn't define this method... - Object clone() throws CloneNotSupportedException; - } - - @SuppressWarnings("unchecked") - public static T[] newArray(int size, T cloneable) throws CloneNotSupportedException { - Object array = Array.newInstance(cloneable.getClass(), size); - Array.set(array, 0, cloneable); - for (int i = 1; i < size; i++) - Array.set(array, i, cloneable.clone()); - return (T[]) array; - } - - public static boolean eq(Object o1, Object o2) { - return Util.eq(o1, o2); - } - - @Test - public void testExpandUserHomeOnUnix() { - SystemProvider save = UtilTest.setSystem(new SystemProviderForTest( - new Properties() {{ - setProperty("user.home", "/home/john"); - }}, new HashMap() - )); - - try { - assertEquals("/home/john", Util.expandUserHome("~")); - assertEquals("/home/john/foo/bar/", Util.expandUserHome("~/foo/bar/")); - assertEquals("file:/home/john/foo/bar/", Util.expandUserHome("file:~/foo/bar/")); - assertEquals("jar:file:/home/john/foo/bar/", Util.expandUserHome("jar:file:~/foo/bar/")); - - assertEquals("/home/john\\foo\\bar\\", Util.expandUserHome("~\\foo\\bar\\")); - assertEquals("file:/home/john\\foo\\bar\\", Util.expandUserHome("file:~\\foo\\bar\\")); - assertEquals("jar:file:/home/john\\foo\\bar\\", Util.expandUserHome("jar:file:~\\foo\\bar\\")); - } finally { - UtilTest.setSystem(save); - } - } - - @Test - public void testExpandUserHomeOnWindows() { - SystemProvider save = UtilTest.setSystem(new SystemProviderForTest( - new Properties() {{ - setProperty("user.home", "C:\\Users\\John"); - }}, new HashMap() - )); - try { - assertEquals("C:\\Users\\John", Util.expandUserHome("~")); - assertEquals("C:\\Users\\John/foo/bar/", Util.expandUserHome("~/foo/bar/")); - assertEquals("file:C:\\Users\\John/foo/bar/", Util.expandUserHome("file:~/foo/bar/")); - assertEquals("jar:file:C:\\Users\\John/foo/bar/", Util.expandUserHome("jar:file:~/foo/bar/")); - - assertEquals("C:\\Users\\John\\foo\\bar\\", Util.expandUserHome("~\\foo\\bar\\")); - assertEquals("file:C:\\Users\\John\\foo\\bar\\", Util.expandUserHome("file:~\\foo\\bar\\")); - assertEquals("jar:file:C:\\Users\\John\\foo\\bar\\", Util.expandUserHome("jar:file:~\\foo\\bar\\")); - } finally { - UtilTest.setSystem(save); - } - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/variableexpansion/KeyExpansionTest.java b/owner/src/test/java/org/aeonbits/owner/variableexpansion/KeyExpansionTest.java deleted file mode 100644 index 13cb9a63c..000000000 --- a/owner/src/test/java/org/aeonbits/owner/variableexpansion/KeyExpansionTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.variableexpansion; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.DisableFeature; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import static org.aeonbits.owner.Config.DisableableFeature.VARIABLE_EXPANSION; -import static org.aeonbits.owner.util.Collections.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Luigi R. Viggiano - */ -public class KeyExpansionTest { - - - @Sources("classpath:org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml") - public interface MyConfig extends Config { - @Key("servers.${env}.name") - String name(); - - @Key("servers.${env}.hostname") - String hostname(); - - @Key("servers.${env}.port") - Integer port(); - - @Key("servers.${env}.user") - String user(); - - @DisableFeature(VARIABLE_EXPANSION) - @Key("servers.${env}.password") - String password(); - } - - @Test - public void testKeyExpansion() { - MyConfig cfg = ConfigFactory.create(MyConfig.class, map("env", "dev")); - - assertEquals("DEV", cfg.name()); - assertEquals("devhost", cfg.hostname()); - assertEquals(new Integer(6000), cfg.port()); - assertEquals("myuser1", cfg.user()); - assertNull(cfg.password()); // expansion is disabled on method level - } - - @DisableFeature(VARIABLE_EXPANSION) - @Sources("classpath:org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml") - public interface MyConfigWithExpansionDisabled extends Config { - @Key("servers.${env}.name") - String name(); - - @Key("servers.${env}.hostname") - String hostname(); - - @Key("servers.${env}.port") - Integer port(); - - @Key("servers.${env}.user") - String user(); - - @Key("servers.${env}.password") - String password(); - } - - @Test - public void testKeyExpansionDisabled() { - MyConfigWithExpansionDisabled cfg = - ConfigFactory.create(MyConfigWithExpansionDisabled.class, map("env", "dev")); - - assertNull(cfg.name()); - assertNull(cfg.hostname()); - assertNull(cfg.port()); - assertNull(cfg.user()); - assertNull(cfg.password()); - } - - @Sources("classpath:org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml") - public interface ExpandsFromAnotherKey extends Config { - - @DefaultValue("dev") - String env(); - - @Key("servers.${env}.name") - String name(); - - @Key("servers.${env}.hostname") - String hostname(); - - @Key("servers.${env}.port") - Integer port(); - - @Key("servers.${env}.user") - String user(); - - @DisableFeature(VARIABLE_EXPANSION) - @Key("servers.${env}.password") - String password(); - } - - @Test - public void testKeyExpansionFromAnotherKey() { - ExpandsFromAnotherKey cfg = ConfigFactory.create(ExpandsFromAnotherKey.class); - - assertEquals("DEV", cfg.name()); - assertEquals("devhost", cfg.hostname()); - assertEquals(new Integer(6000), cfg.port()); - assertEquals("myuser1", cfg.user()); - assertNull(cfg.password()); // expansion is disabled on method level - } - - @Test - public void testKeyExpansionFromAnotherKeyWithImportOverriding() { - ExpandsFromAnotherKey cfg = ConfigFactory.create(ExpandsFromAnotherKey.class, map("env", "uat")); - - assertEquals("UAT", cfg.name()); - assertEquals("uathost", cfg.hostname()); - assertEquals(new Integer(60020), cfg.port()); - assertEquals("myuser2", cfg.user()); - assertNull("mypass2", cfg.password()); // expansion is disabled on method level - } - - @Sources("classpath:org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml") - public interface UseOfDefaultValueIfNotFound extends Config { - - @DefaultValue("dev") - String env(); - - @Config.Key("servers.${env}.nonDefinedInSourceKey") - @Config.DefaultValue("wantedValue") - String undefinedPropInSource(); - - } - - @Test - public void testKeyExpansionAndDefaultValue() { - UseOfDefaultValueIfNotFound cfg = ConfigFactory.create(UseOfDefaultValueIfNotFound.class); - - assertEquals("dev", cfg.env()); - assertEquals("wantedValue", cfg.undefinedPropInSource()); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/variableexpansion/ParametrizedKeyTest.java b/owner/src/test/java/org/aeonbits/owner/variableexpansion/ParametrizedKeyTest.java deleted file mode 100644 index 1cb019100..000000000 --- a/owner/src/test/java/org/aeonbits/owner/variableexpansion/ParametrizedKeyTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.aeonbits.owner.variableexpansion; - -import static org.aeonbits.owner.Config.DisableableFeature.VARIABLE_EXPANSION; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -/** - * @author aknopov - */ -public class ParametrizedKeyTest -{ - private static final String DEV_SETUP = "dev"; - private static final String UAT_SETUP = "uat"; - - @Config.Sources("classpath:org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml") - public interface MyConfig extends Config { - @Key("servers.%s.name") - String name(String setup); - - @Key("servers.%s.hostname") - String hostname(String setup); - - @Key("servers.%s.port") - Integer port(String setup); - - @Key("servers.%s.user") - String user(String setup); - - @DisableFeature(VARIABLE_EXPANSION) - @Key("servers.%s.password") - String password(String setup); - } - - @Test - public void testKeyParametrization() { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - - assertEquals("DEV", cfg.name(DEV_SETUP)); - assertEquals("devhost", cfg.hostname(DEV_SETUP)); - assertEquals(new Integer(6000), cfg.port(DEV_SETUP)); - assertEquals("myuser1", cfg.user(DEV_SETUP)); - assertNull(cfg.password(DEV_SETUP)); // expansion is disabled on method level - - assertEquals("UAT", cfg.name(UAT_SETUP)); - assertEquals("uathost", cfg.hostname(UAT_SETUP)); - assertEquals(new Integer(60020), cfg.port(UAT_SETUP)); - assertEquals("myuser2", cfg.user(UAT_SETUP)); - assertNull(cfg.password(UAT_SETUP)); // expansion is disabled on method level - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/variableexpansion/PropertyNotSetTest.java b/owner/src/test/java/org/aeonbits/owner/variableexpansion/PropertyNotSetTest.java deleted file mode 100644 index 92b6b30dd..000000000 --- a/owner/src/test/java/org/aeonbits/owner/variableexpansion/PropertyNotSetTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.variableexpansion; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * Tests properties resolution. - * - * @author Luigi R. Viggiano - */ -public class PropertyNotSetTest { - - public interface MyConfig extends Config { - @DefaultValue("Hello ${world}.") - String foo(); - } - - @Test - public void testPropertyNotSet() { - MyConfig cfg = ConfigFactory.create(MyConfig.class); - assertEquals("Hello .", cfg.foo()); - } - - @Test - public void testPropertySet() { - Map ctx = new HashMap() {{ - put("world", "Earth"); - }}; - MyConfig cfg = ConfigFactory.create(MyConfig.class, ctx); - assertEquals("Hello Earth.", cfg.foo()); - } - - @Test - public void testPropertyChanged() { - Map ctx = new HashMap() {{ - put("world", "Earth"); - }}; - MyConfig cfg = ConfigFactory.create(MyConfig.class, ctx); - - ctx.put("world", "Mars"); - assertEquals("Hello Earth.", cfg.foo()); - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/variableexpansion/VariableExpansionTest.java b/owner/src/test/java/org/aeonbits/owner/variableexpansion/VariableExpansionTest.java deleted file mode 100644 index 4871475a6..000000000 --- a/owner/src/test/java/org/aeonbits/owner/variableexpansion/VariableExpansionTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.variableexpansion; - -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Config.Sources; -import org.aeonbits.owner.ConfigFactory; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author Luigi R. Viggiano - */ -public class VariableExpansionTest { - @Sources({"classpath:test.properties"}) - public interface SampleConfigWithExpansion extends Config { - String favoriteColor(); - } - - @Test - public void testPropertyWithExpansion() { - SampleConfigWithExpansion config = ConfigFactory.create - (SampleConfigWithExpansion.class); - assertEquals("pink", config.favoriteColor()); - } - -} diff --git a/owner/src/test/java/org/aeonbits/owner/xml/SAXParserFactoryForTest.java b/owner/src/test/java/org/aeonbits/owner/xml/SAXParserFactoryForTest.java deleted file mode 100644 index fc53b3b79..000000000 --- a/owner/src/test/java/org/aeonbits/owner/xml/SAXParserFactoryForTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.xml; - -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -/** - * @author Luigi R. Viggiano - */ -public class SAXParserFactoryForTest extends SAXParserFactory { - private static SAXParserFactory delegate; - - @Override - public SAXParser newSAXParser() throws ParserConfigurationException, SAXException { - return delegate.newSAXParser(); - } - - @Override - public void setFeature(String name, boolean value) throws ParserConfigurationException, - SAXNotRecognizedException, SAXNotSupportedException { - delegate.setFeature(name, value); - } - - @Override - public boolean getFeature(String name) throws ParserConfigurationException, SAXNotRecognizedException, - SAXNotSupportedException { - return delegate.getFeature(name); - } - - public static void setDelegate(SAXParserFactory delegate) { - SAXParserFactoryForTest.delegate = delegate; - } -} diff --git a/owner/src/test/java/org/aeonbits/owner/xml/XmlSourceTest.java b/owner/src/test/java/org/aeonbits/owner/xml/XmlSourceTest.java deleted file mode 100644 index 47331794f..000000000 --- a/owner/src/test/java/org/aeonbits/owner/xml/XmlSourceTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2012-2015, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner.xml; - -import org.aeonbits.owner.Accessible; -import org.aeonbits.owner.Config; -import org.aeonbits.owner.Factory; -import org.aeonbits.owner.TestConstants; -import org.junit.Before; -import org.junit.Test; -import org.xml.sax.SAXException; - -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParserFactory; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; - -import static org.aeonbits.owner.ConfigFactory.newInstance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - -/** - * @author Luigi R. Viggiano - */ -public class XmlSourceTest implements TestConstants { - - private Factory factory; - - public static interface ServerConfig extends Config, Accessible { - - @Key("server.http.port") - int httpPort(); - - @Key("server.http.hostname") - String httpHostname(); - - @Key("server.ssh.port") - int sshPort(); - - @Key("server.ssh.address") - String sshAddress(); - - @Key("server.ssh.alive.interval") - int aliveInterval(); - - @Key("server.ssh.user") - String sshUser(); - } - - @Before - public void before() { - factory = newInstance(); - } - - @Test - public void testXmlReading() { - ServerConfig cfg = factory.create(ServerConfig.class); - assertEquals(80, cfg.httpPort()); - assertEquals("localhost", cfg.httpHostname()); - assertEquals(22, cfg.sshPort()); - assertEquals("127.0.0.1", cfg.sshAddress()); - assertEquals(60, cfg.aliveInterval()); - assertEquals("admin", cfg.sshUser()); - } - - @Test - public void testStoreToXML() throws IOException { - ServerConfig cfg = factory.create(ServerConfig.class); - File target = new File(RESOURCES_DIR + "/XmlSourceTest$ServerConfig.properties.xml"); - target.getParentFile().mkdirs(); - cfg.storeToXML(new FileOutputStream(target), "this is an example"); - - Properties props = new Properties(); - props.loadFromXML(new FileInputStream(target)); - - assertEquals(String.valueOf(cfg.httpPort()), props.getProperty("server.http.port")); - assertEquals(cfg.httpHostname(), props.getProperty("server.http.hostname")); - assertEquals(String.valueOf(cfg.sshPort()), props.getProperty("server.ssh.port")); - assertEquals(cfg.sshAddress(), props.getProperty("server.ssh.address")); - assertEquals(String.valueOf(cfg.aliveInterval()), props.getProperty("server.ssh.alive.interval")); - assertEquals(cfg.sshUser(), props.getProperty("server.ssh.user")); - } - - static interface ServerConfigJavaFormat extends ServerConfig { - } - - @Test - public void testXmlReadingJavaFormat() { - ServerConfigJavaFormat cfg = factory.create(ServerConfigJavaFormat.class); - assertEquals(8080, cfg.httpPort()); - assertEquals("foobar", cfg.httpHostname()); - assertEquals(2222, cfg.sshPort()); - assertEquals("10.0.0.1", cfg.sshAddress()); - assertEquals(30, cfg.aliveInterval()); - assertEquals("root", cfg.sshUser()); - } - - @Test(expected = FactoryConfigurationError.class) - public void testSAXParserMisconfigured() { - System.setProperty("javax.xml.parsers.SAXParserFactory", "foo.bar.baz"); - try { - factory.create(ServerConfigJavaFormat.class); - } finally { - System.getProperties().remove("javax.xml.parsers.SAXParserFactory"); - } - } - - static interface ServerConfigInvalid extends ServerConfig { - } - - @Test - public void testServerConfigInvalid() throws Throwable { - ServerConfigInvalid cfg = factory.create(ServerConfigInvalid.class); - assertNull(cfg.httpHostname()); - } - - @Test - public void testParserConfigurationException() throws ParserConfigurationException, SAXException { - SAXParserFactory saxFactory = mock(SAXParserFactory.class); - ParserConfigurationException expected = new ParserConfigurationException(); - doThrow(expected).when(saxFactory).newSAXParser(); - - SAXParserFactoryForTest.setDelegate(saxFactory); - - System.setProperty("javax.xml.parsers.SAXParserFactory", SAXParserFactoryForTest.class.getName()); - try { - factory.create(ServerConfigJavaFormat.class); - fail("exception is expected"); - } catch (IllegalArgumentException ex) { - assertSame(expected, ex.getCause()); - } finally { - System.getProperties().remove("javax.xml.parsers.SAXParserFactory"); - } - } - -} diff --git a/owner/src/test/resources/org/aeonbits/owner/ConfigTest$SampleConfig.properties b/owner/src/test/resources/org/aeonbits/owner/ConfigTest$SampleConfig.properties deleted file mode 100644 index d50034a1e..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/ConfigTest$SampleConfig.properties +++ /dev/null @@ -1,13 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -hello=Hello %s. -favoriteSong=Speechless - Lady Gaga -server.http.port=80 -salutation.text=Good Afternoon -unsupportedTypeProperty=dummy value: this is unsupported diff --git a/owner/src/test/resources/org/aeonbits/owner/ConfigWithSubstitutionTest$ConfigWithSubstitutionFile.properties b/owner/src/test/resources/org/aeonbits/owner/ConfigWithSubstitutionTest$ConfigWithSubstitutionFile.properties deleted file mode 100644 index 2ab1a3b6d..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/ConfigWithSubstitutionTest$ConfigWithSubstitutionFile.properties +++ /dev/null @@ -1,13 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -story=The ${animal} jumped over the ${target} -animal=quick ${color} fox -target=${target.attribute} dog -target.attribute=lazy -color=brown \ No newline at end of file diff --git a/owner/src/test/resources/org/aeonbits/owner/FooBar.properties b/owner/src/test/resources/org/aeonbits/owner/FooBar.properties deleted file mode 100644 index c8816bdfc..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/FooBar.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -helloWorld = Hello World! \ No newline at end of file diff --git a/owner/src/test/resources/org/aeonbits/owner/LoaderManagerTest$MyConfigDefaultSpec.foobar b/owner/src/test/resources/org/aeonbits/owner/LoaderManagerTest$MyConfigDefaultSpec.foobar deleted file mode 100644 index b5236dc60..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/LoaderManagerTest$MyConfigDefaultSpec.foobar +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -foo=foobar diff --git a/owner/src/test/resources/org/aeonbits/owner/LoaderManagerTest$MyConfigDefaultSpec.properties b/owner/src/test/resources/org/aeonbits/owner/LoaderManagerTest$MyConfigDefaultSpec.properties deleted file mode 100644 index 8ce716064..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/LoaderManagerTest$MyConfigDefaultSpec.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -foo=bar diff --git a/owner/src/test/resources/org/aeonbits/owner/directory with spaces/simple.properties b/owner/src/test/resources/org/aeonbits/owner/directory with spaces/simple.properties deleted file mode 100644 index 0046c2b1f..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/directory with spaces/simple.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -helloWorld = Hello World! diff --git a/owner/src/test/resources/org/aeonbits/owner/first.properties b/owner/src/test/resources/org/aeonbits/owner/first.properties deleted file mode 100644 index a170f1098..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/first.properties +++ /dev/null @@ -1,10 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -foo=first -baz=first \ No newline at end of file diff --git a/owner/src/test/resources/org/aeonbits/owner/importedprops/ImportConfigTest$ImportedPropertiesHaveHigherPriority.properties b/owner/src/test/resources/org/aeonbits/owner/importedprops/ImportConfigTest$ImportedPropertiesHaveHigherPriority.properties deleted file mode 100644 index 12febec79..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/importedprops/ImportConfigTest$ImportedPropertiesHaveHigherPriority.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -minAge=18 diff --git a/owner/src/test/resources/org/aeonbits/owner/importedprops/WithImportedPropertiesTest$WithImportedProperties.properties b/owner/src/test/resources/org/aeonbits/owner/importedprops/WithImportedPropertiesTest$WithImportedProperties.properties deleted file mode 100644 index cf8669bda..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/importedprops/WithImportedPropertiesTest$WithImportedProperties.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -someValue=testing replacement from ${external} properties file. \ No newline at end of file diff --git a/owner/src/test/resources/org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest$SampleConfig.properties b/owner/src/test/resources/org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest$SampleConfig.properties deleted file mode 100644 index 38cffd01b..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest$SampleConfig.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -testKey=testValue diff --git a/owner/src/test/resources/org/aeonbits/owner/second.properties b/owner/src/test/resources/org/aeonbits/owner/second.properties deleted file mode 100644 index 7fa0001a0..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/second.properties +++ /dev/null @@ -1,10 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -foo=second -bar=second \ No newline at end of file diff --git a/owner/src/test/resources/org/aeonbits/owner/third.properties b/owner/src/test/resources/org/aeonbits/owner/third.properties deleted file mode 100644 index 871b8eee7..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/third.properties +++ /dev/null @@ -1,12 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -foo=third -bar=third -baz=third -qux=third \ No newline at end of file diff --git a/owner/src/test/resources/org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml b/owner/src/test/resources/org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml deleted file mode 100644 index 25abca34f..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/variableexpansion/KeyExpansionExample.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - DEV - devhost - 6000 - myuser1 - mypass1 - - - UAT - uathost - 60020 - myuser2 - mypass2 - - diff --git a/owner/src/test/resources/org/aeonbits/owner/xml/Config.xml b/owner/src/test/resources/org/aeonbits/owner/xml/Config.xml deleted file mode 100644 index e48638f66..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/xml/Config.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - fooValue - or properties -foo=bar]]> - - - quux - - diff --git a/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfig.xml b/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfig.xml deleted file mode 100644 index b1a8be9f8..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfig.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - localhost - - -
127.0.0.1
- - admin -
-
diff --git a/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfigInvalid.xml b/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfigInvalid.xml deleted file mode 100644 index 69d42711c..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfigInvalid.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - this is an example - 8080 - foobar - 2222 - 10.0.0.1 - 30 - root - diff --git a/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfigJavaFormat.xml b/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfigJavaFormat.xml deleted file mode 100644 index 52bec73ac..000000000 --- a/owner/src/test/resources/org/aeonbits/owner/xml/XmlSourceTest$ServerConfigJavaFormat.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - this is an example - 8080 - foobar - 2222 - 10.0.0.1 - 30 - root - diff --git a/owner/src/test/resources/test.properties b/owner/src/test/resources/test.properties deleted file mode 100644 index c2b073e54..000000000 --- a/owner/src/test/resources/test.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2012-2015, Luigi R. Viggiano -# All rights reserved. -# -# This software is distributable under the BSD license. -# See the terms of the BSD license in the documentation provided with this software. -# - -favoriteColor=pink \ No newline at end of file diff --git a/phileas-configuration/pom.xml b/phileas-configuration/pom.xml deleted file mode 100644 index 0340185be..000000000 --- a/phileas-configuration/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - 4.0.0 - - phileas - ai.philterd - 2.6.0-SNAPSHOT - - ai.philterd - phileas-configuration - phileas-configuration - - - ai.philterd - owner - ${project.version} - - - org.junit.jupiter - junit-jupiter-api - ${junit.version} - test - - - \ No newline at end of file diff --git a/phileas-configuration/src/main/java/ai/philterd/phileas/configuration/PhileasConfiguration.java b/phileas-configuration/src/main/java/ai/philterd/phileas/configuration/PhileasConfiguration.java deleted file mode 100644 index 0e382d99d..000000000 --- a/phileas-configuration/src/main/java/ai/philterd/phileas/configuration/PhileasConfiguration.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2023 Philterd, LLC @ https://www.philterd.ai - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package ai.philterd.phileas.configuration; - -import org.aeonbits.owner.Config; - -/** - * Phileas configuration using Aeonbits OWNER. - * Not all of the properties exposed through this file may be documented. - */ -@Config.LoadPolicy(Config.LoadType.MERGE) -@Config.Sources({ - "system:env", - "system:properties", - "file:philter.properties" -}) -public interface PhileasConfiguration extends Config { - - // General - @DefaultValue("./indexes/") - @Key("indexes.directory") - String indexesDirectory(); - - @DefaultValue("http://localhost:18080/") - @Key("ner.endpoint") - String philterNerEndpoint(); - - // Timeouts for connection to Philter NER. - - @DefaultValue("600") - @Key("ner.timeout.sec") - int nerTimeoutSec(); - - @DefaultValue("30") - @Key("ner.max.idle.connections") - int nerMaxIdleConnections(); - - @DefaultValue("60") - @Key("ner.keep.alive.duration.ms") - int nerKeepAliveDurationMs(); - - // Span Disambiguation - @DefaultValue("false") - @Key("span.disambiguation.enabled") - boolean spanDisambiguationEnabled(); - - @DefaultValue("murmur3") - @Key("span.disambiguation.hash.algorithm") - String spanDisambiguationHashAlgorithm(); - - @DefaultValue("5") - @Key("span.window.size") - int spanWindowSize(); - - @DefaultValue("512") - @Key("span.disambiguation.vector.size") - int spanDisambiguationVectorSize(); - - @DefaultValue("true") - @Key("span.disambiguation.ignore.stopwords") - boolean spanDisambiguationIgnoreStopWords(); - - @DefaultValue("a, as, able, about, above, according, accordingly, across, actually, after, afterwards, again, against, aint, all, allow, allows, almost, alone, along, already, also, although, always, am, among, amongst, an, and, another, any, anybody, anyhow, anyone, anything, anyway, anyways, anywhere, apart, appear, appreciate, appropriate, are, arent, around, as, aside, ask, asking, associated, at, available, away, awfully, be, became, because, become, becomes, becoming, been, before, beforehand, behind, being, believe, below, beside, besides, best, better, between, beyond, both, brief, but, by, cmon, cs, came, can, cant, cannot, cant, cause, causes, certain, certainly, changes, clearly, co, com, come, comes, concerning, consequently, consider, considering, contain, containing, contains, corresponding, could, couldnt, course, currently, definitely, described, despite, did, didnt, different, do, does, doesnt, doing, dont, done, down, downwards, during, each, edu, eg, eight, either, else, elsewhere, enough, entirely, especially, et, etc, even, ever, every, everybody, everyone, everything, everywhere, ex, exactly, example, except, far, few, ff, fifth, first, five, followed, following, follows, for, former, formerly, forth, four, from, further, furthermore, get, gets, getting, given, gives, go, goes, going, gone, got, gotten, greetings, had, hadnt, happens, hardly, has, hasnt, have, havent, having, he, hes, hello, help, hence, her, here, heres, hereafter, hereby, herein, hereupon, hers, herself, hi, him, himself, his, hither, hopefully, how, howbeit, however, i, id, ill, im, ive, ie, if, ignored, immediate, in, inasmuch, inc, indeed, indicate, indicated, indicates, inner, insofar, instead, into, inward, is, isnt, it, itd, itll, its, its, itself, just, keep, keeps, kept, know, knows, known, last, lately, later, latter, latterly, least, less, lest, let, lets, like, liked, likely, little, look, looking, looks, ltd, mainly, many, may, maybe, me, mean, meanwhile, merely, might, more, moreover, most, mostly, much, must, my, myself, name, namely, nd, near, nearly, necessary, need, needs, neither, never, nevertheless, new, next, nine, no, nobody, non, none, noone, nor, normally, not, nothing, novel, now, nowhere, obviously, of, off, often, oh, ok, okay, old, on, once, one, ones, only, onto, or, other, others, otherwise, ought, our, ours, ourselves, out, outside, over, overall, own, particular, particularly, per, perhaps, placed, please, plus, possible, presumably, probably, provides, que, quite, qv, rather, rd, re, really, reasonably, regarding, regardless, regards, relatively, respectively, right, said, same, saw, say, saying, says, second, secondly, see, seeing, seem, seemed, seeming, seems, seen, self, selves, sensible, sent, serious, seriously, seven, several, shall, she, should, shouldnt, since, six, so, some, somebody, somehow, someone, something, sometime, sometimes, somewhat, somewhere, soon, sorry, specified, specify, specifying, still, sub, such, sup, sure, ts, take, taken, tell, tends, th, than, thank, thanks, thanx, that, thats, thats, the, their, theirs, them, themselves, then, thence, there, theres, thereafter, thereby, therefore, therein, theres, thereupon, these, they, theyd, theyll, theyre, theyve, think, third, this, thorough, thoroughly, those, though, through, throughout, thru, thus, to, together, too, took, toward, towards, tried, tries, truly, try, trying, twice, two, un, under, unfortunately, unless, unlikely, until, unto, up, upon, us, use, used, useful, uses, using, usually, value, various, very, via, viz, vs, want, wants, was, wasnt, way, we, wed, well, were, weve, welcome, well, went, were, werent, what, whats, whatever, when, whence, whenever, where, wheres, whereafter, whereas, whereby, wherein, whereupon, wherever, whether, which, while, whither, who, whos, whoever, whole, whom, whose, why, will, willing, wish, with, within, without, wont, wonder, would, would, wouldnt, yes, yet, you, youd, youll, youre, youve, your, yours, yourself, yourselves") - @Key("span.disambiguation.stopwords") - String spanDisambiguationStopWords(); - - // Bloom filter for custom dictionary filters. - @DefaultValue("0.05") - @Key("filter.fpp") - double bloomFilterFpp(); - - // Cache Service - @DefaultValue("false") - @Key("cache.redis.enabled") - boolean cacheRedisEnabled(); - - @DefaultValue("false") - @Key("cache.redis.cluster") - boolean cacheRedisCluster(); - - @Key("cache.redis.host") - String cacheRedisHost(); - - @Key("cache.redis.port") - int cacheRedisPort(); - - @Key("cache.redis.auth.token") - String cacheRedisAuthToken(); - - @DefaultValue("false") - @Key("cache.redis.ssl") - boolean cacheRedisSsl(); - - @Key("cache.redis.truststore") - String cacheRedisTrustStore(); - - @Key("cache.redis.truststore.password") - String cacheRedisTrustStorePassword(); - - @Key("cache.redis.keystore") - String cacheRedisKeyStore(); - - @Key("cache.redis.keystore.password") - String cacheRedisKeyStorePassword(); - - // Policies - @DefaultValue("./policies/") - @Key("filter.policies.directory") - String policiesDirectory(); - - @Key("filter.policies.s3.bucket") - String policiesS3Bucket(); - - @DefaultValue("") - @Key("filter.policies.s3.prefix") - String policiesS3Prefix(); - - @DefaultValue("us-east-1") - @Key("filter.policies.s3.region") - String policiesS3Region(); - - // Metrics - @DefaultValue("philter") - @Key("metrics.prefix") - String metricsPrefix(); - - // See: https://github.com/micrometer-metrics/micrometer/blob/master/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusConfig.java - // The step size to use in computing windowed statistics like max. The default is 1 minute. - // To get the most out of these statistics, align the step interval to be close to your scrape interval. - @DefaultValue("60") - @Key("metrics.step") - int metricsStep(); - - @DefaultValue("false") - @Key("metrics.jmx.enabled") - boolean metricsJmxEnabled(); - - @DefaultValue("false") - @Key("metrics.prometheus.enabled") - boolean metricsPrometheusEnabled(); - - @DefaultValue("9100") - @Key("metrics.prometheus.port") - int metricsPrometheusPort(); - - @DefaultValue("metrics") - @Key("metrics.prometheus.metrics") - String metricsPrometheusContext(); - - @DefaultValue("false") - @Key("metrics.datadog.enabled") - boolean metricsDataDogEnabled(); - - @Key("metrics.datadog.apikey") - String metricsDataDogApiKey(); - - @DefaultValue("false") - @Key("metrics.cloudwatch.enabled") - boolean metricsCloudWatchEnabled(); - - @DefaultValue("us-east-1") - @Key("metrics.cloudwatch.region") - String metricsCloudWatchRegion(); - - @Key("metrics.cloudwatch.namespace") - String metricsCloudWatchNamespace(); - - @Key("metrics.hostname") - String metricsHostname(); - -} diff --git a/phileas-configuration/src/test/resources/log4j2.xml b/phileas-configuration/src/test/resources/log4j2.xml deleted file mode 100644 index 5e042d359..000000000 --- a/phileas-configuration/src/test/resources/log4j2.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - diff --git a/phileas-core/pom.xml b/phileas-core/pom.xml index ee1ec00b0..248cea531 100644 --- a/phileas-core/pom.xml +++ b/phileas-core/pom.xml @@ -11,14 +11,6 @@ phileas-core phileas-core - - - Mountain Fog Commercial License - https://www.mtnfog.com - manual - Phileas is proprietary closed-source software. - - ai.philterd @@ -70,11 +62,6 @@ phileas-services-alerts ${project.version} - - ai.philterd - phileas-configuration - ${project.version} - org.jsoup jsoup @@ -148,7 +135,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-core/src/main/java/ai/philterd/phileas/services/PhileasFilterService.java b/phileas-core/src/main/java/ai/philterd/phileas/services/PhileasFilterService.java index 5662981be..62e28f381 100644 --- a/phileas-core/src/main/java/ai/philterd/phileas/services/PhileasFilterService.java +++ b/phileas-core/src/main/java/ai/philterd/phileas/services/PhileasFilterService.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.metrics.PhileasMetricsService; import ai.philterd.phileas.model.domain.Domain; import ai.philterd.phileas.model.domain.HealthDomain; diff --git a/phileas-core/src/main/java/ai/philterd/phileas/services/filters/ai/python/PersonsV1Filter.java b/phileas-core/src/main/java/ai/philterd/phileas/services/filters/ai/python/PersonsV1Filter.java index daeeb5db6..226c88069 100644 --- a/phileas-core/src/main/java/ai/philterd/phileas/services/filters/ai/python/PersonsV1Filter.java +++ b/phileas-core/src/main/java/ai/philterd/phileas/services/filters/ai/python/PersonsV1Filter.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.filters.ai.python; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.enums.FilterType; import ai.philterd.phileas.model.filter.FilterConfiguration; import ai.philterd.phileas.model.filter.dynamic.NerFilter; @@ -65,9 +65,9 @@ public PersonsV1Filter(final FilterConfiguration filterConfiguration, this.removePunctuation = removePunctuation; this.tag = tag; - int timeoutSec = phileasConfiguration.nerTimeoutSec(); + int timeoutSec = phileasConfiguration.nerTimeout(); int maxIdleConnections = phileasConfiguration.nerMaxIdleConnections(); - int keepAliveDurationMs = phileasConfiguration.nerKeepAliveDurationMs(); + int keepAliveDurationMs = phileasConfiguration.nerKeepAliveDuration(); final OkHttpClient okHttpClient = new OkHttpClient.Builder() .retryOnConnectionFailure(true) @@ -78,7 +78,7 @@ public PersonsV1Filter(final FilterConfiguration filterConfiguration, .build(); final Retrofit retrofit = new Retrofit.Builder() - .baseUrl(phileasConfiguration.philterNerEndpoint()) + .baseUrl(phileasConfiguration.nerEndpoint()) .client(okHttpClient) .callFactory(okHttpClient) .addConverterFactory(ScalarsConverterFactory.create()) diff --git a/phileas-core/src/test/java/ai/philterd/test/phileas/services/EndToEndTests.java b/phileas-core/src/test/java/ai/philterd/test/phileas/services/EndToEndTests.java index 033e5fffd..7561af9b5 100644 --- a/phileas-core/src/test/java/ai/philterd/test/phileas/services/EndToEndTests.java +++ b/phileas-core/src/test/java/ai/philterd/test/phileas/services/EndToEndTests.java @@ -15,9 +15,7 @@ */ package ai.philterd.test.phileas.services; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.enums.MimeType; import ai.philterd.phileas.model.objects.Span; import ai.philterd.phileas.model.policy.Policy; @@ -27,7 +25,8 @@ import ai.philterd.phileas.model.responses.FilterResponse; import ai.philterd.phileas.model.serializers.PlaceholderDeserializer; import ai.philterd.phileas.services.PhileasFilterService; -import org.aeonbits.owner.ConfigFactory; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -50,7 +49,14 @@ import java.util.List; import java.util.Properties; -import static ai.philterd.test.phileas.services.EndToEndTestsHelper.*; +import static ai.philterd.test.phileas.services.EndToEndTestsHelper.getPdfFilterWithPersonPolicy; +import static ai.philterd.test.phileas.services.EndToEndTestsHelper.getPolicy; +import static ai.philterd.test.phileas.services.EndToEndTestsHelper.getPolicyJustCreditCard; +import static ai.philterd.test.phileas.services.EndToEndTestsHelper.getPolicyJustIdentifier; +import static ai.philterd.test.phileas.services.EndToEndTestsHelper.getPolicyJustStreetAddress; +import static ai.philterd.test.phileas.services.EndToEndTestsHelper.getPolicyWithSentiment; +import static ai.philterd.test.phileas.services.EndToEndTestsHelper.getPolicyZipCodeWithIgnored; +import static ai.philterd.test.phileas.services.EndToEndTestsHelper.getPolicyZipCodeWithIgnoredFromFile; @Disabled("Some of these tests require a running philter-ner service") public class EndToEndTests { @@ -89,7 +95,7 @@ public void pdf3() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final BinaryDocumentFilterResponse response = service.filter(Arrays.asList("pdf"), "context", "documentid", document, MimeType.APPLICATION_PDF, MimeType.APPLICATION_PDF); @@ -122,7 +128,7 @@ public void endToEnd1() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "George Washington was president and his ssn was 123-45-6789 and he lived at 90210.", MimeType.TEXT_PLAIN); @@ -147,7 +153,7 @@ public void endToEnd2() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "My email is test@something.com and cc is 4121742025464465", MimeType.TEXT_PLAIN); @@ -172,7 +178,7 @@ public void endToEnd3() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "test@something.com is email and cc is 4121742025464465", MimeType.TEXT_PLAIN); @@ -197,7 +203,7 @@ public void endToEnd4() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "test@something.com", MimeType.TEXT_PLAIN); @@ -222,7 +228,7 @@ public void endToEnd5() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "90210", MimeType.TEXT_PLAIN); @@ -247,7 +253,7 @@ public void endToEnd6() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "his name was JEFF.", MimeType.TEXT_PLAIN); @@ -272,7 +278,7 @@ public void endToEnd7() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "he was seen on 10-19-2020.", MimeType.TEXT_PLAIN); @@ -297,7 +303,7 @@ public void endToEnd8() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", @@ -323,7 +329,7 @@ public void endToEnd9() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "George Washington was president and his ssn was 123-45-6789 and he lived at 90210. The name 456 should be filtered. Jeff Smith should be ignored.", MimeType.TEXT_PLAIN); @@ -348,7 +354,7 @@ public void endToEnd10() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = IOUtils.toString(this.getClass().getResourceAsStream("/inputs/1.txt"), Charset.defaultCharset()); @@ -378,7 +384,7 @@ public void endToEnd11() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = "IN THE UNITED STATES DISTRICT COURT \nEASTERN DISTRICT OF ARKANSAS \nWESTERN DIVISION \nJAMES EDWARD SMITH, \nafk/a James Edward Bridges, \nADC#103093 \nv. No. 4:14-cv-455-DPM \nPLAINTIFF \nCHARLES A. SMITH; \nMARY ANN CONLEY, \nafk/a Mary Ann Smith; and \nROBERT CASTILLOW DEFENDANTS \nORDER \nJames Smith's prose complaint must be dismissed without prejudice. \nHe hasn't paid the filing fee, moved to proceed in forma pauperis, or provided \nproof of service on any defendant. FED. R. CIV. P. 4(I); Local Rule 5.5(c)(2). \nSo Ordered. \nD.P. Marshall Jr. \nUnited States District Judge \nCase 4:14-cv-00455-DPM Document 2 Filed 12/09/14 Page 1 of 1\n"; @@ -405,7 +411,7 @@ public void endToEnd12() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = IOUtils.toString(this.getClass().getResourceAsStream("/inputs/Oxford_City_unveil_merger_to_expand_their_youth_system.json.txt"), Charset.defaultCharset()); @@ -437,7 +443,7 @@ public void endToEnd13() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = IOUtils.toString(this.getClass().getResourceAsStream("/inputs/Kinross_reports_strong_2020_secondquarter_results.json.txt"), Charset.defaultCharset()); @@ -467,7 +473,7 @@ public void endToEnd14() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = IOUtils.toString(this.getClass().getResourceAsStream("/inputs/Donations_to_Black_Lives_Matter_Group_Dont_Go_to_DNC.json.txt"), Charset.defaultCharset()); @@ -497,7 +503,7 @@ public void endToEnd15() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = IOUtils.toString(this.getClass().getResourceAsStream("/inputs/Fantasy_Baseball_Winners__Losers_Sixto_Sanchez_and_Jeff_McNeil_stay_hot.json.txt"), Charset.defaultCharset()); @@ -529,7 +535,7 @@ public void endToEnd16() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = "the id is 123456."; @@ -561,7 +567,7 @@ public void endToEnd17() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = "he lived at 100 main street"; @@ -593,7 +599,7 @@ public void endToEndWithSentiment() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String input = "his ssn was 123-45-6789"; @@ -633,7 +639,7 @@ public void endToEndUsingCustomDictionary() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "his name was samuel and george.", MimeType.TEXT_PLAIN); @@ -676,7 +682,7 @@ public void endToEndUsingCustomDictionaryFileLuceneFilter() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "his name was samuel and george.", MimeType.TEXT_PLAIN); @@ -717,7 +723,7 @@ public void endToEndUsingCustomDictionaryFileBloomFilter() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "his name was samuel.", MimeType.TEXT_PLAIN); @@ -742,7 +748,7 @@ public void endToEndWithoutDocumentId() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", null, "his name was JEFF.", MimeType.TEXT_PLAIN); @@ -773,7 +779,7 @@ public void endToEndMultiplePolicys() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("justcreditcard"), "context", "documentid", "My email is test@something.com", MimeType.TEXT_PLAIN); @@ -798,7 +804,7 @@ public void endToEndJustCreditCard() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("justcreditcard"), "context", "documentid", "My cc is 4121742025464465", MimeType.TEXT_PLAIN); @@ -823,7 +829,7 @@ public void endToEndJustCreditCardWithIgnoredTerms() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("justcreditcard"), "context", "documentid", "My cc is 4121742025464400", MimeType.TEXT_PLAIN); @@ -847,7 +853,7 @@ public void endToEndWithFilterSpecificIgnoredTerms() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "George Washington was president and his ssn was 123-45-6789 and he lived at 90210.", MimeType.TEXT_PLAIN); @@ -871,7 +877,7 @@ public void endToEndWithFilterIgnoredTermsFromFile() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final FilterResponse response = service.filter(Arrays.asList("default"), "context", "documentid", "George Washington was president and his ssn was 123-45-6789 and he lived at 90210.", MimeType.TEXT_PLAIN); @@ -896,7 +902,7 @@ public void endToEndNonexistentPolicy() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); Assertions.assertThrows(FileNotFoundException.class, () -> { diff --git a/phileas-core/src/test/java/ai/philterd/test/phileas/services/PhileasFilterServiceTest.java b/phileas-core/src/test/java/ai/philterd/test/phileas/services/PhileasFilterServiceTest.java index eb59ec7b0..7bfbda39a 100644 --- a/phileas-core/src/test/java/ai/philterd/test/phileas/services/PhileasFilterServiceTest.java +++ b/phileas-core/src/test/java/ai/philterd/test/phileas/services/PhileasFilterServiceTest.java @@ -15,9 +15,9 @@ */ package ai.philterd.test.phileas.services; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import ai.philterd.phileas.configuration.PhileasConfiguration; import ai.philterd.phileas.model.enums.MimeType; import ai.philterd.phileas.model.objects.Span; import ai.philterd.phileas.model.policy.Policy; @@ -25,7 +25,7 @@ import ai.philterd.phileas.model.responses.BinaryDocumentFilterResponse; import ai.philterd.phileas.model.serializers.PlaceholderDeserializer; import ai.philterd.phileas.services.PhileasFilterService; -import org.aeonbits.owner.ConfigFactory; + import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -118,7 +118,7 @@ public void pdf1() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final BinaryDocumentFilterResponse response = service.filter(Arrays.asList("pdf"), "context", "documentid", document, MimeType.APPLICATION_PDF, MimeType.APPLICATION_PDF); @@ -155,7 +155,7 @@ public void pdf2() throws Exception { properties.setProperty("store.enabled", "false"); properties.setProperty("filter.policies.directory", temp.toFile().getAbsolutePath()); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); PhileasFilterService service = new PhileasFilterService(phileasConfiguration); final BinaryDocumentFilterResponse response = service.filter(Arrays.asList("pdf"), "context", "documentid", document, MimeType.APPLICATION_PDF, MimeType.APPLICATION_PDF); diff --git a/phileas-core/src/test/java/ai/philterd/test/phileas/services/registry/S3PolicyServiceTest.java b/phileas-core/src/test/java/ai/philterd/test/phileas/services/registry/S3PolicyServiceTest.java index d52db102f..4033cc6e0 100644 --- a/phileas-core/src/test/java/ai/philterd/test/phileas/services/registry/S3PolicyServiceTest.java +++ b/phileas-core/src/test/java/ai/philterd/test/phileas/services/registry/S3PolicyServiceTest.java @@ -15,22 +15,25 @@ */ package ai.philterd.test.phileas.services.registry; -import com.google.gson.Gson; -import ai.philterd.phileas.configuration.PhileasConfiguration; -import ai.philterd.phileas.model.policy.Policy; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.policy.Identifiers; +import ai.philterd.phileas.model.policy.Policy; import ai.philterd.phileas.model.policy.filters.Age; import ai.philterd.phileas.model.policy.filters.CreditCard; import ai.philterd.phileas.model.policy.filters.strategies.rules.AgeFilterStrategy; import ai.philterd.phileas.model.policy.filters.strategies.rules.CreditCardFilterStrategy; import ai.philterd.phileas.model.services.PolicyService; import ai.philterd.phileas.services.policies.S3PolicyService; +import com.google.gson.Gson; import io.findify.s3mock.S3Mock; -import org.aeonbits.owner.ConfigFactory; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.jupiter.api.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import redis.embedded.RedisServer; import java.io.IOException; @@ -53,7 +56,7 @@ public class S3PolicyServiceTest { private static boolean isExternalRedis = false; - private PhileasConfiguration getConfiguration() { + private PhileasConfiguration getConfiguration() throws IOException { final Properties properties = new Properties(); @@ -91,7 +94,7 @@ private PhileasConfiguration getConfiguration() { } - return ConfigFactory.create(PhileasConfiguration.class, properties); + return new PhileasConfiguration(properties, "phileas"); } diff --git a/phileas-model/pom.xml b/phileas-model/pom.xml index d34823a45..c973a222c 100644 --- a/phileas-model/pom.xml +++ b/phileas-model/pom.xml @@ -11,14 +11,6 @@ phileas-model phileas-model - - - Mountain Fog Commercial License - https://www.mtnfog.com - manual - Phileas is proprietary closed-source software. - - @@ -63,11 +55,6 @@ - - ai.philterd - phileas-configuration - ${project.version} - org.apache.commons commons-collections4 @@ -172,7 +159,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test @@ -191,7 +178,7 @@ org.junit-pioneer junit-pioneer - 2.0.1 + 2.2.0 test diff --git a/phileas-model/src/main/java/ai/philterd/phileas/model/cache/AbstractRedisCacheService.java b/phileas-model/src/main/java/ai/philterd/phileas/model/cache/AbstractRedisCacheService.java index 6ede06d24..176500875 100644 --- a/phileas-model/src/main/java/ai/philterd/phileas/model/cache/AbstractRedisCacheService.java +++ b/phileas-model/src/main/java/ai/philterd/phileas/model/cache/AbstractRedisCacheService.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.model.cache; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/phileas-model/src/main/java/ai/philterd/phileas/model/configuration/PhileasConfiguration.java b/phileas-model/src/main/java/ai/philterd/phileas/model/configuration/PhileasConfiguration.java new file mode 100644 index 000000000..cc2bcac03 --- /dev/null +++ b/phileas-model/src/main/java/ai/philterd/phileas/model/configuration/PhileasConfiguration.java @@ -0,0 +1,230 @@ +package ai.philterd.phileas.model.configuration; + +import org.apache.commons.lang3.StringUtils; + +import java.io.FileReader; +import java.io.IOException; +import java.util.Properties; + +public class PhileasConfiguration { + + private final String DEFAULT_STOP_WORDS = "a, as, able, about, above, according, accordingly, across, actually, after, afterwards, again, against, aint, all, allow, allows, almost, alone, along, already, also, although, always, am, among, amongst, an, and, another, any, anybody, anyhow, anyone, anything, anyway, anyways, anywhere, apart, appear, appreciate, appropriate, are, arent, around, as, aside, ask, asking, associated, at, available, away, awfully, be, became, because, become, becomes, becoming, been, before, beforehand, behind, being, believe, below, beside, besides, best, better, between, beyond, both, brief, but, by, cmon, cs, came, can, cant, cannot, cant, cause, causes, certain, certainly, changes, clearly, co, com, come, comes, concerning, consequently, consider, considering, contain, containing, contains, corresponding, could, couldnt, course, currently, definitely, described, despite, did, didnt, different, do, does, doesnt, doing, dont, done, down, downwards, during, each, edu, eg, eight, either, else, elsewhere, enough, entirely, especially, et, etc, even, ever, every, everybody, everyone, everything, everywhere, ex, exactly, example, except, far, few, ff, fifth, first, five, followed, following, follows, for, former, formerly, forth, four, from, further, furthermore, get, gets, getting, given, gives, go, goes, going, gone, got, gotten, greetings, had, hadnt, happens, hardly, has, hasnt, have, havent, having, he, hes, hello, help, hence, her, here, heres, hereafter, hereby, herein, hereupon, hers, herself, hi, him, himself, his, hither, hopefully, how, howbeit, however, i, id, ill, im, ive, ie, if, ignored, immediate, in, inasmuch, inc, indeed, indicate, indicated, indicates, inner, insofar, instead, into, inward, is, isnt, it, itd, itll, its, its, itself, just, keep, keeps, kept, know, knows, known, last, lately, later, latter, latterly, least, less, lest, let, lets, like, liked, likely, little, look, looking, looks, ltd, mainly, many, may, maybe, me, mean, meanwhile, merely, might, more, moreover, most, mostly, much, must, my, myself, name, namely, nd, near, nearly, necessary, need, needs, neither, never, nevertheless, new, next, nine, no, nobody, non, none, noone, nor, normally, not, nothing, novel, now, nowhere, obviously, of, off, often, oh, ok, okay, old, on, once, one, ones, only, onto, or, other, others, otherwise, ought, our, ours, ourselves, out, outside, over, overall, own, particular, particularly, per, perhaps, placed, please, plus, possible, presumably, probably, provides, que, quite, qv, rather, rd, re, really, reasonably, regarding, regardless, regards, relatively, respectively, right, said, same, saw, say, saying, says, second, secondly, see, seeing, seem, seemed, seeming, seems, seen, self, selves, sensible, sent, serious, seriously, seven, several, shall, she, should, shouldnt, since, six, so, some, somebody, somehow, someone, something, sometime, sometimes, somewhat, somewhere, soon, sorry, specified, specify, specifying, still, sub, such, sup, sure, ts, take, taken, tell, tends, th, than, thank, thanks, thanx, that, thats, thats, the, their, theirs, them, themselves, then, thence, there, theres, thereafter, thereby, therefore, therein, theres, thereupon, these, they, theyd, theyll, theyre, theyve, think, third, this, thorough, thoroughly, those, though, through, throughout, thru, thus, to, together, too, took, toward, towards, tried, tries, truly, try, trying, twice, two, un, under, unfortunately, unless, unlikely, until, unto, up, upon, us, use, used, useful, uses, using, usually, value, various, very, via, viz, vs, want, wants, was, wasnt, way, we, wed, well, were, weve, welcome, well, went, were, werent, what, whats, whatever, when, whence, whenever, where, wheres, whereafter, whereas, whereby, wherein, whereupon, wherever, whether, which, while, whither, who, whos, whoever, whole, whom, whose, why, will, willing, wish, with, within, without, wont, wonder, would, would, wouldnt, yes, yet, you, youd, youll, youre, youve, your, yours, yourself, yourselves"; + + private final Properties properties; + private final String applicationName; + + public PhileasConfiguration(final String propertyFileName, final String applicationName) throws IOException { + + final FileReader fileReader = new FileReader(propertyFileName); + this.properties = new Properties(); + properties.load(fileReader); + + this.applicationName = applicationName; + + } + + public PhileasConfiguration(final Properties properties, final String applicationName) throws IOException { + + this.properties = properties; + this.applicationName = applicationName; + + } + + public String indexesDirectory() { + return getProperty("indexes.directory", "./indexes/"); + } + + public String nerEndpoint() { + return getProperty("ner.endpoint", "http://localhost:8080/"); + } + + public int nerTimeout() { + return Integer.parseInt(getProperty("ner.timeout.sec", "600")); + } + + public int nerMaxIdleConnections() { + return Integer.parseInt(getProperty("ner.max.idle.connections", "30")); + } + + public int nerKeepAliveDuration() { + return Integer.parseInt(getProperty("ner.keep.alive.duration.ms", "30")); + } + + public boolean spanDisambiguationEnabled() { + return Boolean.parseBoolean(getProperty("span.disambiguation.enabled", "false")); + } + + public String spanDisambiguationHashAlgorithm() { + return getProperty("span.disambiguation.hash.algorithm", "murmur3"); + } + + public int spanDisambiguationVectorSize() { + return Integer.parseInt(getProperty("span.disambiguation.vector.size", "512")); + } + + public boolean spanDisambiguationIgnoreStopWords() { + return Boolean.parseBoolean(getProperty("span.disambiguation.ignore.stopwords", "true")); + } + + public String spanDisambiguationStopWords() { + return getProperty("span.disambiguation.stopwords", DEFAULT_STOP_WORDS); + } + + public int spanWindowSize() { + return Integer.parseInt(getProperty("span.window.size", "5")); + } + + public double bloomFilterFpp() { + return Double.parseDouble(getProperty("filter.fpp", "0.05")); + } + + // Caching + + public boolean cacheRedisEnabled() { + return Boolean.parseBoolean(getProperty("cache.redis.enabled", "false")); + } + + public boolean cacheRedisCluster() { + return Boolean.parseBoolean(getProperty("cache.redis.cluster", "false")); + } + + public String cacheRedisHost() { + return getProperty("cache.redis.host", "localhost"); + } + + public int cacheRedisPort() { + return Integer.parseInt(getProperty("cache.redis.port", "6379")); + } + + public String cacheRedisAuthToken() { + return getProperty("cache.redis.auth.token", ""); + } + + public boolean cacheRedisSsl() { + return Boolean.parseBoolean(getProperty("cache.redis.ssl", "false")); + } + + public String cacheRedisTrustStore() { + return getProperty("cache.redis.truststore", ""); + } + + public String cacheRedisTrustStorePassword() { + return getProperty("cache.redis.truststore.password", ""); + } + + public String cacheRedisKeyStore() { + return getProperty("cache.redis.keystore", ""); + } + + public String cacheRedisKeyStorePassword() { + return getProperty("cache.redis.keystore.password", ""); + } + + // Policies + + public String policiesDirectory() { + return getProperty("filter.policies.directory", "./policies/"); + } + + public String policiesS3Bucket() { + return getProperty("filter.policies.s3.bucket", ""); + } + + public String policiesS3Prefix() { + return getProperty("filter.policies.s3.prefix", ""); + } + + public String policiesS3Region() { + return getProperty("filter.policies.s3.region", "us-east-1"); + } + + // Metrics + + public String metricsPrefix() { + return getProperty("metrics.prefix", applicationName); + } + + // See: https://github.com/micrometer-metrics/micrometer/blob/master/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusConfig.java + // The step size to use in computing windowed statistics like max. The default is 1 minute. + // To get the most out of these statistics, align the step interval to be close to your scrape interval. + public int metricsStep() { + return Integer.parseInt(getProperty("metrics.step", "60")); + } + + public boolean metricsJmxEnabled() { + return Boolean.parseBoolean(getProperty("metrics.jmx.enabled", "false")); + } + + public boolean metricsPrometheusEnabled() { + return Boolean.parseBoolean(getProperty("metrics.prometheus.enabled", "false")); + } + + public int metricsPrometheusPort() { + return Integer.parseInt(getProperty("metrics.prometheus.port", "9100")); + } + + public String metricsPrometheusContext() { + return getProperty("metrics.prometheus.context", "metrics"); + } + + public boolean metricsDataDogEnabled() { + return Boolean.parseBoolean(getProperty("metrics.datadog.enabled", "false")); + } + + public String metricsDataDogApiKey() { + return getProperty("metrics.datadog.apikey", "metrics"); + } + + public boolean metricsCloudWatchEnabled() { + return Boolean.parseBoolean(getProperty("metrics.cloudwatch.enabled", "false")); + } + + public String metricsCloudWatchRegion() { + return String.valueOf(getProperty("metrics.cloudwatch.region", "us-east-1")); + } + + public String metricsCloudWatchNamespace() { + return String.valueOf(getProperty("metrics.cloudwatch.namespace", applicationName)); + } + + public String metricsHostname() { + return String.valueOf(getProperty("metrics.hostname", "")); + } + + private String getProperty(final String property, final String defaultValue) { + + final String environmentVariableValue = getEnvironmentVariable(property); + + if(!StringUtils.isEmpty(environmentVariableValue)) { + return environmentVariableValue; + } + + final String systemPropertyValue = getSystemProperty(property); + + if(!StringUtils.isEmpty(systemPropertyValue)) { + return systemPropertyValue; + } + + final String propertyFileValue = getFileProperty(property); + + if(!StringUtils.isEmpty(propertyFileValue)) { + return propertyFileValue; + } + + return defaultValue; + + } + + private String getEnvironmentVariable(final String environmentVariable) { + return System.getenv(environmentVariable); + } + + private String getSystemProperty(final String property) { + return System.getProperty(property); + } + + private String getFileProperty(final String property) { + return properties.getProperty(property); + } + +} diff --git a/phileas-processors/phileas-processors-structured/phileas-processors-structured-fhir/pom.xml b/phileas-processors/phileas-processors-structured/phileas-processors-structured-fhir/pom.xml index 152e53543..9c275af29 100644 --- a/phileas-processors/phileas-processors-structured/phileas-processors-structured-fhir/pom.xml +++ b/phileas-processors/phileas-processors-structured/phileas-processors-structured-fhir/pom.xml @@ -8,14 +8,6 @@ phileas-processors-structured-fhir phileas-processors-structured-fhir - - - Mountain Fog Commercial License - https://www.mtnfog.com - manual - Phileas is proprietary closed-source software. - - ai.philterd @@ -40,7 +32,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-processors/phileas-processors-unstructured/pom.xml b/phileas-processors/phileas-processors-unstructured/pom.xml index e500af2a2..79c69c21c 100644 --- a/phileas-processors/phileas-processors-unstructured/pom.xml +++ b/phileas-processors/phileas-processors-unstructured/pom.xml @@ -20,7 +20,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-processors/pom.xml b/phileas-processors/pom.xml index c936c42d2..020b29410 100644 --- a/phileas-processors/pom.xml +++ b/phileas-processors/pom.xml @@ -9,14 +9,6 @@ phileas-processors phileas-processors pom - - - Mountain Fog Commercial License - https://www.mtnfog.com - manual - Phileas is proprietary closed-source software. - - phileas-processors-unstructured diff --git a/phileas-services-split/pom.xml b/phileas-services-split/pom.xml index b59b34548..a1e926869 100644 --- a/phileas-services-split/pom.xml +++ b/phileas-services-split/pom.xml @@ -22,7 +22,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-services/phileas-services-ai/pom.xml b/phileas-services/phileas-services-ai/pom.xml index ea745c924..9c7585443 100644 --- a/phileas-services/phileas-services-ai/pom.xml +++ b/phileas-services/phileas-services-ai/pom.xml @@ -8,25 +8,12 @@ phileas-services-ai phileas-services-ai - - - Mountain Fog Commercial License - https://www.mtnfog.com - manual - Phileas is proprietary closed-source software. - - ai.philterd phileas-model ${project.version} - - ai.philterd - phileas-configuration - ${project.version} - org.apache.opennlp opennlp-tools @@ -45,15 +32,9 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test - - com.squareup.okhttp - mockwebserver - 2.7.5 - test - diff --git a/phileas-services/phileas-services-ai/src/test/java/ai/philterd/test/phileas/services/ai/InferenceTest.java b/phileas-services/phileas-services-ai/src/test/java/ai/philterd/test/phileas/services/ai/InferenceTest.java deleted file mode 100644 index 1295dae6f..000000000 --- a/phileas-services/phileas-services-ai/src/test/java/ai/philterd/test/phileas/services/ai/InferenceTest.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2023 Philterd, LLC @ https://www.philterd.ai - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package ai.philterd.test.phileas.services.ai; - -public class InferenceTest { - -} diff --git a/phileas-services/phileas-services-ai/src/test/java/ai/philterd/test/phileas/services/ai/models/ModelCacheTest.java b/phileas-services/phileas-services-ai/src/test/java/ai/philterd/test/phileas/services/ai/models/ModelCacheTest.java index d7e27aa3a..e3c0cb913 100644 --- a/phileas-services/phileas-services-ai/src/test/java/ai/philterd/test/phileas/services/ai/models/ModelCacheTest.java +++ b/phileas-services/phileas-services-ai/src/test/java/ai/philterd/test/phileas/services/ai/models/ModelCacheTest.java @@ -2,8 +2,8 @@ import ai.philterd.phileas.service.ai.models.ModelCache; import opennlp.tools.doccat.DocumentCategorizerME; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ModelCacheTest { @@ -13,7 +13,7 @@ public void getDoesntExist() { final ModelCache modelCache = ModelCache.getInstance(); final DocumentCategorizerME documentCategorizerME = modelCache.get("doesnt-exist"); - Assert.assertNull(documentCategorizerME); + Assertions.assertNull(documentCategorizerME); } diff --git a/phileas-services/phileas-services-alerts/pom.xml b/phileas-services/phileas-services-alerts/pom.xml index 938834654..7914b6d3b 100644 --- a/phileas-services/phileas-services-alerts/pom.xml +++ b/phileas-services/phileas-services-alerts/pom.xml @@ -34,7 +34,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-services/phileas-services-alerts/src/main/java/ai/philterd/phileas/services/alerts/AlertServiceFactory.java b/phileas-services/phileas-services-alerts/src/main/java/ai/philterd/phileas/services/alerts/AlertServiceFactory.java index 80b666f5c..38a7c11bd 100644 --- a/phileas-services/phileas-services-alerts/src/main/java/ai/philterd/phileas/services/alerts/AlertServiceFactory.java +++ b/phileas-services/phileas-services-alerts/src/main/java/ai/philterd/phileas/services/alerts/AlertServiceFactory.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.alerts; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.services.AlertService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/phileas-services/phileas-services-alerts/src/main/java/ai/philterd/phileas/services/alerts/RedisAlertService.java b/phileas-services/phileas-services-alerts/src/main/java/ai/philterd/phileas/services/alerts/RedisAlertService.java index 2a16a9ef4..e71a43b97 100644 --- a/phileas-services/phileas-services-alerts/src/main/java/ai/philterd/phileas/services/alerts/RedisAlertService.java +++ b/phileas-services/phileas-services-alerts/src/main/java/ai/philterd/phileas/services/alerts/RedisAlertService.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.alerts; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.cache.AbstractRedisCacheService; import ai.philterd.phileas.model.enums.FilterType; import ai.philterd.phileas.model.objects.Alert; diff --git a/phileas-services/phileas-services-alerts/src/test/java/ai/philterd/test/phileas/services/alerts/RedisAlertServiceTest.java b/phileas-services/phileas-services-alerts/src/test/java/ai/philterd/test/phileas/services/alerts/RedisAlertServiceTest.java index bed61469f..8da318e44 100644 --- a/phileas-services/phileas-services-alerts/src/test/java/ai/philterd/test/phileas/services/alerts/RedisAlertServiceTest.java +++ b/phileas-services/phileas-services-alerts/src/test/java/ai/philterd/test/phileas/services/alerts/RedisAlertServiceTest.java @@ -15,16 +15,19 @@ */ package ai.philterd.test.phileas.services.alerts; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.enums.FilterType; import ai.philterd.phileas.model.objects.Alert; import ai.philterd.phileas.model.services.AlertService; import ai.philterd.phileas.services.alerts.RedisAlertService; -import org.aeonbits.owner.ConfigFactory; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.jupiter.api.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import redis.embedded.RedisServer; import java.io.IOException; @@ -40,7 +43,7 @@ public class RedisAlertServiceTest { private RedisServer redisServer; private static boolean isExternalRedis = false; - private PhileasConfiguration getConfiguration() { + private PhileasConfiguration getConfiguration() throws IOException { final Properties properties = new Properties(); @@ -78,7 +81,7 @@ private PhileasConfiguration getConfiguration() { } - return ConfigFactory.create(PhileasConfiguration.class, properties); + return new PhileasConfiguration(properties, "phileas"); } diff --git a/phileas-services/phileas-services-anonymization/pom.xml b/phileas-services/phileas-services-anonymization/pom.xml index 06e81bcf6..9fa89060a 100644 --- a/phileas-services/phileas-services-anonymization/pom.xml +++ b/phileas-services/phileas-services-anonymization/pom.xml @@ -13,11 +13,6 @@ phileas-model ${project.version} - - ai.philterd - phileas-configuration - ${project.version} - com.github.javafaker javafaker @@ -42,7 +37,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-services/phileas-services-anonymization/src/main/java/ai/philterd/phileas/services/anonymization/cache/AnonymizationCacheServiceFactory.java b/phileas-services/phileas-services-anonymization/src/main/java/ai/philterd/phileas/services/anonymization/cache/AnonymizationCacheServiceFactory.java index dc60c4186..36f55392e 100644 --- a/phileas-services/phileas-services-anonymization/src/main/java/ai/philterd/phileas/services/anonymization/cache/AnonymizationCacheServiceFactory.java +++ b/phileas-services/phileas-services-anonymization/src/main/java/ai/philterd/phileas/services/anonymization/cache/AnonymizationCacheServiceFactory.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.anonymization.cache; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.services.AnonymizationCacheService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/phileas-services/phileas-services-anonymization/src/main/java/ai/philterd/phileas/services/anonymization/cache/RedisAnonymizationCacheService.java b/phileas-services/phileas-services-anonymization/src/main/java/ai/philterd/phileas/services/anonymization/cache/RedisAnonymizationCacheService.java index cfc7842d8..91b064451 100644 --- a/phileas-services/phileas-services-anonymization/src/main/java/ai/philterd/phileas/services/anonymization/cache/RedisAnonymizationCacheService.java +++ b/phileas-services/phileas-services-anonymization/src/main/java/ai/philterd/phileas/services/anonymization/cache/RedisAnonymizationCacheService.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.anonymization.cache; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.cache.AbstractRedisCacheService; import ai.philterd.phileas.model.services.AnonymizationCacheService; import org.apache.commons.codec.digest.DigestUtils; diff --git a/phileas-services/phileas-services-anonymization/src/test/java/ai/philterd/test/phileas/services/anonymization/cache/AnonymizationCacheServiceFactoryTest.java b/phileas-services/phileas-services-anonymization/src/test/java/ai/philterd/test/phileas/services/anonymization/cache/AnonymizationCacheServiceFactoryTest.java index 108470cb4..bd9e59406 100644 --- a/phileas-services/phileas-services-anonymization/src/test/java/ai/philterd/test/phileas/services/anonymization/cache/AnonymizationCacheServiceFactoryTest.java +++ b/phileas-services/phileas-services-anonymization/src/test/java/ai/philterd/test/phileas/services/anonymization/cache/AnonymizationCacheServiceFactoryTest.java @@ -15,14 +15,14 @@ */ package ai.philterd.test.phileas.services.anonymization.cache; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.services.AnonymizationCacheService; import ai.philterd.phileas.services.anonymization.cache.AnonymizationCacheServiceFactory; import ai.philterd.phileas.services.anonymization.cache.LocalAnonymizationCacheService; -import org.aeonbits.owner.ConfigFactory; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.io.IOException; import java.util.Properties; public class AnonymizationCacheServiceFactoryTest { @@ -30,19 +30,17 @@ public class AnonymizationCacheServiceFactoryTest { @Test public void useLocalAsDefault() throws Exception { - final Properties properties = new Properties(); - final AnonymizationCacheService anonymizationCacheService = AnonymizationCacheServiceFactory.getAnonymizationCacheService(getConfiguration()); - Assertions.assertTrue(anonymizationCacheService instanceof LocalAnonymizationCacheService); + Assertions.assertInstanceOf(LocalAnonymizationCacheService.class, anonymizationCacheService); } - private PhileasConfiguration getConfiguration() { + private PhileasConfiguration getConfiguration() throws IOException { final Properties properties = new Properties(); - return ConfigFactory.create(PhileasConfiguration.class, properties); + return new PhileasConfiguration(properties, "phileas"); } diff --git a/phileas-services/phileas-services-anonymization/src/test/java/ai/philterd/test/phileas/services/anonymization/cache/RedisAnonymizationCacheServiceTest.java b/phileas-services/phileas-services-anonymization/src/test/java/ai/philterd/test/phileas/services/anonymization/cache/RedisAnonymizationCacheServiceTest.java index a44bb5a88..d897a5918 100644 --- a/phileas-services/phileas-services-anonymization/src/test/java/ai/philterd/test/phileas/services/anonymization/cache/RedisAnonymizationCacheServiceTest.java +++ b/phileas-services/phileas-services-anonymization/src/test/java/ai/philterd/test/phileas/services/anonymization/cache/RedisAnonymizationCacheServiceTest.java @@ -15,15 +15,15 @@ */ package ai.philterd.test.phileas.services.anonymization.cache; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.services.anonymization.cache.RedisAnonymizationCacheService; -import org.aeonbits.owner.ConfigFactory; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.*; import redis.embedded.RedisServer; +import java.io.IOException; import java.util.Properties; import static org.junit.jupiter.api.Assumptions.assumeFalse; @@ -35,7 +35,7 @@ public class RedisAnonymizationCacheServiceTest { private RedisServer redisServer; private static boolean isExternalRedis = false; - private PhileasConfiguration getConfiguration() { + private PhileasConfiguration getConfiguration() throws IOException { final Properties properties = new Properties(); @@ -73,9 +73,7 @@ private PhileasConfiguration getConfiguration() { } - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); - - return phileasConfiguration; + return new PhileasConfiguration(properties, "phileas"); } diff --git a/phileas-services/phileas-services-disambiguation/pom.xml b/phileas-services/phileas-services-disambiguation/pom.xml index 8ab5c4c29..a79656109 100644 --- a/phileas-services/phileas-services-disambiguation/pom.xml +++ b/phileas-services/phileas-services-disambiguation/pom.xml @@ -14,11 +14,6 @@ phileas-model ${project.version} - - ai.philterd - phileas-configuration - ${project.version} - org.redisson redisson @@ -38,7 +33,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/AbstractSpanDisambiguationService.java b/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/AbstractSpanDisambiguationService.java index 39bc71680..7ef974c3f 100644 --- a/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/AbstractSpanDisambiguationService.java +++ b/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/AbstractSpanDisambiguationService.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.disambiguation; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.services.SpanDisambiguationCacheService; import ai.philterd.phileas.services.disambiguation.cache.SpanDisambiguationLocalCacheService; import ai.philterd.phileas.services.disambiguation.cache.SpanDisambiguationRedisCacheService; @@ -38,7 +38,7 @@ public abstract class AbstractSpanDisambiguationService { // Changing the size would require starting all over because the values in it would // no longer be valid because the hash function would have changed. - private PhileasConfiguration phileasConfiguration; + private final PhileasConfiguration phileasConfiguration; protected boolean enabled; protected final int vectorSize; diff --git a/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/VectorBasedSpanDisambiguationService.java b/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/VectorBasedSpanDisambiguationService.java index 6eb08e2e8..ab8d1c261 100644 --- a/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/VectorBasedSpanDisambiguationService.java +++ b/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/VectorBasedSpanDisambiguationService.java @@ -15,11 +15,10 @@ */ package ai.philterd.phileas.services.disambiguation; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.enums.FilterType; import ai.philterd.phileas.model.objects.Span; import ai.philterd.phileas.model.services.SpanDisambiguationService; -import org.apache.commons.codec.digest.MurmurHash3; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/cache/SpanDisambiguationRedisCacheService.java b/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/cache/SpanDisambiguationRedisCacheService.java index 3fa26e21d..4ac894c6c 100644 --- a/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/cache/SpanDisambiguationRedisCacheService.java +++ b/phileas-services/phileas-services-disambiguation/src/main/java/ai/philterd/phileas/services/disambiguation/cache/SpanDisambiguationRedisCacheService.java @@ -15,8 +15,8 @@ */ package ai.philterd.phileas.services.disambiguation.cache; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import com.google.gson.Gson; -import ai.philterd.phileas.configuration.PhileasConfiguration; import ai.philterd.phileas.model.cache.AbstractRedisCacheService; import ai.philterd.phileas.model.enums.FilterType; import ai.philterd.phileas.model.objects.Span; diff --git a/phileas-services/phileas-services-disambiguation/src/test/java/ai/philterd/test/phileas/services/disambiguation/LocalVectorBasedSpanDisambiguationServiceTest.java b/phileas-services/phileas-services-disambiguation/src/test/java/ai/philterd/test/phileas/services/disambiguation/LocalVectorBasedSpanDisambiguationServiceTest.java index 9b04de120..e0e2e3359 100644 --- a/phileas-services/phileas-services-disambiguation/src/test/java/ai/philterd/test/phileas/services/disambiguation/LocalVectorBasedSpanDisambiguationServiceTest.java +++ b/phileas-services/phileas-services-disambiguation/src/test/java/ai/philterd/test/phileas/services/disambiguation/LocalVectorBasedSpanDisambiguationServiceTest.java @@ -15,11 +15,10 @@ */ package ai.philterd.test.phileas.services.disambiguation; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.enums.FilterType; import ai.philterd.phileas.model.objects.Span; import ai.philterd.phileas.services.disambiguation.VectorBasedSpanDisambiguationService; -import org.aeonbits.owner.ConfigFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Assertions; @@ -44,7 +43,7 @@ public void disambiguateLocal1() throws IOException { properties.setProperty("span.disambiguation.vector.size", "32"); properties.setProperty("cache.redis.enabled", "false"); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String context = "c"; @@ -78,7 +77,7 @@ public void disambiguateLocal2() throws IOException { properties.setProperty("span.disambiguation.vector.size", "32"); properties.setProperty("cache.redis.enabled", "false"); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String context = "c"; diff --git a/phileas-services/phileas-services-disambiguation/src/test/java/ai/philterd/test/phileas/services/disambiguation/RedisVectorBasedSpanDisambiguationServiceTest.java b/phileas-services/phileas-services-disambiguation/src/test/java/ai/philterd/test/phileas/services/disambiguation/RedisVectorBasedSpanDisambiguationServiceTest.java index 6cbc4971d..ea793c0df 100644 --- a/phileas-services/phileas-services-disambiguation/src/test/java/ai/philterd/test/phileas/services/disambiguation/RedisVectorBasedSpanDisambiguationServiceTest.java +++ b/phileas-services/phileas-services-disambiguation/src/test/java/ai/philterd/test/phileas/services/disambiguation/RedisVectorBasedSpanDisambiguationServiceTest.java @@ -15,11 +15,10 @@ */ package ai.philterd.test.phileas.services.disambiguation; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.enums.FilterType; import ai.philterd.phileas.model.objects.Span; import ai.philterd.phileas.services.disambiguation.VectorBasedSpanDisambiguationService; -import org.aeonbits.owner.ConfigFactory; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -57,7 +56,7 @@ public void after() { public void disambiguateWithRedis1() throws IOException { final Properties properties = getProperties(); - final PhileasConfiguration phileasConfiguration = ConfigFactory.create(PhileasConfiguration.class, properties); + final PhileasConfiguration phileasConfiguration = new PhileasConfiguration(properties, "phileas"); final String context = "c"; diff --git a/phileas-services/phileas-services-metrics/pom.xml b/phileas-services/phileas-services-metrics/pom.xml index a23068b9d..9271e708a 100644 --- a/phileas-services/phileas-services-metrics/pom.xml +++ b/phileas-services/phileas-services-metrics/pom.xml @@ -8,25 +8,12 @@ phileas-services-metrics phileas-services-metrics - - - Mountain Fog Commercial License - https://www.mtnfog.com - manual - Phileas is proprietary closed-source software. - - ai.philterd phileas-model ${project.version} - - ai.philterd - phileas-configuration - ${project.version} - io.micrometer micrometer-registry-jmx @@ -54,7 +41,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-services/phileas-services-metrics/src/main/java/ai/philterd/phileas/metrics/PhileasMetricsService.java b/phileas-services/phileas-services-metrics/src/main/java/ai/philterd/phileas/metrics/PhileasMetricsService.java index 38534e99e..6417bfaff 100644 --- a/phileas-services/phileas-services-metrics/src/main/java/ai/philterd/phileas/metrics/PhileasMetricsService.java +++ b/phileas-services/phileas-services-metrics/src/main/java/ai/philterd/phileas/metrics/PhileasMetricsService.java @@ -15,10 +15,10 @@ */ package ai.philterd.phileas.metrics; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import com.amazonaws.regions.Regions; import com.amazonaws.services.cloudwatch.AmazonCloudWatchAsync; import com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClientBuilder; -import ai.philterd.phileas.configuration.PhileasConfiguration; import ai.philterd.phileas.model.enums.FilterType; import ai.philterd.phileas.model.services.MetricsService; import com.sun.net.httpserver.HttpServer; diff --git a/phileas-services/phileas-services-pdf/pom.xml b/phileas-services/phileas-services-pdf/pom.xml index b9b88e422..d8bcde342 100644 --- a/phileas-services/phileas-services-pdf/pom.xml +++ b/phileas-services/phileas-services-pdf/pom.xml @@ -47,7 +47,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-services/phileas-services-policies/pom.xml b/phileas-services/phileas-services-policies/pom.xml index 765cfc9cd..38a752540 100644 --- a/phileas-services/phileas-services-policies/pom.xml +++ b/phileas-services/phileas-services-policies/pom.xml @@ -14,11 +14,6 @@ phileas-model ${project.version} - - ai.philterd - phileas-configuration - ${project.version} - com.amazonaws aws-java-sdk-s3 @@ -47,7 +42,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/LocalPolicyService.java b/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/LocalPolicyService.java index 0cf04e1d9..7a6b32603 100644 --- a/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/LocalPolicyService.java +++ b/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/LocalPolicyService.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.policies; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.exceptions.api.BadRequestException; import ai.philterd.phileas.model.services.AbstractPolicyService; import ai.philterd.phileas.model.services.PolicyCacheService; @@ -39,8 +39,8 @@ public class LocalPolicyService extends AbstractPolicyService implements PolicyS private static final String JSON_EXTENSION = ".json"; - private String policiesDirectory; - private PolicyCacheService policyCacheService; + private final String policiesDirectory; + private final PolicyCacheService policyCacheService; public LocalPolicyService(PhileasConfiguration phileasConfiguration) { diff --git a/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/S3PolicyService.java b/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/S3PolicyService.java index 71da161a8..f9cc56537 100644 --- a/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/S3PolicyService.java +++ b/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/S3PolicyService.java @@ -15,6 +15,7 @@ */ package ai.philterd.phileas.services.policies; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.AnonymousAWSCredentials; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; @@ -22,7 +23,6 @@ import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.*; -import ai.philterd.phileas.configuration.PhileasConfiguration; import ai.philterd.phileas.model.exceptions.api.BadRequestException; import ai.philterd.phileas.model.exceptions.api.InternalServerErrorException; import ai.philterd.phileas.model.services.AbstractPolicyService; diff --git a/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/cache/PolicyCacheServiceFactory.java b/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/cache/PolicyCacheServiceFactory.java index 3978212cd..496305d3a 100644 --- a/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/cache/PolicyCacheServiceFactory.java +++ b/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/cache/PolicyCacheServiceFactory.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.policies.cache; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.services.PolicyCacheService; import java.io.IOException; diff --git a/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/cache/RedisPolicyCacheService.java b/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/cache/RedisPolicyCacheService.java index 9bb79f069..85242629e 100644 --- a/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/cache/RedisPolicyCacheService.java +++ b/phileas-services/phileas-services-policies/src/main/java/ai/philterd/phileas/services/policies/cache/RedisPolicyCacheService.java @@ -15,7 +15,7 @@ */ package ai.philterd.phileas.services.policies.cache; -import ai.philterd.phileas.configuration.PhileasConfiguration; +import ai.philterd.phileas.model.configuration.PhileasConfiguration; import ai.philterd.phileas.model.cache.AbstractRedisCacheService; import ai.philterd.phileas.model.services.PolicyCacheService; import org.apache.logging.log4j.LogManager; diff --git a/phileas-services/phileas-services-split/pom.xml b/phileas-services/phileas-services-split/pom.xml index 6a083cd48..291c2fc40 100644 --- a/phileas-services/phileas-services-split/pom.xml +++ b/phileas-services/phileas-services-split/pom.xml @@ -22,7 +22,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine ${junit.version} test diff --git a/phileas-services/pom.xml b/phileas-services/pom.xml index 48d66309a..93291518f 100644 --- a/phileas-services/pom.xml +++ b/phileas-services/pom.xml @@ -9,14 +9,6 @@ phileas-services phileas-services pom - - - Mountain Fog Commercial License - https://www.mtnfog.com - manual - Phileas is proprietary closed-source software. - - phileas-services-metrics phileas-services-anonymization diff --git a/pom.xml b/pom.xml index 3b420c38a..3db6fffa0 100644 --- a/pom.xml +++ b/pom.xml @@ -56,9 +56,7 @@ phileas-core phileas-model phileas-services - phileas-configuration phileas-processors - owner UTF-8 @@ -87,17 +85,20 @@ 1.0.2 20220924 1.15.3 - 5.9.1 + 5.10.2 8.13.4 2.19.0 8.3.0 + 3.8.1 + 3.2.5 + 3.2.5 1.10.2 5.4.0 1.27 2.1.0 2.0.23 0.1.6 - 3.19.1 + 3.27.2 2.9.0 2.12 2.0.1 @@ -109,7 +110,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + ${maven.compiler.version} @@ -123,19 +124,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.2 - - - org.junit.platform - junit-platform-surefire-provider - 1.3.2 - - - org.junit.jupiter - junit-jupiter-engine - ${junit.version} - - + ${maven.surefire.version} -Xmx8g --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED @@ -149,7 +138,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 2.22.2 + ${maven.failsafe.version} **/*IT.java