From b1546c59cac350b746e13239a18a2ad3a9f621ff Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Tue, 5 Feb 2019 10:38:16 +0100 Subject: [PATCH] Added checkstyle --- .editorconfig | 14 + .settings.xml | 128 ++--- .springformat | 0 docs/pom.xml | 66 +-- pom.xml | 56 +- sample.groovy | 10 +- spring-cloud-config-client/pom.xml | 6 +- .../client/ConfigClientAutoConfiguration.java | 8 +- .../client/ConfigClientHealthProperties.java | 7 +- .../config/client/ConfigClientProperties.java | 107 ++-- .../client/ConfigClientStateHolder.java | 30 +- .../config/client/ConfigClientWatch.java | 13 +- .../client/ConfigServerHealthIndicator.java | 35 +- .../client/ConfigServerInstanceProvider.java | 28 +- .../ConfigServiceBootstrapConfiguration.java | 12 +- .../ConfigServicePropertySourceLocator.java | 33 +- ...ntConfigServiceBootstrapConfiguration.java | 12 +- .../cloud/config/client/RetryProperties.java | 5 +- .../cloud/config/environment/Environment.java | 32 +- .../config/environment/PropertySource.java | 11 +- .../main/resources/META-INF/spring.factories | 3 +- ...figServiceBootstrapConfigurationTests.java | 41 +- .../ConfigClientAutoConfigurationTests.java | 15 +- .../client/ConfigClientPropertiesTests.java | 144 ++--- .../config/client/ConfigClientWatchTests.java | 27 +- ...nfigServerBootstrapConfigurationTests.java | 32 +- .../ConfigServerHealthIndicatorTests.java | 59 +- ...nfigServiceBootstrapConfigurationTest.java | 81 +-- ...nfigServicePropertySourceLocatorTests.java | 33 +- ...tstrapConfigurationNoSpringRetryTests.java | 18 +- ...figServiceBootstrapConfigurationTests.java | 22 +- spring-cloud-config-dependencies/pom.xml | 103 ++-- spring-cloud-config-monitor/pom.xml | 5 +- ...BasePropertyPathNotificationExtractor.java | 72 +-- ...cketPropertyPathNotificationExtractor.java | 19 +- ...sitePropertyPathNotificationExtractor.java | 6 +- .../EnvironmentMonitorAutoConfiguration.java | 21 +- .../monitor/FileMonitorConfiguration.java | 22 +- ...iteaPropertyPathNotificationExtractor.java | 38 +- ...iteePropertyPathNotificationExtractor.java | 12 +- ...thubPropertyPathNotificationExtractor.java | 14 +- ...tlabPropertyPathNotificationExtractor.java | 14 +- ...GogsPropertyPathNotificationExtractor.java | 20 +- .../config/monitor/PropertyPathEndpoint.java | 22 +- .../monitor/PropertyPathNotification.java | 23 +- .../PropertyPathNotificationExtractor.java | 2 +- .../main/resources/META-INF/spring.factories | 2 +- ...ropertyPathNotificationExtractorTests.java | 85 +-- ...ropertyPathNotificationExtractorTests.java | 28 +- ...ironmentMonitorAutoConfigurationTests.java | 33 +- ...ropertyPathNotificationExtractorTests.java | 64 +-- ...ropertyPathNotificationExtractorTests.java | 17 +- ...ropertyPathNotificationExtractorTests.java | 18 +- ...ropertyPathNotificationExtractorTests.java | 20 +- ...ropertyPathNotificationExtractorTests.java | 62 +- .../monitor/PropertyPathEndpointTests.java | 79 ++- .../pathsamples/bitbucket-invalid.json | 74 +-- .../test/resources/pathsamples/bitbucket.json | 410 +++++++------- .../pathsamples/bitbucketserver-invalid.json | 60 +- .../pathsamples/bitbucketserver.json | 86 +-- .../src/test/resources/pathsamples/gitea.json | 160 +++--- .../src/test/resources/pathsamples/gitee.json | 106 ++-- .../test/resources/pathsamples/github.json | 316 +++++------ .../test/resources/pathsamples/gitlab.json | 134 ++--- .../src/test/resources/pathsamples/gogs.json | 316 +++++------ spring-cloud-config-sample/pom.xml | 23 +- .../src/main/java/sample/Application.java | 25 +- .../src/main/resources/application.yml | 2 +- .../src/main/resources/bootstrap.yml | 2 +- .../resources/bootstrapservercomposite.yml | 2 +- .../sample/ApplicationBootstrapTests.java | 63 ++- .../java/sample/ApplicationFailFastTests.java | 44 +- .../test/java/sample/ApplicationTests.java | 64 ++- .../sample/ServerNativeApplicationTests.java | 49 +- .../src/test/resources/bad.yml | 6 +- .../resources/config-repo/application.yml | 2 +- .../test/resources/config-repo/bar.properties | 2 +- .../resources/config-repo/git/COMMIT_EDITMSG | 1 + .../src/test/resources/config-repo/git/index | Bin 192 -> 225 bytes .../test/resources/config-repo/git/logs/HEAD | 1 + .../config-repo/git/logs/refs/heads/raw | 1 + .../7a/68a4bbc80b44c287787e2306ff9fd7de35cc54 | Bin 0 -> 43 bytes .../a1/9381f44efc80a21996b47adf012ef105ced909 | Bin 0 -> 97 bytes .../ae/3cdf5b88ff281b7f087143289c72a5057a0278 | Bin 0 -> 23 bytes .../b5/1bc19694589d21c06bab8a4f14660b3303d7b0 | Bin 0 -> 159 bytes .../resources/config-repo/git/refs/heads/raw | 2 +- .../src/test/resources/server.yml | 2 +- spring-cloud-config-server/pom.xml | 8 +- .../server/ConfigServerApplication.java | 21 + .../config/server/EnableConfigServer.java | 9 +- ...figServerBootstrapApplicationListener.java | 26 +- .../ConfigServerBootstrapConfiguration.java | 19 +- ...teEnvironmentBeanFactoryPostProcessor.java | 44 +- .../server/composite/CompositeUtils.java | 122 ++-- ...ConditionalOnMissingSearchPathLocator.java | 4 +- .../ConditionalOnSearchPathLocator.java | 4 +- .../composite/OnSearchPathLocatorPresent.java | 58 +- .../server/config/CompositeConfiguration.java | 7 +- .../config/ConfigServerAutoConfiguration.java | 8 +- .../config/ConfigServerConfiguration.java | 9 +- .../ConfigServerEncryptionConfiguration.java | 4 +- .../config/ConfigServerHealthIndicator.java | 42 +- .../config/ConfigServerMvcConfiguration.java | 20 +- .../server/config/ConfigServerProperties.java | 18 +- .../server/config/CredhubConfiguration.java | 3 +- .../config/EncryptionAutoConfiguration.java | 10 +- .../EnvironmentRepositoryConfiguration.java | 203 ++++--- .../ResourceRepositoryConfiguration.java | 6 +- .../diagnostics/GitUriFailureAnalyzer.java | 37 +- .../CipherEnvironmentEncryptor.java | 23 +- .../encryption/EncryptionController.java | 15 +- .../encryption/EnvironmentEncryptor.java | 4 +- .../encryption/EnvironmentPrefixHelper.java | 12 +- .../KeyStoreTextEncryptorLocator.java | 9 +- .../encryption/LocatorTextEncryptor.java | 14 +- .../encryption/PassthruSecretLocator.java | 4 +- .../server/encryption/SecretLocator.java | 2 +- .../SingleTextEncryptorLocator.java | 2 +- .../encryption/TextEncryptorLocator.java | 4 +- .../AbstractScmEnvironmentRepository.java | 17 +- .../CompositeEnvironmentRepository.java | 32 +- .../ConfigurableHttpConnectionFactory.java | 8 +- .../environment/ConsulEnvironmentWatch.java | 41 +- .../CredhubEnvironmentProperties.java | 7 +- .../CredhubEnvironmentRepository.java | 22 +- .../CredhubEnvironmentRepositoryFactory.java | 14 +- .../environment/EnvironmentCleaner.java | 5 +- .../environment/EnvironmentController.java | 151 ++--- ...ronmentEncryptorEnvironmentRepository.java | 3 +- .../EnvironmentNotFoundException.java | 8 +- .../environment/EnvironmentRepository.java | 3 +- .../EnvironmentRepositoryFactory.java | 7 +- ...onmentRepositoryPropertySourceLocator.java | 16 +- .../server/environment/EnvironmentWatch.java | 22 + ...ientConfigurableHttpConnectionFactory.java | 190 ++++--- .../HttpClientVaultRestTemplateFactory.java | 19 +- .../JGitEnvironmentProperties.java | 303 +++++----- .../JGitEnvironmentRepository.java | 113 ++-- .../JdbcEnvironmentProperties.java | 15 +- .../JdbcEnvironmentRepository.java | 33 +- .../JdbcEnvironmentRepositoryFactory.java | 14 +- .../MultipleJGitEnvironmentProperties.java | 86 +-- .../MultipleJGitEnvironmentRepository.java | 44 +- ...tipleJGitEnvironmentRepositoryFactory.java | 60 +- .../NativeEnvironmentProperties.java | 122 ++-- .../NativeEnvironmentRepository.java | 33 +- .../NativeEnvironmentRepositoryFactory.java | 23 +- .../environment/NoSuchLabelException.java | 2 +- .../NoSuchRepositoryException.java | 2 +- .../PassthruEnvironmentRepository.java | 2 +- .../environment/RepositoryException.java | 2 +- ...rchPathCompositeEnvironmentRepository.java | 24 +- .../server/environment/SearchPathLocator.java | 30 +- .../SerializableMapPropertySource.java | 16 +- .../SvnEnvironmentRepositoryFactory.java | 19 +- .../SvnKitEnvironmentProperties.java | 15 +- .../SvnKitEnvironmentRepository.java | 34 +- .../VaultEnvironmentProperties.java | 214 +++---- .../VaultEnvironmentRepository.java | 33 +- .../VaultEnvironmentRepositoryFactory.java | 38 +- .../environment/VaultKvAccessStrategy.java | 32 +- .../VaultKvAccessStrategyFactory.java | 13 +- .../VaultKvAccessStrategySupport.java | 17 +- .../proxy/ProxyHostCredentialsProvider.java | 25 +- .../server/proxy/ProxyHostProperties.java | 35 +- .../server/proxy/SchemeBasedRoutePlanner.java | 44 +- .../resource/GenericResourceRepository.java | 5 +- .../resource/NoSuchResourceException.java | 2 +- .../server/resource/ResourceController.java | 18 +- .../server/resource/ResourceRepository.java | 2 +- .../FileBasedSshTransportConfigCallback.java | 46 +- .../server/ssh/HostKeyAlgoSupported.java | 19 +- .../ssh/HostKeyAlgoSupportedValidator.java | 48 +- .../server/ssh/HostKeyAndAlgoBothExist.java | 19 +- .../ssh/HostKeyAndAlgoBothExistValidator.java | 62 +- .../server/ssh/KnownHostsFileIsValid.java | 24 +- .../server/ssh/KnownHostsFileValidator.java | 48 +- .../config/server/ssh/PrivateKeyIsValid.java | 30 +- .../server/ssh/PrivateKeyValidator.java | 50 +- ...ertiesBasedSshTransportConfigCallback.java | 47 +- .../ssh/PropertyBasedSshSessionFactory.java | 47 +- .../server/ssh/SshPropertyValidator.java | 22 +- .../server/ssh/SshUriPropertyProcessor.java | 41 +- .../server/support/AbstractScmAccessor.java | 34 +- .../AbstractScmAccessorProperties.java | 187 +++--- .../AwsCodeCommitCredentialProvider.java | 385 +++++++------ .../server/support/CredentialException.java | 5 +- .../support/EnvironmentPropertySource.java | 37 +- .../EnvironmentRepositoryProperties.java | 7 +- .../GitCredentialsProviderFactory.java | 56 +- ...tSkipSslValidationCredentialsProvider.java | 38 +- .../server/support/HttpClientSupport.java | 65 ++- .../HttpEnvironmentRepositoryProperties.java | 14 +- .../PassphraseCredentialsProvider.java | 51 +- .../server/test/ConfigServerTestUtils.java | 34 +- .../main/resources/META-INF/spring.factories | 3 - .../cloud/config/server/AdhocTestSuite.java | 32 +- ...BootstrapConfigServerIntegrationTests.java | 44 +- .../server/CompositeClasspathTests.java | 160 +++--- .../server/CompositeIntegrationTests.java | 134 +++-- .../ConfigClientOffIntegrationTests.java | 36 +- .../ConfigClientOnIntegrationTests.java | 31 +- .../server/ConfigServerApplicationTests.java | 11 +- ...CompositeConfigServerIntegrationTests.java | 29 +- .../CredhubConfigServerIntegrationTests.java | 27 +- .../config/server/CredhubIntegrationTest.java | 23 +- .../NativeBootstrapFailureAnalyzerTests.java | 32 +- .../NativeConfigServerIntegrationTests.java | 48 +- ...ubversionConfigServerIntegrationTests.java | 17 +- ...ransportConfigurationIntegrationTests.java | 531 ++++++++++-------- .../VanillaConfigServerIntegrationTests.java | 54 +- .../server/composite/CompositUtilsTests.java | 88 +-- .../ConfigServerHealthIndicatorTests.java | 41 +- ...omCompositeEnvironmentRepositoryTests.java | 95 ++-- .../CustomEnvironmentRepositoryTests.java | 19 +- ...ttpClientVaultRestTemplateFactoryTest.java | 203 +++---- ...AwsCodeCommitCredentialsProviderTests.java | 154 ++--- .../GitCredentialsProviderFactoryTests.java | 124 ++-- .../CipherEnvironmentEncryptorTests.java | 40 +- ...tionControllerMultiTextEncryptorTests.java | 29 +- .../encryption/EncryptionControllerTests.java | 54 +- .../EncryptionIntegrationTests.java | 24 +- .../EnvironmentPrefixHelperTests.java | 42 +- .../KeyStoreTextEncryptorLocatorTests.java | 26 +- .../CompositeEnvironmentRepositoryTests.java | 137 +++-- ...HttpConnectionFactoryIntegrationTests.java | 412 +++++++------- .../CredhubEnvironmentRepositoryTests.java | 112 ++-- ...EnvironmentControllerIntegrationTests.java | 36 +- .../EnvironmentControllerTests.java | 139 ++--- ...ntEncryptorEnvironmentRepositoryTests.java | 22 +- ...ConfigurableHttpConnectionFactoryTest.java | 329 ++++++----- .../environment/JGitConfigServerTestData.java | 168 +++--- ...EnvironmentRepositoryConcurrencyTests.java | 94 ++-- ...EnvironmentRepositoryIntegrationTests.java | 445 +++++++++------ .../JGitEnvironmentRepositorySslTests.java | 23 +- .../JGitEnvironmentRepositoryTests.java | 402 +++++++------ .../JdbcEnvironmentRepositoryTests.java | 11 +- ...ApplicationPlaceholderRepositoryTests.java | 55 +- ...onmentLabelPlaceholderRepositoryTests.java | 46 +- ...mentProfilePlaceholderRepositoryTests.java | 84 ++- ...EnvironmentRepositoryIntegrationTests.java | 51 +- ...ultipleJGitEnvironmentRepositoryTests.java | 149 ++--- ...ativeEnvironmentRepositoryFactoryTest.java | 25 +- .../NativeEnvironmentRepositoryTests.java | 108 ++-- ...EnvironmentRepositoryIntegrationTests.java | 26 +- .../SVNKitEnvironmentRepositoryTests.java | 85 +-- ...EnvironmentRepositoryIntegrationTests.java | 111 ++-- .../VaultEnvironmentRepositoryTests.java | 208 ++++--- .../VaultKvAccessStrategyFactoryTest.java | 10 +- .../VaultKvAccessStrategyTest.java | 29 +- .../GenericResourceRepositoryTests.java | 30 +- .../ResourceControllerIntegrationTests.java | 6 +- .../resource/ResourceControllerTests.java | 126 +++-- .../PropertyBasedSshSessionFactoryTest.java | 123 ++-- .../server/ssh/SshPropertyValidatorTest.java | 126 +++-- .../ssh/SshUriPropertyProcessorTest.java | 114 ++-- .../EnvironmentPropertySourceTest.java | 41 +- ...pSslValidationCredentialsProviderTest.java | 170 +++--- .../server/support/HttpClientSupportTest.java | 69 ++- .../another-config-repo/bar.properties | 2 +- .../another-config-repo/git/COMMIT_EDITMSG | 2 +- .../resources/another-config-repo/git/index | Bin 200 -> 261 bytes .../another-config-repo/git/logs/HEAD | 1 + .../git/logs/refs/heads/master | 1 + .../16/134a43183d280dc9bb3efce05c90c65d5c100a | Bin 0 -> 33 bytes .../37/09aa0e4ed6d9c76fdf3a9980f2a7f84defd630 | Bin 0 -> 161 bytes .../5f/72eaeb42ac3a2554e3cbc54291178a7c29be39 | Bin 0 -> 88 bytes .../ae/3cdf5b88ff281b7f087143289c72a5057a0278 | Bin 0 -> 23 bytes .../fa/7ee004088958d3c5e394d447fa2cb10b10f826 | Bin 0 -> 59 bytes .../another-config-repo/git/refs/heads/master | 2 +- .../another-config-repo/sub/application.yml | 2 +- .../src/test/resources/bad.yml | 6 +- .../test/resources/compositeconfigserver.yml | 2 +- .../resources/config-repo/application.yml | 2 +- .../test/resources/config-repo/bar.properties | 2 +- .../resources/config-repo/git/COMMIT_EDITMSG | 1 + .../src/test/resources/config-repo/git/index | Bin 225 -> 225 bytes .../test/resources/config-repo/git/logs/HEAD | 1 + .../config-repo/git/logs/refs/heads/raw | 1 + .../29/21d46f948329996d3eb4a3d11aaaff6ccda84f | Bin 0 -> 160 bytes .../7a/68a4bbc80b44c287787e2306ff9fd7de35cc54 | Bin 0 -> 43 bytes .../a1/9381f44efc80a21996b47adf012ef105ced909 | Bin 0 -> 97 bytes .../ae/3cdf5b88ff281b7f087143289c72a5057a0278 | Bin 0 -> 23 bytes .../resources/config-repo/git/refs/heads/raw | 2 +- .../resources/configserver-subversion.yml | 2 +- .../src/test/resources/configserver-test.yml | 2 +- .../src/test/resources/data-jdbc.sql | 2 +- .../src/test/resources/enable-bootstrap.yml | 1 - .../resources/encrypt-repo/application.yml | 2 +- .../resources/encrypt-repo/bar.properties | 2 +- .../resources/encrypt-repo/git/COMMIT_EDITMSG | 2 +- .../src/test/resources/encrypt-repo/git/index | Bin 225 -> 225 bytes .../test/resources/encrypt-repo/git/logs/HEAD | 1 + .../encrypt-repo/git/logs/refs/heads/master | 1 + .../1d/3ce3ac9e4a7557e95e990c264470237ddb9488 | Bin 0 -> 418 bytes .../5e/5ca6033619a9aa0524a408b1c6dc7e3c9f5b07 | Bin 0 -> 97 bytes .../ae/3cdf5b88ff281b7f087143289c72a5057a0278 | Bin 0 -> 23 bytes .../bd/414a6cc8653d7e282df0a257babc6283b83596 | Bin 0 -> 160 bytes .../encrypt-repo/git/refs/heads/master | 2 +- .../src/test/resources/foo-cloud.properties | 2 +- .../test/resources/foo-development.properties | 2 +- .../src/test/resources/foo-local.txt | 2 +- .../src/test/resources/foo.properties | 2 +- .../src/test/resources/keystore-bootstrap.yml | 2 +- .../git/COMMIT_EDITMSG | 2 +- .../master-labeltest-config-repo/git/index | Bin 233 -> 214 bytes .../resources/nested-repo/application.yml | 2 +- .../nested-repo/bar/application.properties | 2 +- .../nested-repo/foo/application.properties | 2 +- .../resources/nested-repo/git/COMMIT_EDITMSG | 2 +- .../src/test/resources/nested-repo/git/index | Bin 393 -> 393 bytes .../test/resources/nested-repo/git/logs/HEAD | 1 + .../nested-repo/git/logs/refs/heads/master | 1 + .../16/134a43183d280dc9bb3efce05c90c65d5c100a | Bin 0 -> 33 bytes .../3d/ffcc3cddcc29e350c8ff1c11c53bf577057c56 | Bin 0 -> 66 bytes .../9a/9d30fda1553c5047d2f2f510accf6238b7c131 | Bin 0 -> 117 bytes .../9d/6f44a27376f0dbe4722099e138904788ef561a | 1 + .../ae/3cdf5b88ff281b7f087143289c72a5057a0278 | Bin 0 -> 23 bytes .../c3/bb75b147f1435d96e10bbd83046e4d140c41e3 | Bin 0 -> 67 bytes .../fa/6aef940fd8b36ee6b0f1e3b1324c31fef6eaa0 | Bin 0 -> 21 bytes .../nested-repo/git/refs/heads/master | 2 +- .../src/test/resources/schema-jdbc.sql | 2 +- .../src/test/resources/ssh/key | 2 +- .../ssh/ssh-nested-settings-list.yml | 74 +-- .../resources/ssh/ssh-nested-settings.yml | 54 +- .../ssh/ssh-private-key-block-list.yml | 62 +- .../resources/ssh/ssh-private-key-block.yml | 54 +- .../ssh/ssh-private-key-newline-list.yml | 12 +- .../resources/ssh/ssh-private-key-newline.yml | 2 +- .../symmetric-key-bootstrap.properties | 2 +- .../test/dev/app/application.properties | 2 +- .../test/resources/test/dev/foo.properties | 2 +- .../test/dev/ignore/application.properties | 2 +- .../test/resources/test/dev/placeholder.txt | 2 +- .../src/test/resources/test/dev/spam/foo.txt | 2 +- .../src/test/resources/test/dev/template.json | 4 +- .../resources/test/foo-development.properties | 2 +- .../src/test/resources/test/foo.properties | 2 +- .../src/test/resources/test/local/foo.txt | 2 +- .../test/mysql/application.properties | 2 +- .../test/reactive/application.properties | 4 +- .../test1-config-repo/git/COMMIT_EDITMSG | 2 +- .../resources/test1-config-repo/git/index | Bin 233 -> 214 bytes .../test2-config-repo/application.properties | 2 +- .../test2-config-repo/bar.properties | 2 +- .../test2-config-repo/git/COMMIT_EDITMSG | 9 +- .../resources/test2-config-repo/git/index | Bin 284 -> 317 bytes .../resources/test2-config-repo/git/logs/HEAD | 1 + .../git/logs/refs/heads/master | 1 + .../6b/b5d09918a49cdbea01ac50b8d56a334440d70e | Bin 0 -> 95 bytes .../ae/3cdf5b88ff281b7f087143289c72a5057a0278 | Bin 0 -> 23 bytes .../df/6fc33edab5de1a6faaaa141de2ff0d99fb99e2 | Bin 0 -> 162 bytes .../fa/6aef940fd8b36ee6b0f1e3b1324c31fef6eaa0 | Bin 0 -> 21 bytes .../test2-config-repo/git/refs/heads/master | 2 +- spring-cloud-starter-config/pom.xml | 5 +- .../main/resources/META-INF/spring.provides | 2 +- src/checkstyle/checkstyle-suppressions.xml | 16 + 357 files changed, 8332 insertions(+), 6406 deletions(-) create mode 100644 .editorconfig create mode 100644 .springformat create mode 100644 spring-cloud-config-sample/src/test/resources/config-repo/git/COMMIT_EDITMSG create mode 100644 spring-cloud-config-sample/src/test/resources/config-repo/git/objects/7a/68a4bbc80b44c287787e2306ff9fd7de35cc54 create mode 100644 spring-cloud-config-sample/src/test/resources/config-repo/git/objects/a1/9381f44efc80a21996b47adf012ef105ced909 create mode 100644 spring-cloud-config-sample/src/test/resources/config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 create mode 100644 spring-cloud-config-sample/src/test/resources/config-repo/git/objects/b5/1bc19694589d21c06bab8a4f14660b3303d7b0 create mode 100644 spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/16/134a43183d280dc9bb3efce05c90c65d5c100a create mode 100644 spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/37/09aa0e4ed6d9c76fdf3a9980f2a7f84defd630 create mode 100644 spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/5f/72eaeb42ac3a2554e3cbc54291178a7c29be39 create mode 100644 spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 create mode 100644 spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/fa/7ee004088958d3c5e394d447fa2cb10b10f826 create mode 100644 spring-cloud-config-server/src/test/resources/config-repo/git/COMMIT_EDITMSG create mode 100644 spring-cloud-config-server/src/test/resources/config-repo/git/objects/29/21d46f948329996d3eb4a3d11aaaff6ccda84f create mode 100644 spring-cloud-config-server/src/test/resources/config-repo/git/objects/7a/68a4bbc80b44c287787e2306ff9fd7de35cc54 create mode 100644 spring-cloud-config-server/src/test/resources/config-repo/git/objects/a1/9381f44efc80a21996b47adf012ef105ced909 create mode 100644 spring-cloud-config-server/src/test/resources/config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 create mode 100644 spring-cloud-config-server/src/test/resources/encrypt-repo/git/objects/1d/3ce3ac9e4a7557e95e990c264470237ddb9488 create mode 100644 spring-cloud-config-server/src/test/resources/encrypt-repo/git/objects/5e/5ca6033619a9aa0524a408b1c6dc7e3c9f5b07 create mode 100644 spring-cloud-config-server/src/test/resources/encrypt-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 create mode 100644 spring-cloud-config-server/src/test/resources/encrypt-repo/git/objects/bd/414a6cc8653d7e282df0a257babc6283b83596 create mode 100644 spring-cloud-config-server/src/test/resources/nested-repo/git/objects/16/134a43183d280dc9bb3efce05c90c65d5c100a create mode 100644 spring-cloud-config-server/src/test/resources/nested-repo/git/objects/3d/ffcc3cddcc29e350c8ff1c11c53bf577057c56 create mode 100644 spring-cloud-config-server/src/test/resources/nested-repo/git/objects/9a/9d30fda1553c5047d2f2f510accf6238b7c131 create mode 100644 spring-cloud-config-server/src/test/resources/nested-repo/git/objects/9d/6f44a27376f0dbe4722099e138904788ef561a create mode 100644 spring-cloud-config-server/src/test/resources/nested-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 create mode 100644 spring-cloud-config-server/src/test/resources/nested-repo/git/objects/c3/bb75b147f1435d96e10bbd83046e4d140c41e3 create mode 100644 spring-cloud-config-server/src/test/resources/nested-repo/git/objects/fa/6aef940fd8b36ee6b0f1e3b1324c31fef6eaa0 create mode 100644 spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/6b/b5d09918a49cdbea01ac50b8d56a334440d70e create mode 100644 spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 create mode 100644 spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/df/6fc33edab5de1a6faaaa141de2ff0d99fb99e2 create mode 100644 spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/fa/6aef940fd8b36ee6b0f1e3b1324c31fef6eaa0 create mode 100644 src/checkstyle/checkstyle-suppressions.xml diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..0679d88a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +insert_final_newline = true + +[*.yml] +indent_style = space +indent_size = 2 diff --git a/.settings.xml b/.settings.xml index 6c355129..6f542c94 100644 --- a/.settings.xml +++ b/.settings.xml @@ -1,66 +1,68 @@ - - - repo.spring.io - ${env.CI_DEPLOY_USERNAME} - ${env.CI_DEPLOY_PASSWORD} - - - - - - spring - true - - - spring-snapshots - Spring Snapshots - http://repo.spring.io/libs-snapshot-local - - true - - - - spring-milestones - Spring Milestones - http://repo.spring.io/libs-milestone-local - - false - - - - spring-releases - Spring Releases - http://repo.spring.io/release - - false - - - - - - spring-snapshots - Spring Snapshots - http://repo.spring.io/libs-snapshot-local - - true - - - - spring-milestones - Spring Milestones - http://repo.spring.io/libs-milestone-local - - false - - - - - + + + repo.spring.io + ${env.CI_DEPLOY_USERNAME} + ${env.CI_DEPLOY_PASSWORD} + + + + + + spring + + true + + + + spring-snapshots + Spring Snapshots + http://repo.spring.io/libs-snapshot-local + + true + + + + spring-milestones + Spring Milestones + http://repo.spring.io/libs-milestone-local + + false + + + + spring-releases + Spring Releases + http://repo.spring.io/release + + false + + + + + + spring-snapshots + Spring Snapshots + http://repo.spring.io/libs-snapshot-local + + true + + + + spring-milestones + Spring Milestones + http://repo.spring.io/libs-milestone-local + + false + + + + + diff --git a/.springformat b/.springformat new file mode 100644 index 00000000..e69de29b diff --git a/docs/pom.xml b/docs/pom.xml index b975bc71..a347f98c 100644 --- a/docs/pom.xml +++ b/docs/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 org.springframework.cloud spring-cloud-config-docs @@ -18,14 +20,14 @@ ${basedir}/.. 1.3.x,1.4.x - + - - maven-deploy-plugin - - true - + + maven-deploy-plugin + + true + @@ -33,31 +35,31 @@ docs - - - org.apache.maven.plugins - maven-dependency-plugin - - - org.asciidoctor - asciidoctor-maven-plugin - false - - - com.agilejava.docbkx - docbkx-maven-plugin - - - org.apache.maven.plugins - maven-antrun-plugin - false - - - org.codehaus.mojo - build-helper-maven-plugin - false - - + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.asciidoctor + asciidoctor-maven-plugin + false + + + com.agilejava.docbkx + docbkx-maven-plugin + + + org.apache.maven.plugins + maven-antrun-plugin + false + + + org.codehaus.mojo + build-helper-maven-plugin + false + + diff --git a/pom.xml b/pom.xml index c1b165c0..2613c9fd 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 org.springframework.cloud spring-cloud-config @@ -16,14 +18,23 @@ https://github.com/spring-cloud/spring-cloud-config - scm:git:git://github.com/spring-cloud/spring-cloud-config.git - scm:git:ssh://git@github.com/spring-cloud/spring-cloud-config.git + scm:git:git://github.com/spring-cloud/spring-cloud-config.git + + + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-config.git + HEAD - - config + + config 2.1.1.BUILD-SNAPSHOT - + + true + true + + true + + spring-cloud-config-dependencies spring-cloud-config-client @@ -33,7 +44,7 @@ spring-cloud-starter-config docs - + org.springframework.cloud @@ -61,7 +72,7 @@ 1.11.52 - + spring @@ -139,7 +150,8 @@ surefireArgLine - ${project.build.directory}/jacoco.exec + ${project.build.directory}/jacoco.exec + @@ -150,7 +162,8 @@ - ${project.build.directory}/jacoco.exec + ${project.build.directory}/jacoco.exec + @@ -167,4 +180,27 @@ + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + io.spring.javaformat + spring-javaformat-maven-plugin + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + + diff --git a/sample.groovy b/sample.groovy index 4aa47868..f798b269 100644 --- a/sample.groovy +++ b/sample.groovy @@ -3,8 +3,8 @@ package demo @Grab('spring-cloud-starter') @RestController class Application { - @RequestMapping("/") - String home() { - "Hello World" - } -} \ No newline at end of file + @RequestMapping("/") + String home() { + "Hello World" + } +} diff --git a/spring-cloud-config-client/pom.xml b/spring-cloud-config-client/pom.xml index 11e1df1b..0cb42071 100644 --- a/spring-cloud-config-client/pom.xml +++ b/spring-cloud-config-client/pom.xml @@ -1,7 +1,7 @@ - + 4.0.0 spring-cloud-config-client jar diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientAutoConfiguration.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientAutoConfiguration.java index 72f4fb85..5d2171bb 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientAutoConfiguration.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.client; import org.springframework.beans.factory.BeanFactoryUtils; @@ -20,7 +21,6 @@ import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.refresh.ContextRefresher; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @@ -70,18 +70,20 @@ public class ConfigClientAutoConfiguration { ConfigClientHealthProperties properties, Environment environment) { return new ConfigServerHealthIndicator(locator, environment, properties); } + } @Configuration @ConditionalOnClass(ContextRefresher.class) @ConditionalOnBean(ContextRefresher.class) - @ConditionalOnProperty(value = "spring.cloud.config.watch.enabled") + @ConditionalOnProperty("spring.cloud.config.watch.enabled") protected static class ConfigClientWatchConfiguration { @Bean public ConfigClientWatch configClientWatch(ContextRefresher contextRefresher) { return new ConfigClientWatch(contextRefresher); } + } } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientHealthProperties.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientHealthProperties.java index 717b963e..25c1f4d2 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientHealthProperties.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientHealthProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT 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.springframework.cloud.config.client; @@ -24,6 +23,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; */ @ConfigurationProperties("health.config") public class ConfigClientHealthProperties { + /** * Flag to indicate that the config server health indicator should be installed. */ @@ -43,10 +43,11 @@ public class ConfigClientHealthProperties { } public long getTimeToLive() { - return timeToLive; + return this.timeToLive; } public void setTimeToLive(long timeToLive) { this.timeToLive = timeToLive; } + } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientProperties.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientProperties.java index ef8aaf19..f1cf90c6 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientProperties.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import java.util.Map; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; import org.springframework.web.util.UriComponentsBuilder; @@ -37,9 +36,24 @@ import org.springframework.web.util.UriComponentsBuilder; @ConfigurationProperties(ConfigClientProperties.PREFIX) public class ConfigClientProperties { + /** + * Prefix for Spring Cloud Config properties. + */ public static final String PREFIX = "spring.cloud.config"; + + /** + * Token header name. + */ public static final String TOKEN_HEADER = "X-Config-Token"; + + /** + * State header name. + */ public static final String STATE_HEADER = "X-Config-State"; + + /** + * Authorization header name. + */ public static final String AUTHORIZATION = "authorization"; /** @@ -162,7 +176,7 @@ public class ConfigClientProperties { } public String getUsername() { - return username; + return this.username; } public void setUsername(String username) { @@ -170,7 +184,7 @@ public class ConfigClientProperties { } public String getPassword() { - return password; + return this.password; } public void setPassword(String password) { @@ -206,7 +220,7 @@ public class ConfigClientProperties { } public int getRequestReadTimeout() { - return requestReadTimeout; + return this.requestReadTimeout; } public void setRequestReadTimeout(int requestReadTimeout) { @@ -214,7 +228,7 @@ public class ConfigClientProperties { } public boolean isSendState() { - return sendState; + return this.sendState; } public void setSendState(boolean sendState) { @@ -222,7 +236,7 @@ public class ConfigClientProperties { } public Map getHeaders() { - return headers; + return this.headers; } public void setHeaders(Map headers) { @@ -294,26 +308,68 @@ public class ConfigClientProperties { return credentials; } + public ConfigClientProperties override( + org.springframework.core.env.Environment environment) { + ConfigClientProperties override = new ConfigClientProperties(); + BeanUtils.copyProperties(this, override); + override.setName( + environment.resolvePlaceholders("${" + ConfigClientProperties.PREFIX + + ".name:${spring.application.name:application}}")); + if (environment.containsProperty(ConfigClientProperties.PREFIX + ".profile")) { + override.setProfile( + environment.getProperty(ConfigClientProperties.PREFIX + ".profile")); + } + if (environment.containsProperty(ConfigClientProperties.PREFIX + ".label")) { + override.setLabel( + environment.getProperty(ConfigClientProperties.PREFIX + ".label")); + } + return override; + } + + @Override + public String toString() { + return "ConfigClientProperties [enabled=" + this.enabled + ", profile=" + + this.profile + ", name=" + this.name + ", label=" + this.label + + ", username=" + this.username + ", password=" + this.password + ", uri=" + + Arrays.toString(this.uri) + ", discovery=" + this.discovery + + ", failFast=" + this.failFast + ", token=" + this.token + + ", requestReadTimeout=" + this.requestReadTimeout + ", sendState=" + + this.sendState + ", headers=" + this.headers + "]"; + } + + /** + * Credentials properties. + */ public static class Credentials { private String username; + private String password; + private String uri; public String getUsername() { - return username; + return this.username; } public String getPassword() { - return password; + return this.password; } public String getUri() { - return uri; + return this.uri; } + } + /** + * Discovery properties. + */ public static class Discovery { + + /** + * Default config server service id name. + */ public static final String DEFAULT_CONFIG_SERVER = "configserver"; /** @@ -321,6 +377,7 @@ public class ConfigClientProperties { * will be looked up via discovery). */ private boolean enabled; + /** * Service id to locate config server. */ @@ -344,34 +401,4 @@ public class ConfigClientProperties { } - public ConfigClientProperties override( - org.springframework.core.env.Environment environment) { - ConfigClientProperties override = new ConfigClientProperties(); - BeanUtils.copyProperties(this, override); - override.setName( - environment.resolvePlaceholders("${" + ConfigClientProperties.PREFIX - + ".name:${spring.application.name:application}}")); - if (environment.containsProperty(ConfigClientProperties.PREFIX + ".profile")) { - override.setProfile( - environment.getProperty(ConfigClientProperties.PREFIX + ".profile")); - } - if (environment.containsProperty(ConfigClientProperties.PREFIX + ".label")) { - override.setLabel( - environment.getProperty(ConfigClientProperties.PREFIX + ".label")); - } - return override; - } - - @Override - public String toString() { - return "ConfigClientProperties [enabled=" + enabled + ", profile=" + profile - + ", name=" + name + ", label=" + label + ", username=" + username - + ", password=" + password + ", uri=" + Arrays.toString(uri) - + ", discovery=" + discovery + ", failFast=" + failFast + ", token=" - + token + ", requestReadTimeout=" + requestReadTimeout + ", sendState=" - + sendState + ", headers=" + headers + "]"; - } - - - } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientStateHolder.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientStateHolder.java index ca4d8a2b..b3d95f9d 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientStateHolder.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientStateHolder.java @@ -1,15 +1,40 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.client; /** * @author Spencer Gibb */ -public class ConfigClientStateHolder { +public final class ConfigClientStateHolder { + + private ConfigClientStateHolder() { + throw new IllegalStateException("Can't instantiate a utility class"); + } + private static ThreadLocal state = new ThreadLocal<>(); public static void resetState() { state.remove(); } + public static String getState() { + return state.get(); + } + public static void setState(String newState) { if (newState == null) { resetState(); @@ -18,7 +43,4 @@ public class ConfigClientStateHolder { state.set(newState); } - public static String getState() { - return state.get(); - } } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java index 95e999bb..5cce6d7c 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,12 @@ package org.springframework.cloud.config.client; import java.io.Closeable; import java.util.concurrent.atomic.AtomicBoolean; + import javax.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.context.refresh.ContextRefresher; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; @@ -34,11 +36,12 @@ import static org.springframework.util.StringUtils.hasText; */ public class ConfigClientWatch implements Closeable, EnvironmentAware { - private static Log log = LogFactory - .getLog(ConfigServicePropertySourceLocator.class); + private static Log log = LogFactory.getLog(ConfigServicePropertySourceLocator.class); private final AtomicBoolean running = new AtomicBoolean(false); + private final ContextRefresher refresher; + private Environment environment; public ConfigClientWatch(ContextRefresher refresher) { @@ -59,7 +62,7 @@ public class ConfigClientWatch implements Closeable, EnvironmentAware { public void watchConfigServer() { if (this.running.get()) { String newState = this.environment.getProperty("config.client.state"); - String oldState = ConfigClientStateHolder.getState(); + String oldState = ConfigClientStateHolder.getState(); // only refresh if state has changed if (stateChanged(oldState, newState)) { @@ -71,7 +74,7 @@ public class ConfigClientWatch implements Closeable, EnvironmentAware { /* for testing */ boolean stateChanged(String oldState, String newState) { return (!hasText(oldState) && hasText(newState)) - || (hasText(oldState) && !oldState.equals(newState)); + || (hasText(oldState) && !oldState.equals(newState)); } @Override diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerHealthIndicator.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerHealthIndicator.java index b77b1a18..799bd20c 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerHealthIndicator.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerHealthIndicator.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.client; import java.util.ArrayList; @@ -16,7 +32,9 @@ import org.springframework.core.env.PropertySource; public class ConfigServerHealthIndicator extends AbstractHealthIndicator { private ConfigServicePropertySourceLocator locator; + private ConfigClientHealthProperties properties; + private Environment environment; private long lastAccess = 0; @@ -30,28 +48,31 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator { this.properties = properties; } - @Override - protected void doHealthCheck(Builder builder) throws Exception { + @Override + protected void doHealthCheck(Builder builder) throws Exception { PropertySource propertySource = getPropertySource(); builder.up(); if (propertySource instanceof CompositePropertySource) { List sources = new ArrayList<>(); - for (PropertySource ps : ((CompositePropertySource) propertySource).getPropertySources()) { + for (PropertySource ps : ((CompositePropertySource) propertySource) + .getPropertySources()) { sources.add(ps.getName()); } builder.withDetail("propertySources", sources); - } else if (propertySource!=null) { + } + else if (propertySource != null) { builder.withDetail("propertySources", propertySource.toString()); - } else { + } + else { builder.unknown().withDetail("error", "no property sources located"); } - } + } private PropertySource getPropertySource() { long accessTime = System.currentTimeMillis(); if (isCacheStale(accessTime)) { this.lastAccess = accessTime; - this.cached = locator.locate(this.environment); + this.cached = this.locator.locate(this.environment); } return this.cached; } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerInstanceProvider.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerInstanceProvider.java index ad3a2097..1ea98ef2 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerInstanceProvider.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerInstanceProvider.java @@ -1,16 +1,39 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.client; +import java.util.List; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.retry.annotation.Retryable; -import java.util.List; - +/** + * Fetches config server instances. + * + * @author Nastya Smirnova + */ public class ConfigServerInstanceProvider { private static Log logger = LogFactory.getLog(ConfigServerInstanceProvider.class); + private final DiscoveryClient client; public ConfigServerInstanceProvider(DiscoveryClient client) { @@ -29,4 +52,5 @@ public class ConfigServerInstanceProvider { + ") via discovery. No of instances found: " + instances.size()); return instances; } + } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfiguration.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfiguration.java index 4a9237a9..85671071 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.config.client; import org.aspectj.lang.annotation.Aspect; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -53,13 +54,14 @@ public class ConfigServiceBootstrapConfiguration { @Bean @ConditionalOnMissingBean(ConfigServicePropertySourceLocator.class) @ConditionalOnProperty(value = "spring.cloud.config.enabled", matchIfMissing = true) - public ConfigServicePropertySourceLocator configServicePropertySource(ConfigClientProperties properties) { + public ConfigServicePropertySourceLocator configServicePropertySource( + ConfigClientProperties properties) { ConfigServicePropertySourceLocator locator = new ConfigServicePropertySourceLocator( properties); return locator; } - @ConditionalOnProperty(value = "spring.cloud.config.fail-fast") + @ConditionalOnProperty("spring.cloud.config.fail-fast") @ConditionalOnClass({ Retryable.class, Aspect.class, AopAutoConfiguration.class }) @Configuration @EnableRetry(proxyTargetClass = true) @@ -71,12 +73,12 @@ public class ConfigServiceBootstrapConfiguration { @ConditionalOnMissingBean(name = "configServerRetryInterceptor") public RetryOperationsInterceptor configServerRetryInterceptor( RetryProperties properties) { - return RetryInterceptorBuilder - .stateless() + return RetryInterceptorBuilder.stateless() .backOffOptions(properties.getInitialInterval(), properties.getMultiplier(), properties.getMaxInterval()) .maxAttempts(properties.getMaxAttempts()).build(); } + } } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocator.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocator.java index da848a6b..48a074b0 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocator.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.bootstrap.config.PropertySourceLocator; import org.springframework.cloud.config.client.ConfigClientProperties.Credentials; import org.springframework.cloud.config.environment.Environment; @@ -51,9 +52,9 @@ import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; +import static org.springframework.cloud.config.client.ConfigClientProperties.AUTHORIZATION; import static org.springframework.cloud.config.client.ConfigClientProperties.STATE_HEADER; import static org.springframework.cloud.config.client.ConfigClientProperties.TOKEN_HEADER; -import static org.springframework.cloud.config.client.ConfigClientProperties.AUTHORIZATION; /** * @author Dave Syer @@ -67,6 +68,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator .getLog(ConfigServicePropertySourceLocator.class); private RestTemplate restTemplate; + private ConfigClientProperties defaultProperties; public ConfigServicePropertySourceLocator(ConfigClientProperties defaultProperties) { @@ -80,8 +82,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator ConfigClientProperties properties = this.defaultProperties.override(environment); CompositePropertySource composite = new CompositePropertySource("configService"); RestTemplate restTemplate = this.restTemplate == null - ? getSecureRestTemplate(properties) - : this.restTemplate; + ? getSecureRestTemplate(properties) : this.restTemplate; Exception error = null; String errorBody = null; try { @@ -134,12 +135,12 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator } if (properties.isFailFast()) { throw new IllegalStateException( - "Could not locate PropertySource and the fail fast property is set, failing" + - (errorBody == null ? "" : ": " + errorBody), error); + "Could not locate PropertySource and the fail fast property is set, failing" + + (errorBody == null ? "" : ": " + errorBody), + error); } logger.warn("Could not locate PropertySource: " + (errorBody == null - ? error == null ? "label not found" : error.getMessage() - : errorBody)); + ? error == null ? "label not found" : error.getMessage() : errorBody)); return null; } @@ -226,10 +227,12 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator catch (ResourceAccessException e) { logger.info("Connect Timeout Exception on Url - " + uri + ". Will be trying the next url if available"); - if (i == noOfUrls - 1) + if (i == noOfUrls - 1) { throw e; - else + } + else { continue; + } } if (response == null || response.getStatusCode() != HttpStatus.OK) { @@ -259,7 +262,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator headers.remove(AUTHORIZATION); // To avoid redundant addition of header } if (!headers.isEmpty()) { - template.setInterceptors(Arrays. asList( + template.setInterceptors(Arrays.asList( new GenericRequestHeaderInterceptor(headers))); } @@ -285,6 +288,9 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator } + /** + * Adds the provided headers to the request. + */ public static class GenericRequestHeaderInterceptor implements ClientHttpRequestInterceptor { @@ -297,15 +303,16 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - for (Entry header : headers.entrySet()) { + for (Entry header : this.headers.entrySet()) { request.getHeaders().add(header.getKey(), header.getValue()); } return execution.execute(request, body); } protected Map getHeaders() { - return headers; + return this.headers; } } + } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfiguration.java index a716efcc..ef3cc514 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,8 @@ import org.springframework.context.event.SmartApplicationListener; @Configuration @Import({ UtilAutoConfiguration.class }) @EnableDiscoveryClient -public class DiscoveryClientConfigServiceBootstrapConfiguration implements SmartApplicationListener { +public class DiscoveryClientConfigServiceBootstrapConfiguration + implements SmartApplicationListener { private static Log logger = LogFactory .getLog(DiscoveryClientConfigServiceBootstrapConfiguration.class); @@ -76,7 +77,8 @@ public class DiscoveryClientConfigServiceBootstrapConfiguration implements Smart public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { startup((ContextRefreshedEvent) event); - } else if (event instanceof HeartbeatEvent) { + } + else if (event instanceof HeartbeatEvent) { heartbeat((HeartbeatEvent) event); } } @@ -86,7 +88,7 @@ public class DiscoveryClientConfigServiceBootstrapConfiguration implements Smart } public void heartbeat(HeartbeatEvent event) { - if (monitor.update(event.getValue())) { + if (this.monitor.update(event.getValue())) { refresh(); } } @@ -128,7 +130,7 @@ public class DiscoveryClientConfigServiceBootstrapConfiguration implements Smart } catch (Exception ex) { - if (config.isFailFast()) { + if (this.config.isFailFast()) { throw ex; } else { diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/RetryProperties.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/RetryProperties.java index 38f2d10c..736e262a 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/RetryProperties.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/RetryProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,14 +29,17 @@ public class RetryProperties { * Initial retry interval in milliseconds. */ long initialInterval = 1000; + /** * Multiplier for next interval. */ double multiplier = 1.1; + /** * Maximum interval for backoff. */ long maxInterval = 2000; + /** * Maximum number of attempts. */ diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/environment/Environment.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/environment/Environment.java index 184dd57b..2da199eb 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/environment/Environment.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/environment/Environment.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,18 +51,18 @@ public class Environment { } /** - * Copies all fields except propertySources - * @param env + * Copies all fields except propertySources. + * @param env Spring Environment */ public Environment(Environment env) { - this(env.getName(), env.getProfiles(), env.getLabel(), env.getVersion(), env.getState()); + this(env.getName(), env.getProfiles(), env.getLabel(), env.getVersion(), + env.getState()); } @JsonCreator public Environment(@JsonProperty("name") String name, @JsonProperty("profiles") String[] profiles, - @JsonProperty("label") String label, - @JsonProperty("version") String version, + @JsonProperty("label") String label, @JsonProperty("version") String version, @JsonProperty("state") String state) { super(); this.name = name; @@ -85,11 +85,11 @@ public class Environment { } public List getPropertySources() { - return propertySources; + return this.propertySources; } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -97,7 +97,7 @@ public class Environment { } public String getLabel() { - return label; + return this.label; } public void setLabel(String label) { @@ -105,7 +105,7 @@ public class Environment { } public String[] getProfiles() { - return profiles; + return this.profiles; } public void setProfiles(String[] profiles) { @@ -113,7 +113,7 @@ public class Environment { } public String getVersion() { - return version; + return this.version; } public void setVersion(String version) { @@ -121,7 +121,7 @@ public class Environment { } public String getState() { - return state; + return this.state; } public void setState(String state) { @@ -130,10 +130,10 @@ public class Environment { @Override public String toString() { - return "Environment [name=" + name + ", profiles=" + Arrays.asList(profiles) - + ", label=" + label + ", propertySources=" + propertySources - + ", version=" + version - + ", state=" + state + "]"; + return "Environment [name=" + this.name + ", profiles=" + + Arrays.asList(this.profiles) + ", label=" + this.label + + ", propertySources=" + this.propertySources + ", version=" + + this.version + ", state=" + this.state + "]"; } } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/environment/PropertySource.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/environment/PropertySource.java index 974cabfc..2366ae93 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/environment/PropertySource.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/environment/PropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,9 +25,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Simple plain text serializable encapsulation of a named source of key-value pairs. * Basically a DTO for {@link PropertySource}, but also applicable outside the domain of a * Spring application. - * - * @author Dave Syer * + * @author Dave Syer */ public class PropertySource { @@ -43,16 +42,16 @@ public class PropertySource { } public String getName() { - return name; + return this.name; } public Map getSource() { - return source; + return this.source; } @Override public String toString() { - return "PropertySource [name=" + name + "]"; + return "PropertySource [name=" + this.name + "]"; } } diff --git a/spring-cloud-config-client/src/main/resources/META-INF/spring.factories b/spring-cloud-config-client/src/main/resources/META-INF/spring.factories index 4efe1764..2841101a 100644 --- a/spring-cloud-config-client/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-config-client/src/main/resources/META-INF/spring.factories @@ -1,8 +1,7 @@ # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.config.client.ConfigClientAutoConfiguration - # Bootstrap components org.springframework.cloud.bootstrap.BootstrapConfiguration=\ org.springframework.cloud.config.client.ConfigServiceBootstrapConfiguration,\ -org.springframework.cloud.config.client.DiscoveryClientConfigServiceBootstrapConfiguration \ No newline at end of file +org.springframework.cloud.config.client.DiscoveryClientConfigServiceBootstrapConfiguration diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/BaseDiscoveryClientConfigServiceBootstrapConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/BaseDiscoveryClientConfigServiceBootstrapConfigurationTests.java index 088c34d8..1bb99232 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/BaseDiscoveryClientConfigServiceBootstrapConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/BaseDiscoveryClientConfigServiceBootstrapConfigurationTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.client; import java.util.Arrays; @@ -17,7 +33,7 @@ import org.springframework.cloud.commons.util.UtilAutoConfiguration; import org.springframework.cloud.config.client.ConfigClientProperties.Credentials; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -44,7 +60,7 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest void givenDiscoveryClientReturnsNoInfo() { given(this.client.getInstances(DEFAULT_CONFIG_SERVER)) - .willReturn(Collections. emptyList()); + .willReturn(Collections.emptyList()); } void givenDiscoveryClientReturnsInfo() { @@ -60,20 +76,21 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest void givenDiscoveryClientReturnsInfoOnThirdTry() { given(this.client.getInstances(DEFAULT_CONFIG_SERVER)) - .willReturn(Collections. emptyList()) - .willReturn(Collections. emptyList()) + .willReturn(Collections.emptyList()) + .willReturn(Collections.emptyList()) .willReturn(Arrays.asList(this.info)); } void expectNoInstancesOfConfigServerException() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage( + this.expectedException.expect(IllegalStateException.class); + this.expectedException.expectMessage( "No instances found of configserver (" + DEFAULT_CONFIG_SERVER + ")"); } void expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup() { - assertEquals(1, this.context.getBeanNamesForType( - DiscoveryClientConfigServiceBootstrapConfiguration.class).length); + assertThat(this.context.getBeanNamesForType( + DiscoveryClientConfigServiceBootstrapConfiguration.class).length) + .isEqualTo(1); } void expectConfigClientPropertiesHasDefaultConfiguration() { @@ -88,18 +105,18 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest ConfigClientProperties properties = this.context .getBean(ConfigClientProperties.class); Credentials credentials = properties.getCredentials(0); - assertEquals(expectedUri, credentials.getUri()); + assertThat(credentials.getUri()).isEqualTo(expectedUri); } void expectConfigClientPropertiesHasMultipleUris(final String expectedUri1, final String expectedUri2) { ConfigClientProperties properties = this.context .getBean(ConfigClientProperties.class); - assertEquals(2, properties.getUri().length); + assertThat(properties.getUri().length).isEqualTo(2); Credentials credentials1 = properties.getCredentials(0); Credentials credentials2 = properties.getCredentials(1); - assertEquals(expectedUri1, credentials1.getUri()); - assertEquals(expectedUri2, credentials2.getUri()); + assertThat(credentials1.getUri()).isEqualTo(expectedUri1); + assertThat(credentials2.getUri()).isEqualTo(expectedUri2); } void verifyDiscoveryClientCalledThreeTimes() { diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientAutoConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientAutoConfigurationTests.java index 23e36e3d..878c45b5 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientAutoConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class ConfigClientAutoConfigurationTests { @@ -32,17 +32,18 @@ public class ConfigClientAutoConfigurationTests { public void sunnyDay() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ConfigClientAutoConfiguration.class); - assertEquals(1, BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, - ConfigClientProperties.class).length); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, + ConfigClientProperties.class).length).isEqualTo(1); context.close(); } @Test public void withParent() { ConfigurableApplicationContext context = new SpringApplicationBuilder( - ConfigClientAutoConfiguration.class).child(Object.class).web(WebApplicationType.NONE).run(); - assertEquals(1, BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, - ConfigClientProperties.class).length); + ConfigClientAutoConfiguration.class).child(Object.class) + .web(WebApplicationType.NONE).run(); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, + ConfigClientProperties.class).length).isEqualTo(1); context.close(); } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientPropertiesTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientPropertiesTests.java index 6e7d5038..b41669bf 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientPropertiesTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.client; +import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.cloud.config.client.ConfigClientProperties.Credentials; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.env.MockEnvironment; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import org.junit.Rule; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -35,96 +34,96 @@ import org.junit.Rule; */ public class ConfigClientPropertiesTests { - private ConfigClientProperties locator = new ConfigClientProperties( - new StandardEnvironment()); - @Rule public ExpectedException expected = ExpectedException.none(); + private ConfigClientProperties locator = new ConfigClientProperties( + new StandardEnvironment()); + @Test public void vanilla() { - locator.setUri(new String[] { "http://localhost:9999" }); - locator.setPassword("secret"); - Credentials credentials = locator.getCredentials(0); - assertEquals("http://localhost:9999", credentials.getUri()); - assertEquals("user", credentials.getUsername()); - assertEquals("secret", credentials.getPassword()); + this.locator.setUri(new String[] { "http://localhost:9999" }); + this.locator.setPassword("secret"); + Credentials credentials = this.locator.getCredentials(0); + assertThat(credentials.getUri()).isEqualTo("http://localhost:9999"); + assertThat(credentials.getUsername()).isEqualTo("user"); + assertThat(credentials.getPassword()).isEqualTo("secret"); } @Test public void uriCreds() { - locator.setUri(new String[] { "http://foo:bar@localhost:9999" }); - Credentials credentials = locator.getCredentials(0); - assertEquals("http://localhost:9999", credentials.getUri()); - assertEquals("foo", credentials.getUsername()); - assertEquals("bar", credentials.getPassword()); + this.locator.setUri(new String[] { "http://foo:bar@localhost:9999" }); + Credentials credentials = this.locator.getCredentials(0); + assertThat(credentials.getUri()).isEqualTo("http://localhost:9999"); + assertThat(credentials.getUsername()).isEqualTo("foo"); + assertThat(credentials.getPassword()).isEqualTo("bar"); } @Test public void explicitPassword() { - locator.setUri(new String[] { "http://foo:bar@localhost:9999" }); - locator.setPassword("secret"); - Credentials credentials = locator.getCredentials(0); - assertEquals("http://localhost:9999", credentials.getUri()); - assertEquals("foo", credentials.getUsername()); - assertEquals("secret", credentials.getPassword()); + this.locator.setUri(new String[] { "http://foo:bar@localhost:9999" }); + this.locator.setPassword("secret"); + Credentials credentials = this.locator.getCredentials(0); + assertThat(credentials.getUri()).isEqualTo("http://localhost:9999"); + assertThat(credentials.getUsername()).isEqualTo("foo"); + assertThat(credentials.getPassword()).isEqualTo("secret"); } @Test public void testIfNoColonPresentInUriCreds() { - locator.setUri(new String[] { "http://foobar@localhost:9999" }); - locator.setPassword("secret"); - Credentials credentials = locator.getCredentials(0); - assertEquals("http://localhost:9999", credentials.getUri()); - assertEquals("foobar", credentials.getUsername()); - assertEquals("secret", credentials.getPassword()); + this.locator.setUri(new String[] { "http://foobar@localhost:9999" }); + this.locator.setPassword("secret"); + Credentials credentials = this.locator.getCredentials(0); + assertThat(credentials.getUri()).isEqualTo("http://localhost:9999"); + assertThat(credentials.getUsername()).isEqualTo("foobar"); + assertThat(credentials.getPassword()).isEqualTo("secret"); } @Test public void testIfColonPresentAtTheEndInUriCreds() { - locator.setUri(new String[] { "http://foobar:@localhost:9999" }); - locator.setPassword("secret"); - Credentials credentials = locator.getCredentials(0); - assertEquals("http://localhost:9999", credentials.getUri()); - assertEquals("foobar", credentials.getUsername()); - assertEquals("secret", credentials.getPassword()); + this.locator.setUri(new String[] { "http://foobar:@localhost:9999" }); + this.locator.setPassword("secret"); + Credentials credentials = this.locator.getCredentials(0); + assertThat(credentials.getUri()).isEqualTo("http://localhost:9999"); + assertThat(credentials.getUsername()).isEqualTo("foobar"); + assertThat(credentials.getPassword()).isEqualTo("secret"); } @Test public void testIfColonPresentAtTheStartInUriCreds() { - locator.setUri(new String[] { "http://:foobar@localhost:9999" }); - Credentials credentials = locator.getCredentials(0); - assertEquals("http://localhost:9999", credentials.getUri()); - assertEquals("", credentials.getUsername()); - assertEquals("foobar", credentials.getPassword()); + this.locator.setUri(new String[] { "http://:foobar@localhost:9999" }); + Credentials credentials = this.locator.getCredentials(0); + assertThat(credentials.getUri()).isEqualTo("http://localhost:9999"); + assertThat(credentials.getUsername()).isEqualTo(""); + assertThat(credentials.getPassword()).isEqualTo("foobar"); } @Test public void testIfColonPresentAtTheStartAndEndInUriCreds() { - locator.setUri(new String[] { "http://:foobar:@localhost:9999" }); - Credentials credentials = locator.getCredentials(0); - assertEquals("http://localhost:9999", credentials.getUri()); - assertEquals("", credentials.getUsername()); - assertEquals("foobar:", credentials.getPassword()); + this.locator.setUri(new String[] { "http://:foobar:@localhost:9999" }); + Credentials credentials = this.locator.getCredentials(0); + assertThat(credentials.getUri()).isEqualTo("http://localhost:9999"); + assertThat(credentials.getUsername()).isEqualTo(""); + assertThat(credentials.getPassword()).isEqualTo("foobar:"); } @Test public void testIfSpacePresentAsUriCreds() { - locator.setUri(new String[] { "http:// @localhost:9999" }); - locator.setPassword("secret"); - Credentials credentials = locator.getCredentials(0); - assertEquals("http://localhost:9999", credentials.getUri()); - assertEquals(" ", credentials.getUsername()); - assertEquals("secret", credentials.getPassword()); + this.locator.setUri(new String[] { "http:// @localhost:9999" }); + this.locator.setPassword("secret"); + Credentials credentials = this.locator.getCredentials(0); + assertThat(credentials.getUri()).isEqualTo("http://localhost:9999"); + assertThat(credentials.getUsername()).isEqualTo(" "); + assertThat(credentials.getPassword()).isEqualTo("secret"); } @Test public void changeNameInOverride() { - locator.setName("one"); + this.locator.setName("one"); ConfigurableEnvironment environment = new StandardEnvironment(); TestPropertyValues.of("spring.application.name:two").applyTo(environment); - ConfigClientProperties override = locator.override(environment); - assertEquals("two", override.getName()); + ConfigClientProperties override = this.locator.override(environment); + assertThat(override.getName()).isEqualTo("two"); } @Test @@ -137,32 +136,35 @@ public class ConfigClientPropertiesTests { properties.setUsername("explicitName"); properties.setPassword("explicitPW"); Credentials credentials = properties.getCredentials(0); - assertThat(credentials.getPassword(), equalTo("explicitPW")); - assertThat(credentials.getUsername(), equalTo("explicitName")); + assertThat(credentials.getPassword()).isEqualTo("explicitPW"); + assertThat(credentials.getUsername()).isEqualTo("explicitName"); } @Test public void checkIfExceptionThrownForNegativeIndex() { - locator.setUri(new String[] { "http://localhost:8888", "http://localhost:8889" }); - expected.expect(IllegalStateException.class); - expected.expectMessage("Trying to access an invalid array index"); - Credentials credentials = locator.getCredentials(-1); + this.locator.setUri( + new String[] { "http://localhost:8888", "http://localhost:8889" }); + this.expected.expect(IllegalStateException.class); + this.expected.expectMessage("Trying to access an invalid array index"); + Credentials credentials = this.locator.getCredentials(-1); } @Test public void checkIfExceptionThrownForPositiveInvalidIndex() { - locator.setUri(new String[] { "http://localhost:8888", "http://localhost:8889" }); - expected.expect(IllegalStateException.class); - expected.expectMessage("Trying to access an invalid array index"); - Credentials credentials = locator.getCredentials(3); + this.locator.setUri( + new String[] { "http://localhost:8888", "http://localhost:8889" }); + this.expected.expect(IllegalStateException.class); + this.expected.expectMessage("Trying to access an invalid array index"); + Credentials credentials = this.locator.getCredentials(3); } @Test public void checkIfExceptionThrownForIndexEqualToLength() { - locator.setUri(new String[] { "http://localhost:8888", "http://localhost:8889" }); - expected.expect(IllegalStateException.class); - expected.expectMessage("Trying to access an invalid array index"); - Credentials credentials = locator.getCredentials(2); + this.locator.setUri( + new String[] { "http://localhost:8888", "http://localhost:8889" }); + this.expected.expect(IllegalStateException.class); + this.expected.expectMessage("Trying to access an invalid array index"); + Credentials credentials = this.locator.getCredentials(2); } } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientWatchTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientWatchTests.java index f37878c4..93472330 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientWatchTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientWatchTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,28 +12,27 @@ * WITHOUT 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.springframework.cloud.config.client; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Spencer Gibb */ public class ConfigClientWatchTests { - @Test - public void stateChangedWorks() { - ConfigClientWatch watch = new ConfigClientWatch(null); - assertThat(watch.stateChanged(null, "1"), is(true)); - assertThat(watch.stateChanged("1", "2"), is(true)); - assertThat(watch.stateChanged("1", null), is(true)); - assertThat(watch.stateChanged("1", "1"), is(false)); - watch.close(); - } + @Test + public void stateChangedWorks() { + ConfigClientWatch watch = new ConfigClientWatch(null); + assertThat(watch.stateChanged(null, "1")).isTrue(); + assertThat(watch.stateChanged("1", "2")).isTrue(); + assertThat(watch.stateChanged("1", null)).isTrue(); + assertThat(watch.stateChanged("1", "1")).isFalse(); + watch.close(); + } + } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerBootstrapConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerBootstrapConfigurationTests.java index 8923a845..c04131ba 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerBootstrapConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerBootstrapConfigurationTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.client; import org.junit.Test; @@ -8,19 +24,21 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration; import org.springframework.context.ConfigurableApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class ConfigServerBootstrapConfigurationTests { @Test public void withHealthIndicator() { ConfigurableApplicationContext context = new SpringApplicationBuilder( - PropertySourceBootstrapConfiguration.class, ConfigServiceBootstrapConfiguration.class) - .child(ConfigClientAutoConfiguration.class).web(WebApplicationType.NONE).run(); - assertEquals(1, BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, - ConfigClientProperties.class).length); - assertEquals(1, BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, - ConfigServerHealthIndicator.class).length); + PropertySourceBootstrapConfiguration.class, + ConfigServiceBootstrapConfiguration.class) + .child(ConfigClientAutoConfiguration.class) + .web(WebApplicationType.NONE).run(); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, + ConfigClientProperties.class).length).isEqualTo(1); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, + ConfigServerHealthIndicator.class).length).isEqualTo(1); context.close(); } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerHealthIndicatorTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerHealthIndicatorTests.java index 3593e3fd..171e58f9 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerHealthIndicatorTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,16 @@ package org.springframework.cloud.config.client; -import static org.junit.Assert.assertEquals; +import java.util.Collections; + +import org.junit.Test; + +import org.springframework.boot.actuate.health.Status; +import org.springframework.core.env.Environment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; + +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; @@ -24,14 +33,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import java.util.Collections; - -import org.junit.Test; -import org.springframework.boot.actuate.health.Status; -import org.springframework.core.env.Environment; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.PropertySource; - /** * @author Dave Syer * @author Marcos Barbero @@ -39,46 +40,50 @@ import org.springframework.core.env.PropertySource; */ public class ConfigServerHealthIndicatorTests { - private ConfigServicePropertySourceLocator locator = - mock(ConfigServicePropertySourceLocator.class); + private ConfigServicePropertySourceLocator locator = mock( + ConfigServicePropertySourceLocator.class); + private Environment environment = mock(Environment.class); + private ConfigServerHealthIndicator indicator = new ConfigServerHealthIndicator( - locator, environment, new ConfigClientHealthProperties()); + this.locator, this.environment, new ConfigClientHealthProperties()); @Test public void testDefaultStatus() { // UNKNOWN is better than DOWN since it doesn't stop the app from working - assertEquals(Status.UNKNOWN, indicator.health().getStatus()); + assertThat(this.indicator.health().getStatus()).isEqualTo(Status.UNKNOWN); } @Test public void testExceptionStatus() { - doThrow(new IllegalStateException()).when(locator).locate(any(Environment.class)); - assertEquals(Status.DOWN, indicator.health().getStatus()); - verify(locator, times(1)).locate(any(Environment.class)); + doThrow(new IllegalStateException()).when(this.locator) + .locate(any(Environment.class)); + assertThat(this.indicator.health().getStatus()).isEqualTo(Status.DOWN); + verify(this.locator, times(1)).locate(any(Environment.class)); } @Test public void testServerUp() { - PropertySource source = new MapPropertySource("foo", Collections.emptyMap()); - doReturn(source).when(locator).locate(any(Environment.class)); - assertEquals(Status.UP, indicator.health().getStatus()); - verify(locator, times(1)).locate(any(Environment.class)); + PropertySource source = new MapPropertySource("foo", + Collections.emptyMap()); + doReturn(source).when(this.locator).locate(any(Environment.class)); + assertThat(this.indicator.health().getStatus()).isEqualTo(Status.UP); + verify(this.locator, times(1)).locate(any(Environment.class)); } @Test public void healthIsCached() { - PropertySource source = new MapPropertySource("foo", Collections.emptyMap()); - doReturn(source).when(locator).locate(any(Environment.class)); + PropertySource source = new MapPropertySource("foo", + Collections.emptyMap()); + doReturn(source).when(this.locator).locate(any(Environment.class)); // not cached - assertEquals(Status.UP, indicator.health().getStatus()); + assertThat(this.indicator.health().getStatus()).isEqualTo(Status.UP); // cached - assertEquals(Status.UP, indicator.health().getStatus()); + assertThat(this.indicator.health().getStatus()).isEqualTo(Status.UP); - verify(locator, times(1)).locate(any(Environment.class)); + verify(this.locator, times(1)).locate(any(Environment.class)); } - } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfigurationTest.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfigurationTest.java index 45e29e0a..aff530a8 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfigurationTest.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,12 @@ package org.springframework.cloud.config.client; +import java.lang.reflect.Field; + import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -28,8 +31,6 @@ import org.springframework.core.env.Environment; import org.springframework.util.ReflectionUtils; import org.springframework.web.client.RestTemplate; -import java.lang.reflect.Field; - import static org.assertj.core.api.Assertions.assertThat; /** @@ -38,50 +39,54 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ConfigServiceBootstrapConfigurationTest { - private AnnotationConfigApplicationContext context; + private AnnotationConfigApplicationContext context; - @Before - public void setUp() throws Exception { - this.context = new AnnotationConfigApplicationContext(); - } + @Before + public void setUp() throws Exception { + this.context = new AnnotationConfigApplicationContext(); + } - @After - public void tearDown() throws Exception { - if (this.context != null) { - this.context.close(); - } - } + @After + public void tearDown() throws Exception { + if (this.context != null) { + this.context.close(); + } + } - @Test - public void overrideConfigServicePropertySourceLocatorWhenBeanIsProvided() { - TestPropertyValues.of("spring.cloud.config.enabled=true").applyTo(this.context); - this.context.register(ConfigServicePropertySourceLocatorOverrideConfig.class); - this.context.register(ConfigServiceBootstrapConfiguration.class); - this.context.refresh(); + @Test + public void overrideConfigServicePropertySourceLocatorWhenBeanIsProvided() { + TestPropertyValues.of("spring.cloud.config.enabled=true").applyTo(this.context); + this.context.register(ConfigServicePropertySourceLocatorOverrideConfig.class); + this.context.register(ConfigServiceBootstrapConfiguration.class); + this.context.refresh(); - ConfigServicePropertySourceLocator locator = this.context.getBean(ConfigServicePropertySourceLocator.class); + ConfigServicePropertySourceLocator locator = this.context + .getBean(ConfigServicePropertySourceLocator.class); - Field restTemplateField = ReflectionUtils.findField(ConfigServicePropertySourceLocator.class, "restTemplate"); - restTemplateField.setAccessible(true); + Field restTemplateField = ReflectionUtils + .findField(ConfigServicePropertySourceLocator.class, "restTemplate"); + restTemplateField.setAccessible(true); - RestTemplate restTemplate = (RestTemplate) ReflectionUtils.getField(restTemplateField, locator); + RestTemplate restTemplate = (RestTemplate) ReflectionUtils + .getField(restTemplateField, locator); - assertThat(restTemplate).isNotNull(); - } + assertThat(restTemplate).isNotNull(); + } - @Configuration - protected static class ConfigServicePropertySourceLocatorOverrideConfig { + @Configuration + protected static class ConfigServicePropertySourceLocatorOverrideConfig { - @Autowired - private Environment environment; + @Autowired + private Environment environment; - @Bean - public ConfigServicePropertySourceLocator locator() { - ConfigServicePropertySourceLocator locator = new ConfigServicePropertySourceLocator(new ConfigClientProperties(environment)); - locator.setRestTemplate(new RestTemplate()); - return locator; - } + @Bean + public ConfigServicePropertySourceLocator locator() { + ConfigServicePropertySourceLocator locator = new ConfigServicePropertySourceLocator( + new ConfigClientProperties(this.environment)); + locator.setRestTemplate(new RestTemplate()); + return locator; + } - } + } -} \ No newline at end of file +} diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocatorTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocatorTests.java index f24cc872..746a17fd 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocatorTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocatorTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.client; import java.io.ByteArrayInputStream; @@ -34,9 +50,6 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.springframework.cloud.config.client.ConfigClientProperties.AUTHORIZATION; public class ConfigServicePropertySourceLocatorTests { @@ -56,7 +69,7 @@ public class ConfigServicePropertySourceLocatorTests { Environment body = new Environment("app", "master"); mockRequestResponseWithoutLabel(new ResponseEntity<>(body, HttpStatus.OK)); this.locator.setRestTemplate(this.restTemplate); - assertNotNull(this.locator.locate(this.environment)); + assertThat(this.locator.locate(this.environment)).isNotNull(); } @Test @@ -66,7 +79,7 @@ public class ConfigServicePropertySourceLocatorTests { this.locator.setRestTemplate(this.restTemplate); TestPropertyValues.of("spring.cloud.config.label:v1.0.0") .applyTo(this.environment); - assertNotNull(this.locator.locate(this.environment)); + assertThat(this.locator.locate(this.environment)).isNotNull(); } @Test @@ -77,7 +90,7 @@ public class ConfigServicePropertySourceLocatorTests { this.locator.setRestTemplate(this.restTemplate); TestPropertyValues.of("spring.cloud.config.label:release/v1.0.0") .applyTo(this.environment); - assertNotNull(this.locator.locate(this.environment)); + assertThat(this.locator.locate(this.environment)).isNotNull(); } @Test @@ -86,7 +99,7 @@ public class ConfigServicePropertySourceLocatorTests { new ResponseEntity((Void) null, HttpStatus.NOT_FOUND), "nosuchlabel"); this.locator.setRestTemplate(this.restTemplate); - assertNull(this.locator.locate(this.environment)); + assertThat(this.locator.locate(this.environment)).isNull(); } @Test @@ -94,7 +107,7 @@ public class ConfigServicePropertySourceLocatorTests { mockRequestResponseWithoutLabel( new ResponseEntity<>("Wah!", HttpStatus.INTERNAL_SERVER_ERROR)); this.locator.setRestTemplate(this.restTemplate); - assertNull(this.locator.locate(this.environment)); + assertThat(this.locator.locate(this.environment)).isNull(); } @Test @@ -247,8 +260,8 @@ public class ConfigServicePropertySourceLocatorTests { while (iterator.hasNext()) { GenericRequestHeaderInterceptor genericRequestHeaderInterceptor = (GenericRequestHeaderInterceptor) iterator .next(); - assertEquals(null, - genericRequestHeaderInterceptor.getHeaders().get(AUTHORIZATION)); + assertThat(genericRequestHeaderInterceptor.getHeaders().get(AUTHORIZATION)) + .isEqualTo(null); } } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTests.java index 578dc210..5626d152 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.client; import org.junit.Test; @@ -48,4 +64,4 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTest verifyDiscoveryClientCalledOnce(); } -} \ No newline at end of file +} diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationTests.java index 1a9e3491..233fc31d 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.springframework.cloud.client.discovery.event.HeartbeatEvent; import org.springframework.cloud.config.client.ConfigClientProperties.Credentials; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -38,9 +38,11 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests this.context = new AnnotationConfigApplicationContext( DiscoveryClientConfigServiceBootstrapConfiguration.class); - assertEquals(0, this.context.getBeanNamesForType(DiscoveryClient.class).length); - assertEquals(0, this.context.getBeanNamesForType( - DiscoveryClientConfigServiceBootstrapConfiguration.class).length); + assertThat(this.context.getBeanNamesForType(DiscoveryClient.class).length) + .isEqualTo(0); + assertThat(this.context.getBeanNamesForType( + DiscoveryClientConfigServiceBootstrapConfiguration.class).length) + .isEqualTo(0); } @Test @@ -63,7 +65,7 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests givenDiscoveryClientReturnsInfo(); verifyDiscoveryClientCalledOnce(); - context.publishEvent(new HeartbeatEvent(context, "new")); + this.context.publishEvent(new HeartbeatEvent(this.context, "new")); expectConfigClientPropertiesHasConfigurationFromEureka(); } @@ -109,9 +111,9 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests ConfigClientProperties locator = this.context .getBean(ConfigClientProperties.class); Credentials credentials = locator.getCredentials(0); - assertEquals("http://foo:8877/", credentials.getUri()); - assertEquals("bar", credentials.getPassword()); - assertEquals("user", credentials.getUsername()); + assertThat(credentials.getUri()).isEqualTo("http://foo:8877/"); + assertThat(credentials.getPassword()).isEqualTo("bar"); + assertThat(credentials.getUsername()).isEqualTo("user"); } @Test @@ -148,7 +150,7 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup(); verifyDiscoveryClientCalledThreeTimes(); - context.publishEvent(new HeartbeatEvent(context, "new")); + this.context.publishEvent(new HeartbeatEvent(this.context, "new")); expectConfigClientPropertiesHasConfigurationFromEureka(); } diff --git a/spring-cloud-config-dependencies/pom.xml b/spring-cloud-config-dependencies/pom.xml index c36c1788..8992323b 100644 --- a/spring-cloud-config-dependencies/pom.xml +++ b/spring-cloud-config-dependencies/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 @@ -19,56 +20,56 @@ - - org.springframework.cloud - spring-cloud-starter-config - ${project.version} - - - org.springframework.cloud - spring-cloud-config-client - ${project.version} - - - org.springframework.cloud - spring-cloud-config-server - ${project.version} - - - org.springframework.cloud - spring-cloud-config-monitor - ${project.version} - - - org.springframework.credhub - spring-credhub-core - ${spring-credhub.version} - - - org.eclipse.jgit - org.eclipse.jgit - ${jgit.version} - - - org.eclipse.jgit - org.eclipse.jgit.junit.http - ${jgit.version} - - - org.eclipse.jgit - org.eclipse.jgit.http.apache - ${jgit.version} - - - com.jcraft - jsch - 0.1.54 - - - org.tmatesoft.svnkit - svnkit - 1.8.12 - + + org.springframework.cloud + spring-cloud-starter-config + ${project.version} + + + org.springframework.cloud + spring-cloud-config-client + ${project.version} + + + org.springframework.cloud + spring-cloud-config-server + ${project.version} + + + org.springframework.cloud + spring-cloud-config-monitor + ${project.version} + + + org.springframework.credhub + spring-credhub-core + ${spring-credhub.version} + + + org.eclipse.jgit + org.eclipse.jgit + ${jgit.version} + + + org.eclipse.jgit + org.eclipse.jgit.junit.http + ${jgit.version} + + + org.eclipse.jgit + org.eclipse.jgit.http.apache + ${jgit.version} + + + com.jcraft + jsch + 0.1.54 + + + org.tmatesoft.svnkit + svnkit + 1.8.12 + diff --git a/spring-cloud-config-monitor/pom.xml b/spring-cloud-config-monitor/pom.xml index 06f17eac..6175eb3b 100644 --- a/spring-cloud-config-monitor/pom.xml +++ b/spring-cloud-config-monitor/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 org.springframework.cloud diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BasePropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BasePropertyPathNotificationExtractor.java index 71185674..357dcb6f 100755 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BasePropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BasePropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,41 +28,43 @@ import org.springframework.util.MultiValueMap; * */ public abstract class BasePropertyPathNotificationExtractor - implements PropertyPathNotificationExtractor { + implements PropertyPathNotificationExtractor { - @Override - public PropertyPathNotification extract(MultiValueMap headers, - Map request) { - if (requestBelongsToGitRepoManager(headers)) { - if (request.get("commits") instanceof Collection) { - Set paths = new HashSet<>(); - @SuppressWarnings("unchecked") - Collection> commits = (Collection>) request - .get("commits"); - addPaths( paths, commits ); - if (!paths.isEmpty()) { - return new PropertyPathNotification(paths.toArray(new String[0])); - } - } - } - return null; - } + @Override + public PropertyPathNotification extract(MultiValueMap headers, + Map request) { + if (requestBelongsToGitRepoManager(headers)) { + if (request.get("commits") instanceof Collection) { + Set paths = new HashSet<>(); + @SuppressWarnings("unchecked") + Collection> commits = (Collection>) request + .get("commits"); + addPaths(paths, commits); + if (!paths.isEmpty()) { + return new PropertyPathNotification(paths.toArray(new String[0])); + } + } + } + return null; + } - protected void addPaths(Set< String > paths, Collection< Map< String, Object > > commits) { - for (Map commit : commits) { - addAllPaths(paths, commit, "added"); - addAllPaths(paths, commit, "removed"); - addAllPaths(paths, commit, "modified"); - } - } + protected void addPaths(Set paths, Collection> commits) { + for (Map commit : commits) { + addAllPaths(paths, commit, "added"); + addAllPaths(paths, commit, "removed"); + addAllPaths(paths, commit, "modified"); + } + } + + private void addAllPaths(Set paths, Map commit, String name) { + @SuppressWarnings("unchecked") + Collection files = (Collection) commit.get(name); + if (files != null) { + paths.addAll(files); + } + } + + protected abstract boolean requestBelongsToGitRepoManager( + MultiValueMap headers); - private void addAllPaths(Set paths, Map commit, String name) { - @SuppressWarnings("unchecked") - Collection files = (Collection) commit.get(name); - if (files != null) { - paths.addAll(files); - } - } - - protected abstract boolean requestBelongsToGitRepoManager(MultiValueMap headers); } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractor.java index 1da0077c..7741f21e 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,21 +37,22 @@ public class BitbucketPropertyPathNotificationExtractor @Override public PropertyPathNotification extract(MultiValueMap headers, Map request) { - if (("repo:push".equals(headers.getFirst("X-Event-Key")) || - "pullrequest:fulfilled".equals(headers.getFirst("X-Event-Key"))) && - StringUtils.hasText(headers.getFirst("X-Hook-UUID"))) { + if (("repo:push".equals(headers.getFirst("X-Event-Key")) + || "pullrequest:fulfilled".equals(headers.getFirst("X-Event-Key"))) + && StringUtils.hasText(headers.getFirst("X-Hook-UUID"))) { // Bitbucket cloud Object push = request.get("push"); - if (push instanceof Map && ((Map)push).get("changes") instanceof Collection) { + if (push instanceof Map + && ((Map) push).get("changes") instanceof Collection) { // Bitbucket doesn't tell us the files that changed so this is a // broadcast to all apps return new PropertyPathNotification("application.yml"); } } - else if ( ("repo:refs_changed".equals(headers.getFirst("X-Event-Key")) || - "pr:merged".equals(headers.getFirst("X-Event-Key"))) && - StringUtils.hasText(headers.getFirst("X-Request-Id"))) { - //Bitbucket server + else if (("repo:refs_changed".equals(headers.getFirst("X-Event-Key")) + || "pr:merged".equals(headers.getFirst("X-Event-Key"))) + && StringUtils.hasText(headers.getFirst("X-Request-Id"))) { + // Bitbucket server if (request.get("changes") instanceof Collection) { // Bitbucket doesn't tell us the files that changed so this is a // broadcast to all apps diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractor.java index 4d244ddd..44d221d3 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ import org.springframework.core.annotation.Order; import org.springframework.util.MultiValueMap; /** - * A {@link PropertyPathNotificationExtractor} that cycles through a set of (ordered) delegates, - * looking for the first non-null outcome. + * A {@link PropertyPathNotificationExtractor} that cycles through a set of (ordered) + * delegates, looking for the first non-null outcome. * * @author Dave Syer * diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfiguration.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfiguration.java index 3ec297ab..a87b6edd 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfiguration.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,52 +36,55 @@ import org.springframework.context.annotation.Import; @Import(FileMonitorConfiguration.class) public class EnvironmentMonitorAutoConfiguration { - @Autowired(required=false) + @Autowired(required = false) private List extractors; @Bean public PropertyPathEndpoint propertyPathEndpoint(BusProperties busProperties) { - return new PropertyPathEndpoint(new CompositePropertyPathNotificationExtractor(this.extractors), busProperties.getId()); + return new PropertyPathEndpoint( + new CompositePropertyPathNotificationExtractor(this.extractors), + busProperties.getId()); } @Configuration protected static class PropertyPathNotificationExtractorConfiguration { @Bean - @ConditionalOnProperty(value="spring.cloud.config.server.monitor.github.enabled", havingValue="true", matchIfMissing=true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.github.enabled", havingValue = "true", matchIfMissing = true) public GithubPropertyPathNotificationExtractor githubPropertyPathNotificationExtractor() { return new GithubPropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value="spring.cloud.config.server.monitor.gitlab.enabled", havingValue="true", matchIfMissing=true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitlab.enabled", havingValue = "true", matchIfMissing = true) public GitlabPropertyPathNotificationExtractor gitlabPropertyPathNotificationExtractor() { return new GitlabPropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value="spring.cloud.config.server.monitor.bitbucket.enabled", havingValue="true", matchIfMissing=true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.bitbucket.enabled", havingValue = "true", matchIfMissing = true) public BitbucketPropertyPathNotificationExtractor bitbucketPropertyPathNotificationExtractor() { return new BitbucketPropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value="spring.cloud.config.server.monitor.gitea.enabled", havingValue="true", matchIfMissing=true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitea.enabled", havingValue = "true", matchIfMissing = true) public GiteaPropertyPathNotificationExtractor giteaPropertyPathNotificationExtractor() { return new GiteaPropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value="spring.cloud.config.server.monitor.gitee.enabled", havingValue="true", matchIfMissing=true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitee.enabled", havingValue = "true", matchIfMissing = true) public GiteePropertyPathNotificationExtractor giteePropertyPathNotificationExtractor() { return new GiteePropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value="spring.cloud.config.server.monitor.gogs.enabled", havingValue="true", matchIfMissing=true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gogs.enabled", havingValue = "true", matchIfMissing = true) public GogsPropertyPathNotificationExtractor gogsPropertyPathNotificationExtractor() { return new GogsPropertyPathNotificationExtractor(); } + } } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/FileMonitorConfiguration.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/FileMonitorConfiguration.java index 9646a85a..fe09af19 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/FileMonitorConfiguration.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/FileMonitorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.config.server.environment.AbstractScmEnvironmentRepository; import org.springframework.cloud.config.server.environment.NativeEnvironmentRepository; @@ -98,7 +99,7 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA } /** - * see {@link #getPhase()} + * see {@link #getPhase()}. * @param phase the phase. */ public void setPhase(int phase) { @@ -111,8 +112,8 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA } /** - * @see #isRunning() * @param running true if running. + * @see #isRunning() */ public void setRunning(boolean running) { this.running = running; @@ -124,8 +125,8 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA } /** - * @see #isAutoStartup() * @param autoStartup true to auto start. + * @see #isAutoStartup() */ public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; @@ -187,7 +188,8 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA if (this.scmRepository != null) { try { - Resource resource = this.resourceLoader.getResource(this.scmRepository.getUri()); + Resource resource = this.resourceLoader + .getResource(this.scmRepository.getUri()); if (resource instanceof FileSystemResource) { return Collections.singleton(Paths.get(resource.getURI())); } @@ -306,11 +308,13 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA log.debug("registering: " + dir + " for file creation events"); } try { - dir.register(this.watcher, StandardWatchEventKinds.ENTRY_CREATE, - StandardWatchEventKinds.ENTRY_MODIFY); - } catch (IOException e) { + dir.register(this.watcher, StandardWatchEventKinds.ENTRY_CREATE, + StandardWatchEventKinds.ENTRY_MODIFY); + } + catch (IOException e) { throw e; - } catch (Exception e) { + } + catch (Exception e) { throw new IOException("Cannot register watcher for " + dir, e); } } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GiteaPropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GiteaPropertyPathNotificationExtractor.java index a75b68c4..d63f8613 100755 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GiteaPropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GiteaPropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,24 +30,26 @@ import org.springframework.util.MultiValueMap; */ @Order(Ordered.LOWEST_PRECEDENCE - 100) public class GiteaPropertyPathNotificationExtractor - extends BasePropertyPathNotificationExtractor { + extends BasePropertyPathNotificationExtractor { - private static final String HEADERS_KEY = "X-Gitea-Event"; + private static final String HEADERS_KEY = "X-Gitea-Event"; - private static final String HEADERS_VALUE = "push"; - - /** - * gitea doesn't return which files have been added/modified/deleted yet. - * - * @see https://github.com/go-gitea/gitea/issues/4313 - */ - @Override - protected void addPaths(Set paths, Collection> commits) { - paths.add( "application.yml" ); - } + private static final String HEADERS_VALUE = "push"; + + /** + * gitea doesn't return which files have been added/modified/deleted yet. + * + * related issue: https://github.com/go-gitea/gitea/issues/4313 + */ + @Override + protected void addPaths(Set paths, Collection> commits) { + paths.add("application.yml"); + } + + @Override + protected boolean requestBelongsToGitRepoManager( + MultiValueMap headers) { + return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY)); + } - @Override - protected boolean requestBelongsToGitRepoManager(MultiValueMap headers) { - return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY)); - } } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GiteePropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GiteePropertyPathNotificationExtractor.java index d9e70441..c0da8921 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GiteePropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GiteePropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import org.springframework.core.annotation.Order; import org.springframework.util.MultiValueMap; /** - * @author lly835 + * @author lly 835 * */ @Order(Ordered.LOWEST_PRECEDENCE - 100) @@ -33,7 +33,9 @@ public class GiteePropertyPathNotificationExtractor private static final String HEADERS_VALUE = "Push Hook"; @Override - protected boolean requestBelongsToGitRepoManager(MultiValueMap headers) { - return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY)); - } + protected boolean requestBelongsToGitRepoManager( + MultiValueMap headers) { + return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY)); + } + } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GithubPropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GithubPropertyPathNotificationExtractor.java index 5f060977..173c6713 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GithubPropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GithubPropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,12 @@ import org.springframework.util.MultiValueMap; */ @Order(Ordered.LOWEST_PRECEDENCE - 300) public class GithubPropertyPathNotificationExtractor - extends BasePropertyPathNotificationExtractor { + extends BasePropertyPathNotificationExtractor { + + @Override + protected boolean requestBelongsToGitRepoManager( + MultiValueMap headers) { + return "push".equals(headers.getFirst("X-Github-Event")); + } - @Override - protected boolean requestBelongsToGitRepoManager(MultiValueMap headers) { - return "push".equals(headers.getFirst("X-Github-Event")); - } } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GitlabPropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GitlabPropertyPathNotificationExtractor.java index d68edf90..3365b4a1 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GitlabPropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GitlabPropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,12 @@ import org.springframework.util.MultiValueMap; */ @Order(Ordered.LOWEST_PRECEDENCE - 100) public class GitlabPropertyPathNotificationExtractor - extends BasePropertyPathNotificationExtractor { + extends BasePropertyPathNotificationExtractor { + + @Override + protected boolean requestBelongsToGitRepoManager( + MultiValueMap headers) { + return "Push Hook".equals(headers.getFirst("X-Gitlab-Event")); + } - @Override - protected boolean requestBelongsToGitRepoManager(MultiValueMap headers) { - return "Push Hook".equals(headers.getFirst("X-Gitlab-Event")); - } } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GogsPropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GogsPropertyPathNotificationExtractor.java index 97d6a952..e691b258 100755 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GogsPropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/GogsPropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,19 +21,21 @@ import org.springframework.core.annotation.Order; import org.springframework.util.MultiValueMap; /** - * @author lly835 + * @author lly 835 * */ @Order(Ordered.LOWEST_PRECEDENCE - 100) public class GogsPropertyPathNotificationExtractor - extends BasePropertyPathNotificationExtractor { + extends BasePropertyPathNotificationExtractor { - private static final String HEADERS_KEY = "X-Gogs-Event"; + private static final String HEADERS_KEY = "X-Gogs-Event"; - private static final String HEADERS_VALUE = "push"; + private static final String HEADERS_VALUE = "push"; + + @Override + protected boolean requestBelongsToGitRepoManager( + MultiValueMap headers) { + return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY)); + } - @Override - protected boolean requestBelongsToGitRepoManager(MultiValueMap headers) { - return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY)); - } } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java index 661b37bc..d72eea19 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.bus.event.RefreshRemoteApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; @@ -46,22 +47,24 @@ import org.springframework.web.bind.annotation.RestController; */ @RestController @RequestMapping(path = "${spring.cloud.config.monitor.endpoint.path:}/monitor") -public class PropertyPathEndpoint - implements ApplicationEventPublisherAware { +public class PropertyPathEndpoint implements ApplicationEventPublisherAware { private static Log log = LogFactory.getLog(PropertyPathEndpoint.class); private final PropertyPathNotificationExtractor extractor; + private ApplicationEventPublisher applicationEventPublisher; + private String busId; - public PropertyPathEndpoint(PropertyPathNotificationExtractor extractor, String busId) { + public PropertyPathEndpoint(PropertyPathNotificationExtractor extractor, + String busId) { this.extractor = extractor; this.busId = busId; } /* for testing */ String getBusId() { - return busId; + return this.busId; } @Override @@ -84,9 +87,8 @@ public class PropertyPathEndpoint if (this.applicationEventPublisher != null) { for (String service : services) { log.info("Refresh for: " + service); - this.applicationEventPublisher - .publishEvent(new RefreshRemoteApplicationEvent(this, - this.busId, service)); + this.applicationEventPublisher.publishEvent( + new RefreshRemoteApplicationEvent(this, this.busId, service)); } return services; } @@ -107,8 +109,8 @@ public class PropertyPathEndpoint private Set guessServiceName(String path) { Set services = new LinkedHashSet<>(); if (path != null) { - String stem = StringUtils - .stripFilenameExtension(StringUtils.getFilename(StringUtils.cleanPath(path))); + String stem = StringUtils.stripFilenameExtension( + StringUtils.getFilename(StringUtils.cleanPath(path))); // TODO: correlate with service registry int index = stem.indexOf("-"); while (index >= 0) { diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathNotification.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathNotification.java index caf71288..61794b55 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathNotification.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathNotification.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,12 +24,12 @@ package org.springframework.cloud.config.monitor; */ public class PropertyPathNotification { + private String[] paths; + public PropertyPathNotification(String... paths) { this.paths = paths; } - private String[] paths; - public PropertyPathNotification() { } @@ -42,15 +42,19 @@ public class PropertyPathNotification { } public boolean equals(Object o) { - if (o == this) + if (o == this) { return true; - if (!(o instanceof PropertyPathNotification)) + } + if (!(o instanceof PropertyPathNotification)) { return false; + } final PropertyPathNotification other = (PropertyPathNotification) o; - if (!other.canEqual(this)) + if (!other.canEqual(this)) { return false; - if (!java.util.Arrays.deepEquals(this.getPaths(), other.getPaths())) + } + if (!java.util.Arrays.deepEquals(this.getPaths(), other.getPaths())) { return false; + } return true; } @@ -66,7 +70,8 @@ public class PropertyPathNotification { } public String toString() { - return "PropertyPathNotification(paths=" + java.util.Arrays - .deepToString(this.getPaths()) + ")"; + return "PropertyPathNotification(paths=" + + java.util.Arrays.deepToString(this.getPaths()) + ")"; } + } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathNotificationExtractor.java index 0fc03bd9..4eaf0154 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathNotificationExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-monitor/src/main/resources/META-INF/spring.factories b/spring-cloud-config-monitor/src/main/resources/META-INF/spring.factories index 62436d49..66f23537 100644 --- a/spring-cloud-config-monitor/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-config-monitor/src/main/resources/META-INF/spring.factories @@ -1,3 +1,3 @@ # Autoconfiguration org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -org.springframework.cloud.config.monitor.EnvironmentMonitorAutoConfiguration \ No newline at end of file +org.springframework.cloud.config.monitor.EnvironmentMonitorAutoConfiguration diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractorTests.java index f2ddfb8f..67c6017c 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,18 @@ package org.springframework.cloud.config.monitor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - import java.util.Map; import java.util.UUID; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; + import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb @@ -44,8 +42,8 @@ public class BitbucketPropertyPathNotificationExtractorTests { private HttpHeaders headers; @Before - public void setup(){ - headers = new HttpHeaders(); + public void setup() { + this.headers = new HttpHeaders(); } @Test @@ -54,18 +52,18 @@ public class BitbucketPropertyPathNotificationExtractorTests { Map value = readPayload("pathsamples/bitbucket.json"); setHeaders("repo:push"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("application.yml", extracted.getPaths()[0]); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("application.yml"); } - - @Test + + @Test public void bitbucketPullRequestFulfillmentDetected() throws Exception { // https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html#EventPayloads-Merged Map value = readPayload("pathsamples/bitbucket.json"); setHeaders("pullrequest:fulfilled"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("application.yml", extracted.getPaths()[0]); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("application.yml"); } private void setHeaders(String eventKey) { @@ -87,50 +85,51 @@ public class BitbucketPropertyPathNotificationExtractorTests { public void githubNotDetected() throws Exception { assertNotExtracted("pathsamples/github.json", "repo:push"); } - + @Test public void missingUuidHeader() throws Exception { // https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html#EventPayloads-Push Map value = readPayload("pathsamples/bitbucket.json"); this.headers.set("X-Event-Key", "repo:push"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } - + @Test public void missingChanges() throws Exception { // https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html#EventPayloads-Push Map value = readPayload("pathsamples/bitbucket-invalid.json"); setHeaders("repo:push"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } - private void assertNotExtracted(String path, String eventKey) throws java.io.IOException { + private void assertNotExtracted(String path, String eventKey) + throws java.io.IOException { Map value = readPayload(path); setHeaders(eventKey); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } - + @Test public void bitbucketServerSample() throws Exception { // https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html Map value = readPayload("pathsamples/bitbucketserver.json"); setServerHeaders("repo:refs_changed"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("application.yml", extracted.getPaths()[0]); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("application.yml"); } - - @Test + + @Test public void bitbucketServerSamplePullRequest() throws Exception { // https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html Map value = readPayload("pathsamples/bitbucketserver.json"); setServerHeaders("pr:merged"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("application.yml", extracted.getPaths()[0]); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("application.yml"); } private void setServerHeaders(String eventKey) { @@ -140,39 +139,41 @@ public class BitbucketPropertyPathNotificationExtractorTests { @Test public void notAPushOrPullRequestServer() throws Exception { - assertNotExtractedServer("pathsamples/bitbucketserver.json", "repo:comment:added"); + assertNotExtractedServer("pathsamples/bitbucketserver.json", + "repo:comment:added"); } - + @Test public void missingUuidHeaderServer() throws Exception { // https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html Map value = readPayload("pathsamples/bitbucketserver.json"); this.headers.set("X-Event-Key", "repo:refs_changed"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } - + @Test public void missingChangesServer() throws Exception { // https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html - Map value = readPayload("pathsamples/bitbucketserver-invalid.json"); + Map value = readPayload( + "pathsamples/bitbucketserver-invalid.json"); setServerHeaders("repo:refs_changed"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } - - private void assertNotExtractedServer(String path, String eventKey) throws java.io.IOException { + + private void assertNotExtractedServer(String path, String eventKey) + throws java.io.IOException { Map value = readPayload(path); setServerHeaders(eventKey); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } - + private Map readPayload(String path) throws java.io.IOException { - return new ObjectMapper().readValue( - new ClassPathResource(path).getInputStream(), - new TypeReference>() { - }); + return new ObjectMapper().readValue(new ClassPathResource(path).getInputStream(), + new TypeReference>() { + }); } } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractorTests.java index efbd06c9..0d9be1c6 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,14 @@ import java.util.Arrays; import java.util.Collections; import java.util.Map; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; + import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import static org.hamcrest.Matchers.arrayContainingInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -53,8 +50,8 @@ public class CompositePropertyPathNotificationExtractorTests { }); this.headers.set("X-Github-Event", "push"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("README.md", extracted.getPaths()[0]); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("README.md"); } @Test @@ -65,18 +62,19 @@ public class CompositePropertyPathNotificationExtractorTests { }); this.headers.set("X-Gitlab-Event", "Push Hook"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); + assertThat(extracted).isNotNull(); String[] paths = extracted.getPaths(); - assertThat("paths was wrong", paths, arrayContainingInAnyOrder("oldapp.yml", "newapp.properties", "application.yml")); + assertThat(paths).as("paths was wrong").contains("oldapp.yml", + "newapp.properties", "application.yml"); } @Test public void fallback() throws Exception { - Map value = Collections. singletonMap("path", + Map value = Collections.singletonMap("path", "foo"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("foo", extracted.getPaths()[0]); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("foo"); } } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfigurationTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfigurationTests.java index 9edbcf7b..4207d30d 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfigurationTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -41,33 +41,29 @@ public class EnvironmentMonitorAutoConfigurationTests { @Test public void testExtractorsCount() { ConfigurableApplicationContext context = new SpringApplicationBuilder( - BusConfig.class, - EnvironmentMonitorAutoConfiguration.class, + BusConfig.class, EnvironmentMonitorAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class, PropertyPlaceholderAutoConfiguration.class).properties("server.port=-1") .run(); PropertyPathEndpoint endpoint = context.getBean(PropertyPathEndpoint.class); - assertEquals(7, - ((Collection) ReflectionTestUtils.getField( - ReflectionTestUtils.getField(endpoint, "extractor"), - "extractors")).size()); + assertThat(((Collection) ReflectionTestUtils.getField( + ReflectionTestUtils.getField(endpoint, "extractor"), "extractors")) + .size()).isEqualTo(7); context.close(); } @Test public void testCanAddCustomPropertyPathNotificationExtractor() { ConfigurableApplicationContext context = new SpringApplicationBuilder( - BusConfig.class, - CustomPropertyPathNotificationExtractorConfig.class, + BusConfig.class, CustomPropertyPathNotificationExtractorConfig.class, EnvironmentMonitorAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class, PropertyPlaceholderAutoConfiguration.class).properties("server.port=-1") .run(); PropertyPathEndpoint endpoint = context.getBean(PropertyPathEndpoint.class); - assertEquals(8, - ((Collection) ReflectionTestUtils.getField( - ReflectionTestUtils.getField(endpoint, "extractor"), - "extractors")).size()); + assertThat(((Collection) ReflectionTestUtils.getField( + ReflectionTestUtils.getField(endpoint, "extractor"), "extractors")) + .size()).isEqualTo(8); context.close(); } @@ -78,16 +74,19 @@ public class EnvironmentMonitorAutoConfigurationTests { public BusProperties busProperties() { return new BusProperties(); } - } + + } @Configuration static class CustomPropertyPathNotificationExtractorConfig { + @Bean public PropertyPathNotificationExtractor customNotificationExtractor() { return (headers, payload) -> { - throw new UnsupportedOperationException("doesn't do anything"); - }; + throw new UnsupportedOperationException("doesn't do anything"); + }; } + } } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GiteaPropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GiteaPropertyPathNotificationExtractorTests.java index e77fd00f..70f15e9f 100755 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GiteaPropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GiteaPropertyPathNotificationExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,16 @@ package org.springframework.cloud.config.monitor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - import java.util.Map; -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; -import org.springframework.http.HttpHeaders; - import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpHeaders; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juan Pablo Santos Rodríguez @@ -35,32 +33,32 @@ import com.fasterxml.jackson.databind.ObjectMapper; */ public class GiteaPropertyPathNotificationExtractorTests { - private GiteaPropertyPathNotificationExtractor extractor = new GiteaPropertyPathNotificationExtractor(); + private GiteaPropertyPathNotificationExtractor extractor = new GiteaPropertyPathNotificationExtractor(); - private HttpHeaders headers = new HttpHeaders(); + private HttpHeaders headers = new HttpHeaders(); - @Test - public void giteaSample() throws Exception { - // See https://docs.gitea.io/en-us/webhooks/ - Map value = new ObjectMapper().readValue( - new ClassPathResource("pathsamples/gitea.json").getInputStream(), - new TypeReference>() { - }); - this.headers.set("X-Gitea-Event", "push"); - PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("application.yml", extracted.getPaths()[0]); - } + @Test + public void giteaSample() throws Exception { + // See https://docs.gitea.io/en-us/webhooks/ + Map value = new ObjectMapper().readValue( + new ClassPathResource("pathsamples/gitea.json").getInputStream(), + new TypeReference>() { + }); + this.headers.set("X-Gitea-Event", "push"); + PropertyPathNotification extracted = this.extractor.extract(this.headers, value); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("application.yml"); + } - @Test - public void notAPushNotDetected() throws Exception { - Map value = new ObjectMapper().readValue( - new ClassPathResource("pathsamples/gitea.json").getInputStream(), - new TypeReference>() { - }); - this.headers.set("X-Gitea-Event", "issues"); - PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); - } + @Test + public void notAPushNotDetected() throws Exception { + Map value = new ObjectMapper().readValue( + new ClassPathResource("pathsamples/gitea.json").getInputStream(), + new TypeReference>() { + }); + this.headers.set("X-Gitea-Event", "issues"); + PropertyPathNotification extracted = this.extractor.extract(this.headers, value); + assertThat(extracted).isNull(); + } } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GiteePropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GiteePropertyPathNotificationExtractorTests.java index 0ad93d40..5b85edc7 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GiteePropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GiteePropertyPathNotificationExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +21,14 @@ import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; + import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; + +import static org.assertj.core.api.Assertions.assertThat; /** - * @author lly835 - * + * @author lly 835 */ public class GiteePropertyPathNotificationExtractorTests { @@ -46,8 +45,8 @@ public class GiteePropertyPathNotificationExtractorTests { }); this.headers.set("x-git-oschina-event", "Push Hook"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("d.txt", extracted.getPaths()[0]); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("d.txt"); } @Test @@ -58,7 +57,7 @@ public class GiteePropertyPathNotificationExtractorTests { }); this.headers.set("x-git-oschina-event", "Issue Hook"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GithubPropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GithubPropertyPathNotificationExtractorTests.java index 36f49de4..47c0a78a 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GithubPropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GithubPropertyPathNotificationExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,16 +18,14 @@ package org.springframework.cloud.config.monitor; import java.util.Map; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; + import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -48,8 +46,8 @@ public class GithubPropertyPathNotificationExtractorTests { }); this.headers.set("X-Github-Event", "push"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("README.md", extracted.getPaths()[0]); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("README.md"); } @Test @@ -60,7 +58,7 @@ public class GithubPropertyPathNotificationExtractorTests { }); this.headers.set("X-Github-Event", "issues"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GitlabPropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GitlabPropertyPathNotificationExtractorTests.java index 752cdc5d..98e54495 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GitlabPropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GitlabPropertyPathNotificationExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,17 +18,14 @@ package org.springframework.cloud.config.monitor; import java.util.Map; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; + import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import static org.hamcrest.Matchers.arrayContainingInAnyOrder; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -49,9 +46,10 @@ public class GitlabPropertyPathNotificationExtractorTests { }); this.headers.set("X-Gitlab-Event", "Push Hook"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); + assertThat(extracted).isNotNull(); String[] paths = extracted.getPaths(); - assertThat("paths was wrong", paths, arrayContainingInAnyOrder("oldapp.yml", "newapp.properties", "application.yml")); + assertThat(paths).as("paths was wrong").contains("oldapp.yml", + "newapp.properties", "application.yml"); } @Test @@ -63,7 +61,7 @@ public class GitlabPropertyPathNotificationExtractorTests { }); this.headers.set("X-Gitlab-Event", "Issue Hook"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); + assertThat(extracted).isNull(); } } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GogsPropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GogsPropertyPathNotificationExtractorTests.java index b5363497..2d6784fd 100755 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GogsPropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/GogsPropertyPathNotificationExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,16 @@ package org.springframework.cloud.config.monitor; -import static org.junit.Assert.*; - import java.util.Map; -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; -import org.springframework.http.HttpHeaders; - import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpHeaders; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Craig Walls @@ -33,32 +33,32 @@ import com.fasterxml.jackson.databind.ObjectMapper; */ public class GogsPropertyPathNotificationExtractorTests { - private GogsPropertyPathNotificationExtractor extractor = new GogsPropertyPathNotificationExtractor(); + private GogsPropertyPathNotificationExtractor extractor = new GogsPropertyPathNotificationExtractor(); - private HttpHeaders headers = new HttpHeaders(); + private HttpHeaders headers = new HttpHeaders(); - @Test - public void gogsSample() throws Exception { - // See https://gogs.io/docs/features/webhook - Map value = new ObjectMapper().readValue( - new ClassPathResource("pathsamples/gogs.json").getInputStream(), - new TypeReference>() { - }); - this.headers.set("X-Gogs-Event", "push"); - PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNotNull(extracted); - assertEquals("README.md", extracted.getPaths()[0]); - } + @Test + public void gogsSample() throws Exception { + // See https://gogs.io/docs/features/webhook + Map value = new ObjectMapper().readValue( + new ClassPathResource("pathsamples/gogs.json").getInputStream(), + new TypeReference>() { + }); + this.headers.set("X-Gogs-Event", "push"); + PropertyPathNotification extracted = this.extractor.extract(this.headers, value); + assertThat(extracted).isNotNull(); + assertThat(extracted.getPaths()[0]).isEqualTo("README.md"); + } - @Test - public void notAPushNotDetected() throws Exception { - Map value = new ObjectMapper().readValue( - new ClassPathResource("pathsamples/gogs.json").getInputStream(), - new TypeReference>() { - }); - this.headers.set("X-Gogs-Event", "issues"); - PropertyPathNotification extracted = this.extractor.extract(this.headers, value); - assertNull(extracted); - } + @Test + public void notAPushNotDetected() throws Exception { + Map value = new ObjectMapper().readValue( + new ClassPathResource("pathsamples/gogs.json").getInputStream(), + new TypeReference>() { + }); + this.headers.set("X-Gogs-Event", "issues"); + PropertyPathNotification extracted = this.extractor.extract(this.headers, value); + assertThat(extracted).isNull(); + } } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java index 7807ba12..1f0d92d3 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,18 @@ package org.springframework.cloud.config.monitor; -import static org.junit.Assert.assertEquals; - import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; + import org.springframework.context.support.StaticApplicationContext; import org.springframework.http.HttpHeaders; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @@ -34,8 +35,8 @@ import org.springframework.http.HttpHeaders; public class PropertyPathEndpointTests { private PropertyPathEndpoint endpoint = new PropertyPathEndpoint( - new CompositePropertyPathNotificationExtractor( - Collections.emptyList()), "abc1"); + new CompositePropertyPathNotificationExtractor(Collections.emptyList()), + "abc1"); @Before public void init() { @@ -44,15 +45,16 @@ public class PropertyPathEndpointTests { publisher.refresh(); } - @Test - public void testBusId() { - assertEquals("abc1", this.endpoint.getBusId()); - } + @Test + public void testBusId() { + assertThat(this.endpoint.getBusId()).isEqualTo("abc1"); + } @Test public void testNotifyByForm() { - assertEquals(0, this.endpoint - .notifyByForm(new HttpHeaders(), new ArrayList<>()).size()); + assertThat( + this.endpoint.notifyByForm(new HttpHeaders(), new ArrayList<>()).size()) + .isEqualTo(0); } @Test @@ -60,62 +62,59 @@ public class PropertyPathEndpointTests { List request = new ArrayList<>(); request.add("/foo/bar.properties"); request.add("/application.properties"); - assertEquals("[bar, *]", - this.endpoint.notifyByForm(new HttpHeaders(), request).toString()); + assertThat(this.endpoint.notifyByForm(new HttpHeaders(), request).toString()) + .isEqualTo("[bar, *]"); } @Test public void testNotifyAll() { - assertEquals("[*]", + assertThat( this.endpoint - .notifyByPath(new HttpHeaders(), Collections - .singletonMap("path", "application.yml")) - .toString()); + .notifyByPath(new HttpHeaders(), + Collections.singletonMap("path", "application.yml")) + .toString()).isEqualTo("[*]"); } @Test public void testNotifyAllWithProfile() { - assertEquals("[*:local]", - this.endpoint - .notifyByPath(new HttpHeaders(), Collections - .singletonMap("path", "application-local.yml")) - .toString()); + assertThat(this.endpoint + .notifyByPath(new HttpHeaders(), + Collections.singletonMap("path", "application-local.yml")) + .toString()).isEqualTo("[*:local]"); } @Test public void testNotifyOne() { - assertEquals("[foo]", - this.endpoint - .notifyByPath(new HttpHeaders(), Collections - .singletonMap("path", "foo.yml")) - .toString()); + assertThat(this.endpoint.notifyByPath(new HttpHeaders(), + Collections.singletonMap("path", "foo.yml")).toString()) + .isEqualTo("[foo]"); } @Test public void testNotifyOneWithWindowsPath() { - assertEquals("[foo]", - this.endpoint - .notifyByPath(new HttpHeaders(), Collections - .singletonMap("path", "C:\\config\\foo.yml")) - .toString()); + assertThat(this.endpoint + .notifyByPath(new HttpHeaders(), + Collections.singletonMap("path", "C:\\config\\foo.yml")) + .toString()).isEqualTo("[foo]"); } @Test public void testNotifyOneWithProfile() { - assertEquals("[foo:local, foo-local]", + assertThat( this.endpoint - .notifyByPath(new HttpHeaders(), Collections - .singletonMap("path", "foo-local.yml")) - .toString()); + .notifyByPath(new HttpHeaders(), + Collections.singletonMap("path", "foo-local.yml")) + .toString()).isEqualTo("[foo:local, foo-local]"); } @Test public void testNotifyMultiDash() { - assertEquals("[foo:local-dev, foo-local:dev, foo-local-dev]", + assertThat( this.endpoint - .notifyByPath(new HttpHeaders(), Collections - .singletonMap("path", "foo-local-dev.yml")) - .toString()); + .notifyByPath(new HttpHeaders(), + Collections.singletonMap("path", "foo-local-dev.yml")) + .toString()).isEqualTo( + "[foo:local-dev, foo-local:dev, foo-local-dev]"); } } diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucket-invalid.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucket-invalid.json index 6ac0c92f..f491557b 100644 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucket-invalid.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucket-invalid.json @@ -1,38 +1,38 @@ { - "actor": { - "username": "emmap1", - "display_name": "Emma", - "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", - "links": { - "self": { - "href": "https://api.bitbucket.org/api/2.0/users/emmap1" - }, - "html": { - "href": "https://api.bitbucket.org/emmap1" - }, - "avatar": { - "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" - } - } - }, - "repository": { - "links": { - "self": { - "href": "https://api.bitbucket.org/api/2.0/repositories/bitbucket/bitbucket" - }, - "html": { - "href": "https://api.bitbucket.org/bitbucket/bitbucket" - }, - "avatar": { - "href": "https://api-staging-assetroot.s3.amazonaws.com/c/photos/2014/Aug/01/bitbucket-logo-2629490769-3_avatar.png" - } - }, - "uuid": "{673a6070-3421-46c9-9d48-90745f7bfe8e}", - "full_name": "team_name/repo_name", - "name": "repo_name", - "scm": "git", - "is_private": true - }, - "push": { - } -} \ No newline at end of file + "actor": { + "username": "emmap1", + "display_name": "Emma", + "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", + "links": { + "self": { + "href": "https://api.bitbucket.org/api/2.0/users/emmap1" + }, + "html": { + "href": "https://api.bitbucket.org/emmap1" + }, + "avatar": { + "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" + } + } + }, + "repository": { + "links": { + "self": { + "href": "https://api.bitbucket.org/api/2.0/repositories/bitbucket/bitbucket" + }, + "html": { + "href": "https://api.bitbucket.org/bitbucket/bitbucket" + }, + "avatar": { + "href": "https://api-staging-assetroot.s3.amazonaws.com/c/photos/2014/Aug/01/bitbucket-logo-2629490769-3_avatar.png" + } + }, + "uuid": "{673a6070-3421-46c9-9d48-90745f7bfe8e}", + "full_name": "team_name/repo_name", + "name": "repo_name", + "scm": "git", + "is_private": true + }, + "push": { + } +} diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucket.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucket.json index 35610d5b..2b8ea0d3 100644 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucket.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucket.json @@ -1,206 +1,206 @@ { - "actor": { - "username": "emmap1", - "display_name": "Emma", - "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", - "links": { - "self": { - "href": "https://api.bitbucket.org/api/2.0/users/emmap1" - }, - "html": { - "href": "https://api.bitbucket.org/emmap1" - }, - "avatar": { - "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" - } - } - }, - "repository": { - "links": { - "self": { - "href": "https://api.bitbucket.org/api/2.0/repositories/bitbucket/bitbucket" - }, - "html": { - "href": "https://api.bitbucket.org/bitbucket/bitbucket" - }, - "avatar": { - "href": "https://api-staging-assetroot.s3.amazonaws.com/c/photos/2014/Aug/01/bitbucket-logo-2629490769-3_avatar.png" - } - }, - "uuid": "{673a6070-3421-46c9-9d48-90745f7bfe8e}", - "full_name": "team_name/repo_name", - "name": "repo_name", - "scm": "git", - "is_private": true - }, - "push": { - "changes": [ - { - "new": { - "type": "branch", - "name": "name-of-branch", - "target": { - "type": "commit", - "hash": "709d658dc5b6d6afcd46049c2f332ee3f515a67d", - "author": { - "username": "emmap1", - "display_name": "Emma", - "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", - "links": { - "self": { - "href": "https://api.bitbucket.org/api/2.0/users/emmap1" - }, - "html": { - "href": "https://api.bitbucket.org/emmap1" - }, - "avatar": { - "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" - } - } - }, - "message": "new commit message\n", - "date": "2015-06-09T03:34:49+00:00", - "parents": [ - { - "type": "commit", - "hash": "1e65c05c1d5171631d92438a13901ca7dae9618c", - "links": { - "self": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commit/8cbbd65829c7ad834a97841e0defc965718036a0" - }, - "html": { - "href": "https://bitbucket.org/user_name/repo_name/commits/8cbbd65829c7ad834a97841e0defc965718036a0" - } - } - } - ], - "links": { - "self": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commit/c4b2b7914156a878aa7c9da452a09fb50c2091f2" - }, - "html": { - "href": "https://bitbucket.org/user_name/repo_name/commits/c4b2b7914156a878aa7c9da452a09fb50c2091f2" - } - } - }, - "links": { - "self": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/refs/branches/master" - }, - "commits": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commits/master" - }, - "html": { - "href": "https://bitbucket.org/user_name/repo_name/branch/master" - } - } - }, - "old": { - "type": "branch", - "name": "name-of-branch", - "target": { - "type": "commit", - "hash": "1e65c05c1d5171631d92438a13901ca7dae9618c", - "author": { - "username": "emmap1", - "display_name": "Emma", - "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", - "links": { - "self": { - "href": "https://api.bitbucket.org/api/2.0/users/emmap1" - }, - "html": { - "href": "https://api.bitbucket.org/emmap1" - }, - "avatar": { - "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" - } - } - }, - "message": "old commit message\n", - "date": "2015-06-08T21:34:56+00:00", - "parents": [ - { - "type": "commit", - "hash": "e0d0c2041e09746be5ce4b55067d5a8e3098c843", - "links": { - "self": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commit/9c4a3452da3bc4f37af5a6bb9c784246f44406f7" - }, - "html": { - "href": "https://bitbucket.org/user_name/repo_name/commits/9c4a3452da3bc4f37af5a6bb9c784246f44406f7" - } - } - } - ], - "links": { - "self": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commit/b99ea6dad8f416e57c5ca78c1ccef590600d841b" - }, - "html": { - "href": "https://bitbucket.org/user_name/repo_name/commits/b99ea6dad8f416e57c5ca78c1ccef590600d841b" - } - } - }, - "links": { - "self": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/refs/branches/master" - }, - "commits": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commits/master" - }, - "html": { - "href": "https://bitbucket.org/user_name/repo_name/branch/master" - } - } - }, - "links": { - "html": { - "href": "https://bitbucket.org/user_name/repo_name/branches/compare/c4b2b7914156a878aa7c9da452a09fb50c2091f2..b99ea6dad8f416e57c5ca78c1ccef590600d841b" - }, - "diff": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/diff/c4b2b7914156a878aa7c9da452a09fb50c2091f2..b99ea6dad8f416e57c5ca78c1ccef590600d841b" - }, - "commits": { - "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commits?include=c4b2b7914156a878aa7c9da452a09fb50c2091f2&exclude=b99ea6dad8f416e57c5ca78c1ccef590600d841b" - } - }, - "created": false, - "forced": false, - "closed": false, - "commits": [ - { - "hash": "03f4a7270240708834de475bcf21532d6134777e", - "type": "commit", - "message": "commit message\n", - "author": { - "username": "emmap1", - "display_name": "Emma", - "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", - "links": { - "self": { - "href": "https://api.bitbucket.org/api/2.0/users/emmap1" - }, - "html": { - "href": "https://api.bitbucket.org/emmap1" - }, - "avatar": { - "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" - } - } - }, - "links": { - "self": { - "href": "https://api.bitbucket.org/2.0/repositories/user/repo/commit/03f4a7270240708834de475bcf21532d6134777e" - }, - "html": { - "href": "https://bitbucket.org/user/repo/commits/03f4a7270240708834de475bcf21532d6134777e" - } - } - } - ], - "truncated": false - } - ] - } -} \ No newline at end of file + "actor": { + "username": "emmap1", + "display_name": "Emma", + "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", + "links": { + "self": { + "href": "https://api.bitbucket.org/api/2.0/users/emmap1" + }, + "html": { + "href": "https://api.bitbucket.org/emmap1" + }, + "avatar": { + "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" + } + } + }, + "repository": { + "links": { + "self": { + "href": "https://api.bitbucket.org/api/2.0/repositories/bitbucket/bitbucket" + }, + "html": { + "href": "https://api.bitbucket.org/bitbucket/bitbucket" + }, + "avatar": { + "href": "https://api-staging-assetroot.s3.amazonaws.com/c/photos/2014/Aug/01/bitbucket-logo-2629490769-3_avatar.png" + } + }, + "uuid": "{673a6070-3421-46c9-9d48-90745f7bfe8e}", + "full_name": "team_name/repo_name", + "name": "repo_name", + "scm": "git", + "is_private": true + }, + "push": { + "changes": [ + { + "new": { + "type": "branch", + "name": "name-of-branch", + "target": { + "type": "commit", + "hash": "709d658dc5b6d6afcd46049c2f332ee3f515a67d", + "author": { + "username": "emmap1", + "display_name": "Emma", + "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", + "links": { + "self": { + "href": "https://api.bitbucket.org/api/2.0/users/emmap1" + }, + "html": { + "href": "https://api.bitbucket.org/emmap1" + }, + "avatar": { + "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" + } + } + }, + "message": "new commit message\n", + "date": "2015-06-09T03:34:49+00:00", + "parents": [ + { + "type": "commit", + "hash": "1e65c05c1d5171631d92438a13901ca7dae9618c", + "links": { + "self": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commit/8cbbd65829c7ad834a97841e0defc965718036a0" + }, + "html": { + "href": "https://bitbucket.org/user_name/repo_name/commits/8cbbd65829c7ad834a97841e0defc965718036a0" + } + } + } + ], + "links": { + "self": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commit/c4b2b7914156a878aa7c9da452a09fb50c2091f2" + }, + "html": { + "href": "https://bitbucket.org/user_name/repo_name/commits/c4b2b7914156a878aa7c9da452a09fb50c2091f2" + } + } + }, + "links": { + "self": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/refs/branches/master" + }, + "commits": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commits/master" + }, + "html": { + "href": "https://bitbucket.org/user_name/repo_name/branch/master" + } + } + }, + "old": { + "type": "branch", + "name": "name-of-branch", + "target": { + "type": "commit", + "hash": "1e65c05c1d5171631d92438a13901ca7dae9618c", + "author": { + "username": "emmap1", + "display_name": "Emma", + "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", + "links": { + "self": { + "href": "https://api.bitbucket.org/api/2.0/users/emmap1" + }, + "html": { + "href": "https://api.bitbucket.org/emmap1" + }, + "avatar": { + "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" + } + } + }, + "message": "old commit message\n", + "date": "2015-06-08T21:34:56+00:00", + "parents": [ + { + "type": "commit", + "hash": "e0d0c2041e09746be5ce4b55067d5a8e3098c843", + "links": { + "self": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commit/9c4a3452da3bc4f37af5a6bb9c784246f44406f7" + }, + "html": { + "href": "https://bitbucket.org/user_name/repo_name/commits/9c4a3452da3bc4f37af5a6bb9c784246f44406f7" + } + } + } + ], + "links": { + "self": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commit/b99ea6dad8f416e57c5ca78c1ccef590600d841b" + }, + "html": { + "href": "https://bitbucket.org/user_name/repo_name/commits/b99ea6dad8f416e57c5ca78c1ccef590600d841b" + } + } + }, + "links": { + "self": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/refs/branches/master" + }, + "commits": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commits/master" + }, + "html": { + "href": "https://bitbucket.org/user_name/repo_name/branch/master" + } + } + }, + "links": { + "html": { + "href": "https://bitbucket.org/user_name/repo_name/branches/compare/c4b2b7914156a878aa7c9da452a09fb50c2091f2..b99ea6dad8f416e57c5ca78c1ccef590600d841b" + }, + "diff": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/diff/c4b2b7914156a878aa7c9da452a09fb50c2091f2..b99ea6dad8f416e57c5ca78c1ccef590600d841b" + }, + "commits": { + "href": "https://api.bitbucket.org/2.0/repositories/user_name/repo_name/commits?include=c4b2b7914156a878aa7c9da452a09fb50c2091f2&exclude=b99ea6dad8f416e57c5ca78c1ccef590600d841b" + } + }, + "created": false, + "forced": false, + "closed": false, + "commits": [ + { + "hash": "03f4a7270240708834de475bcf21532d6134777e", + "type": "commit", + "message": "commit message\n", + "author": { + "username": "emmap1", + "display_name": "Emma", + "uuid": "{a54f16da-24e9-4d7f-a3a7-b1ba2cd98aa3}", + "links": { + "self": { + "href": "https://api.bitbucket.org/api/2.0/users/emmap1" + }, + "html": { + "href": "https://api.bitbucket.org/emmap1" + }, + "avatar": { + "href": "https://bitbucket-api-assetroot.s3.amazonaws.com/c/photos/2015/Feb/26/3613917261-0-emmap1-avatar_avatar.png" + } + } + }, + "links": { + "self": { + "href": "https://api.bitbucket.org/2.0/repositories/user/repo/commit/03f4a7270240708834de475bcf21532d6134777e" + }, + "html": { + "href": "https://bitbucket.org/user/repo/commits/03f4a7270240708834de475bcf21532d6134777e" + } + } + } + ], + "truncated": false + } + ] + } +} diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucketserver-invalid.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucketserver-invalid.json index 26e3912c..d8eb7201 100644 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucketserver-invalid.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucketserver-invalid.json @@ -1,30 +1,30 @@ -{ - "eventKey":"repo:refs_changed", - "date":"2017-09-19T09:45:32+1000", - "actor":{ - "name":"admin", - "emailAddress":"admin@example.com", - "id":1, - "displayName":"Administrator", - "active":true, - "slug":"admin", - "type":"NORMAL" - }, - "repository":{ - "slug":"repository", - "id":84, - "name":"repository", - "scmId":"git", - "state":"AVAILABLE", - "statusMessage":"Available", - "forkable":true, - "project":{ - "key":"PROJ", - "id":84, - "name":"project", - "public":false, - "type":"NORMAL" - }, - "public":false - } -} \ No newline at end of file +{ + "eventKey": "repo:refs_changed", + "date": "2017-09-19T09:45:32+1000", + "actor": { + "name": "admin", + "emailAddress": "admin@example.com", + "id": 1, + "displayName": "Administrator", + "active": true, + "slug": "admin", + "type": "NORMAL" + }, + "repository": { + "slug": "repository", + "id": 84, + "name": "repository", + "scmId": "git", + "state": "AVAILABLE", + "statusMessage": "Available", + "forkable": true, + "project": { + "key": "PROJ", + "id": 84, + "name": "project", + "public": false, + "type": "NORMAL" + }, + "public": false + } +} diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucketserver.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucketserver.json index b0d88522..79e0bcdf 100644 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucketserver.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/bitbucketserver.json @@ -1,43 +1,43 @@ -{ - "eventKey":"repo:refs_changed", - "date":"2017-09-19T09:45:32+1000", - "actor":{ - "name":"admin", - "emailAddress":"admin@example.com", - "id":1, - "displayName":"Administrator", - "active":true, - "slug":"admin", - "type":"NORMAL" - }, - "repository":{ - "slug":"repository", - "id":84, - "name":"repository", - "scmId":"git", - "state":"AVAILABLE", - "statusMessage":"Available", - "forkable":true, - "project":{ - "key":"PROJ", - "id":84, - "name":"project", - "public":false, - "type":"NORMAL" - }, - "public":false - }, - "changes":[ - { - "ref":{ - "id":"refs/heads/master", - "displayId":"master", - "type":"BRANCH" - }, - "refId":"refs/heads/master", - "fromHash":"ecddabb624f6f5ba43816f5926e580a5f680a932", - "toHash":"178864a7d521b6f5e720b386b2c2b0ef8563e0dc", - "type":"UPDATE" - } - ] -} \ No newline at end of file +{ + "eventKey": "repo:refs_changed", + "date": "2017-09-19T09:45:32+1000", + "actor": { + "name": "admin", + "emailAddress": "admin@example.com", + "id": 1, + "displayName": "Administrator", + "active": true, + "slug": "admin", + "type": "NORMAL" + }, + "repository": { + "slug": "repository", + "id": 84, + "name": "repository", + "scmId": "git", + "state": "AVAILABLE", + "statusMessage": "Available", + "forkable": true, + "project": { + "key": "PROJ", + "id": 84, + "name": "project", + "public": false, + "type": "NORMAL" + }, + "public": false + }, + "changes": [ + { + "ref": { + "id": "refs/heads/master", + "displayId": "master", + "type": "BRANCH" + }, + "refId": "refs/heads/master", + "fromHash": "ecddabb624f6f5ba43816f5926e580a5f680a932", + "toHash": "178864a7d521b6f5e720b386b2c2b0ef8563e0dc", + "type": "UPDATE" + } + ] +} diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/gitea.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/gitea.json index 3a24f895..ffeaa9fd 100755 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/gitea.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/gitea.json @@ -1,81 +1,81 @@ { - "secret": "gitea_push", - "ref": "refs/heads/master", - "before": "70767b558d8f850eac3fead13dfc232d043646a0", - "after": "78b77379c448caf024c73fa280ca571449224590", - "compare_url": "http://gitea.lawyers.corp/internal/lawsuits/compare/70767b558d8f850eac3fead13dfc232d043646a0...78b77379c448caf024c73fa280ca571449224590", - "commits": [ - { - "id": "78b77379c448caf024c73fa280ca571449224590", - "message": "SUPPORT-4765: urlencode\n", - "url": "http://gitea.lawyers.corp/internal/lawsuits/commit/78b77379c448caf024c73fa280ca571449224590", - "author": { - "name": "Perry Mason", - "email": "perrym@lawyers.corp", - "username": "git" - }, - "committer": { - "name": "Perry Mason", - "email": "perrym@lawyers.corp", - "username": "git" - }, - "verification": null, - "timestamp": "2018-08-27T11:18:34Z" - } - ], - "repository": { - "id": 480, - "owner": { - "id": 3, - "login": "internal", - "full_name": "", - "email": "", - "avatar_url": "http://gitea.lawyers.corp/avatars/dbc87f99ecd29cb0eb4447807ad73f9f", - "language": "", - "username": "internal" - }, - "name": "lawsuits", - "full_name": "internal/lawsuits", - "description": "", - "empty": false, - "private": false, - "fork": false, - "parent": null, - "mirror": false, - "size": 5516, - "html_url": "http://gitea.lawyers.corp/internal/lawsuits", - "ssh_url": "git@localhost:internal/lawsuits.git", - "clone_url": "http://gitea.lawyers.corp/internal/lawsuits.git", - "website": "", - "stars_count": 1, - "forks_count": 20, - "watchers_count": 6, - "open_issues_count": 0, - "default_branch": "master", - "created_at": "2018-01-18T15:11:51Z", - "updated_at": "2018-08-27T11:18:34Z", - "permissions": { - "admin": false, - "push": false, - "pull": false - } - }, - "pusher": { - "id": 2, - "login": "perrym", - "full_name": "Perry Mason", - "email": "perrym@lawyers.corp", - "avatar_url": "http://gitea.lawyers.corp/avatars/5868737ae078a4441031bf550d16e967", - "language": "en-US", - "username": "perrym" - }, - "sender": { - "id": 2, - "login": "perrym", - "full_name": "Perry Mason", - "email": "perrym@lawyers.corp", - "avatar_url": "http://gitea.lawyers.corp/avatars/5868737ae078a4441031bf550d16e967", - "language": "en-US", - "username": "perrym" - } -} \ No newline at end of file + "secret": "gitea_push", + "ref": "refs/heads/master", + "before": "70767b558d8f850eac3fead13dfc232d043646a0", + "after": "78b77379c448caf024c73fa280ca571449224590", + "compare_url": "http://gitea.lawyers.corp/internal/lawsuits/compare/70767b558d8f850eac3fead13dfc232d043646a0...78b77379c448caf024c73fa280ca571449224590", + "commits": [ + { + "id": "78b77379c448caf024c73fa280ca571449224590", + "message": "SUPPORT-4765: urlencode\n", + "url": "http://gitea.lawyers.corp/internal/lawsuits/commit/78b77379c448caf024c73fa280ca571449224590", + "author": { + "name": "Perry Mason", + "email": "perrym@lawyers.corp", + "username": "git" + }, + "committer": { + "name": "Perry Mason", + "email": "perrym@lawyers.corp", + "username": "git" + }, + "verification": null, + "timestamp": "2018-08-27T11:18:34Z" + } + ], + "repository": { + "id": 480, + "owner": { + "id": 3, + "login": "internal", + "full_name": "", + "email": "", + "avatar_url": "http://gitea.lawyers.corp/avatars/dbc87f99ecd29cb0eb4447807ad73f9f", + "language": "", + "username": "internal" + }, + "name": "lawsuits", + "full_name": "internal/lawsuits", + "description": "", + "empty": false, + "private": false, + "fork": false, + "parent": null, + "mirror": false, + "size": 5516, + "html_url": "http://gitea.lawyers.corp/internal/lawsuits", + "ssh_url": "git@localhost:internal/lawsuits.git", + "clone_url": "http://gitea.lawyers.corp/internal/lawsuits.git", + "website": "", + "stars_count": 1, + "forks_count": 20, + "watchers_count": 6, + "open_issues_count": 0, + "default_branch": "master", + "created_at": "2018-01-18T15:11:51Z", + "updated_at": "2018-08-27T11:18:34Z", + "permissions": { + "admin": false, + "push": false, + "pull": false + } + }, + "pusher": { + "id": 2, + "login": "perrym", + "full_name": "Perry Mason", + "email": "perrym@lawyers.corp", + "avatar_url": "http://gitea.lawyers.corp/avatars/5868737ae078a4441031bf550d16e967", + "language": "en-US", + "username": "perrym" + }, + "sender": { + "id": 2, + "login": "perrym", + "full_name": "Perry Mason", + "email": "perrym@lawyers.corp", + "avatar_url": "http://gitea.lawyers.corp/avatars/5868737ae078a4441031bf550d16e967", + "language": "en-US", + "username": "perrym" + } +} diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/gitee.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/gitee.json index 1331a464..016f84a6 100644 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/gitee.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/gitee.json @@ -1,54 +1,56 @@ { - "before": "fb32ef5812dc132ece716a05c50c7531c6dc1b4d", - "after": "ac63b9ba95191a1bf79d60bc262851a66c12cda1", - "ref": "refs/heads/master", - "user_id": 13, - "user_name": "123", - "user": { - "name": "123", - "username": "test123", - "url": "https://gitee.com/oschina" - }, - "repository": { - "name": "webhook", - "url": "http://git.oschina.net/oschina/webhook", - "description": "", - "homepage": "https://gitee.com/oschina/webhook" - }, - "commits": [{ - "id": "ac63b9ba95191a1bf79d60bc262851a66c12cda1", - "message": "1234 bug fix", - "timestamp": "2016-12-09T17:28:02 08:00", - "url": "https://gitee.com/oschina/webhook/commit/ac63b9ba95191a1bf79d60bc262851a66c12cda1", - "author": { - "name": "123", - "email": "123@123.com", - "time": "2016-12-09T17:28:02 08:00" - }, - "added": [ - "d.txt" - ], - "modified": [ - "c.txt" - ], - "removed": [ - "b.txt" - ] - }], - "total_commits_count": 1, - "commits_more_than_ten": false, - "project": { - "name": "webhook", - "path": "webhook", - "url": "https://gitee.com/oschina/webhook", - "git_ssh_url": "git@gitee.com:oschina/webhook.git", - "git_http_url": "https://gitee.com/oschina/webhook.git", - "git_svn_url": "svn://gitee.com/oschina/webhook", - "namespace": "oschina", - "name_with_namespace": "oschina/webhook", - "path_with_namespace": "oschina/webhook", - "default_branch": "master" - }, - "hook_name": "push_hooks", - "password": "pwd" + "before": "fb32ef5812dc132ece716a05c50c7531c6dc1b4d", + "after": "ac63b9ba95191a1bf79d60bc262851a66c12cda1", + "ref": "refs/heads/master", + "user_id": 13, + "user_name": "123", + "user": { + "name": "123", + "username": "test123", + "url": "https://gitee.com/oschina" + }, + "repository": { + "name": "webhook", + "url": "http://git.oschina.net/oschina/webhook", + "description": "", + "homepage": "https://gitee.com/oschina/webhook" + }, + "commits": [ + { + "id": "ac63b9ba95191a1bf79d60bc262851a66c12cda1", + "message": "1234 bug fix", + "timestamp": "2016-12-09T17:28:02 08:00", + "url": "https://gitee.com/oschina/webhook/commit/ac63b9ba95191a1bf79d60bc262851a66c12cda1", + "author": { + "name": "123", + "email": "123@123.com", + "time": "2016-12-09T17:28:02 08:00" + }, + "added": [ + "d.txt" + ], + "modified": [ + "c.txt" + ], + "removed": [ + "b.txt" + ] + } + ], + "total_commits_count": 1, + "commits_more_than_ten": false, + "project": { + "name": "webhook", + "path": "webhook", + "url": "https://gitee.com/oschina/webhook", + "git_ssh_url": "git@gitee.com:oschina/webhook.git", + "git_http_url": "https://gitee.com/oschina/webhook.git", + "git_svn_url": "svn://gitee.com/oschina/webhook", + "namespace": "oschina", + "name_with_namespace": "oschina/webhook", + "path_with_namespace": "oschina/webhook", + "default_branch": "master" + }, + "hook_name": "push_hooks", + "password": "pwd" } diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/github.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/github.json index 59e1a2f2..b2f3c390 100644 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/github.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/github.json @@ -1,161 +1,157 @@ { - "ref": "refs/heads/changes", - "before": "9049f1265b7d61be4a8904a9a27120d2064dab3b", - "after": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "created": false, - "deleted": false, - "forced": false, - "base_ref": null, - "compare": "https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f", - "commits": [ - { - "id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "distinct": true, - "message": "Update README.md", - "timestamp": "2015-05-05T19:40:15-04:00", - "url": "https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "author": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com", - "username": "baxterthehacker" - }, - "committer": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com", - "username": "baxterthehacker" - }, - "added": [ - - ], - "removed": [ - - ], - "modified": [ - "README.md" - ] - } - ], - "head_commit": { - "id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "distinct": true, - "message": "Update README.md", - "timestamp": "2015-05-05T19:40:15-04:00", - "url": "https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "author": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com", - "username": "baxterthehacker" - }, - "committer": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com", - "username": "baxterthehacker" - }, - "added": [ - - ], - "removed": [ - - ], - "modified": [ - "README.md" - ] - }, - "repository": { - "id": 35129377, - "name": "public-repo", - "full_name": "baxterthehacker/public-repo", - "owner": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com" - }, - "private": false, - "html_url": "https://github.com/baxterthehacker/public-repo", - "description": "", - "fork": false, - "url": "https://github.com/baxterthehacker/public-repo", - "forks_url": "https://api.github.com/repos/baxterthehacker/public-repo/forks", - "keys_url": "https://api.github.com/repos/baxterthehacker/public-repo/keys{/key_id}", - "collaborators_url": "https://api.github.com/repos/baxterthehacker/public-repo/collaborators{/collaborator}", - "teams_url": "https://api.github.com/repos/baxterthehacker/public-repo/teams", - "hooks_url": "https://api.github.com/repos/baxterthehacker/public-repo/hooks", - "issue_events_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/events{/number}", - "events_url": "https://api.github.com/repos/baxterthehacker/public-repo/events", - "assignees_url": "https://api.github.com/repos/baxterthehacker/public-repo/assignees{/user}", - "branches_url": "https://api.github.com/repos/baxterthehacker/public-repo/branches{/branch}", - "tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/tags", - "blobs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/blobs{/sha}", - "git_tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/tags{/sha}", - "git_refs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/refs{/sha}", - "trees_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/trees{/sha}", - "statuses_url": "https://api.github.com/repos/baxterthehacker/public-repo/statuses/{sha}", - "languages_url": "https://api.github.com/repos/baxterthehacker/public-repo/languages", - "stargazers_url": "https://api.github.com/repos/baxterthehacker/public-repo/stargazers", - "contributors_url": "https://api.github.com/repos/baxterthehacker/public-repo/contributors", - "subscribers_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscribers", - "subscription_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscription", - "commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/commits{/sha}", - "git_commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/commits{/sha}", - "comments_url": "https://api.github.com/repos/baxterthehacker/public-repo/comments{/number}", - "issue_comment_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/comments{/number}", - "contents_url": "https://api.github.com/repos/baxterthehacker/public-repo/contents/{+path}", - "compare_url": "https://api.github.com/repos/baxterthehacker/public-repo/compare/{base}...{head}", - "merges_url": "https://api.github.com/repos/baxterthehacker/public-repo/merges", - "archive_url": "https://api.github.com/repos/baxterthehacker/public-repo/{archive_format}{/ref}", - "downloads_url": "https://api.github.com/repos/baxterthehacker/public-repo/downloads", - "issues_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues{/number}", - "pulls_url": "https://api.github.com/repos/baxterthehacker/public-repo/pulls{/number}", - "milestones_url": "https://api.github.com/repos/baxterthehacker/public-repo/milestones{/number}", - "notifications_url": "https://api.github.com/repos/baxterthehacker/public-repo/notifications{?since,all,participating}", - "labels_url": "https://api.github.com/repos/baxterthehacker/public-repo/labels{/name}", - "releases_url": "https://api.github.com/repos/baxterthehacker/public-repo/releases{/id}", - "created_at": 1430869212, - "updated_at": "2015-05-05T23:40:12Z", - "pushed_at": 1430869217, - "git_url": "git://github.com/baxterthehacker/public-repo.git", - "ssh_url": "git@github.com:baxterthehacker/public-repo.git", - "clone_url": "https://github.com/baxterthehacker/public-repo.git", - "svn_url": "https://github.com/baxterthehacker/public-repo", - "homepage": null, - "size": 0, - "stargazers_count": 0, - "watchers_count": 0, - "language": null, - "has_issues": true, - "has_downloads": true, - "has_wiki": true, - "has_pages": true, - "forks_count": 0, - "mirror_url": null, - "open_issues_count": 0, - "forks": 0, - "open_issues": 0, - "watchers": 0, - "default_branch": "master", - "stargazers": 0, - "master_branch": "master" - }, - "pusher": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com" - }, - "sender": { - "login": "baxterthehacker", - "id": 6752317, - "avatar_url": "https://avatars.githubusercontent.com/u/6752317?v=3", - "gravatar_id": "", - "url": "https://api.github.com/users/baxterthehacker", - "html_url": "https://github.com/baxterthehacker", - "followers_url": "https://api.github.com/users/baxterthehacker/followers", - "following_url": "https://api.github.com/users/baxterthehacker/following{/other_user}", - "gists_url": "https://api.github.com/users/baxterthehacker/gists{/gist_id}", - "starred_url": "https://api.github.com/users/baxterthehacker/starred{/owner}{/repo}", - "subscriptions_url": "https://api.github.com/users/baxterthehacker/subscriptions", - "organizations_url": "https://api.github.com/users/baxterthehacker/orgs", - "repos_url": "https://api.github.com/users/baxterthehacker/repos", - "events_url": "https://api.github.com/users/baxterthehacker/events{/privacy}", - "received_events_url": "https://api.github.com/users/baxterthehacker/received_events", - "type": "User", - "site_admin": false - } -} \ No newline at end of file + "ref": "refs/heads/changes", + "before": "9049f1265b7d61be4a8904a9a27120d2064dab3b", + "after": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "created": false, + "deleted": false, + "forced": false, + "base_ref": null, + "compare": "https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f", + "commits": [ + { + "id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "distinct": true, + "message": "Update README.md", + "timestamp": "2015-05-05T19:40:15-04:00", + "url": "https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "author": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com", + "username": "baxterthehacker" + }, + "committer": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com", + "username": "baxterthehacker" + }, + "added": [ + ], + "removed": [ + ], + "modified": [ + "README.md" + ] + } + ], + "head_commit": { + "id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "distinct": true, + "message": "Update README.md", + "timestamp": "2015-05-05T19:40:15-04:00", + "url": "https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "author": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com", + "username": "baxterthehacker" + }, + "committer": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com", + "username": "baxterthehacker" + }, + "added": [ + ], + "removed": [ + ], + "modified": [ + "README.md" + ] + }, + "repository": { + "id": 35129377, + "name": "public-repo", + "full_name": "baxterthehacker/public-repo", + "owner": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com" + }, + "private": false, + "html_url": "https://github.com/baxterthehacker/public-repo", + "description": "", + "fork": false, + "url": "https://github.com/baxterthehacker/public-repo", + "forks_url": "https://api.github.com/repos/baxterthehacker/public-repo/forks", + "keys_url": "https://api.github.com/repos/baxterthehacker/public-repo/keys{/key_id}", + "collaborators_url": "https://api.github.com/repos/baxterthehacker/public-repo/collaborators{/collaborator}", + "teams_url": "https://api.github.com/repos/baxterthehacker/public-repo/teams", + "hooks_url": "https://api.github.com/repos/baxterthehacker/public-repo/hooks", + "issue_events_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/events{/number}", + "events_url": "https://api.github.com/repos/baxterthehacker/public-repo/events", + "assignees_url": "https://api.github.com/repos/baxterthehacker/public-repo/assignees{/user}", + "branches_url": "https://api.github.com/repos/baxterthehacker/public-repo/branches{/branch}", + "tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/tags", + "blobs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/blobs{/sha}", + "git_tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/tags{/sha}", + "git_refs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/refs{/sha}", + "trees_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/trees{/sha}", + "statuses_url": "https://api.github.com/repos/baxterthehacker/public-repo/statuses/{sha}", + "languages_url": "https://api.github.com/repos/baxterthehacker/public-repo/languages", + "stargazers_url": "https://api.github.com/repos/baxterthehacker/public-repo/stargazers", + "contributors_url": "https://api.github.com/repos/baxterthehacker/public-repo/contributors", + "subscribers_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscribers", + "subscription_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscription", + "commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/commits{/sha}", + "git_commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/commits{/sha}", + "comments_url": "https://api.github.com/repos/baxterthehacker/public-repo/comments{/number}", + "issue_comment_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/comments{/number}", + "contents_url": "https://api.github.com/repos/baxterthehacker/public-repo/contents/{+path}", + "compare_url": "https://api.github.com/repos/baxterthehacker/public-repo/compare/{base}...{head}", + "merges_url": "https://api.github.com/repos/baxterthehacker/public-repo/merges", + "archive_url": "https://api.github.com/repos/baxterthehacker/public-repo/{archive_format}{/ref}", + "downloads_url": "https://api.github.com/repos/baxterthehacker/public-repo/downloads", + "issues_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues{/number}", + "pulls_url": "https://api.github.com/repos/baxterthehacker/public-repo/pulls{/number}", + "milestones_url": "https://api.github.com/repos/baxterthehacker/public-repo/milestones{/number}", + "notifications_url": "https://api.github.com/repos/baxterthehacker/public-repo/notifications{?since,all,participating}", + "labels_url": "https://api.github.com/repos/baxterthehacker/public-repo/labels{/name}", + "releases_url": "https://api.github.com/repos/baxterthehacker/public-repo/releases{/id}", + "created_at": 1430869212, + "updated_at": "2015-05-05T23:40:12Z", + "pushed_at": 1430869217, + "git_url": "git://github.com/baxterthehacker/public-repo.git", + "ssh_url": "git@github.com:baxterthehacker/public-repo.git", + "clone_url": "https://github.com/baxterthehacker/public-repo.git", + "svn_url": "https://github.com/baxterthehacker/public-repo", + "homepage": null, + "size": 0, + "stargazers_count": 0, + "watchers_count": 0, + "language": null, + "has_issues": true, + "has_downloads": true, + "has_wiki": true, + "has_pages": true, + "forks_count": 0, + "mirror_url": null, + "open_issues_count": 0, + "forks": 0, + "open_issues": 0, + "watchers": 0, + "default_branch": "master", + "stargazers": 0, + "master_branch": "master" + }, + "pusher": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com" + }, + "sender": { + "login": "baxterthehacker", + "id": 6752317, + "avatar_url": "https://avatars.githubusercontent.com/u/6752317?v=3", + "gravatar_id": "", + "url": "https://api.github.com/users/baxterthehacker", + "html_url": "https://github.com/baxterthehacker", + "followers_url": "https://api.github.com/users/baxterthehacker/followers", + "following_url": "https://api.github.com/users/baxterthehacker/following{/other_user}", + "gists_url": "https://api.github.com/users/baxterthehacker/gists{/gist_id}", + "starred_url": "https://api.github.com/users/baxterthehacker/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/baxterthehacker/subscriptions", + "organizations_url": "https://api.github.com/users/baxterthehacker/orgs", + "repos_url": "https://api.github.com/users/baxterthehacker/repos", + "events_url": "https://api.github.com/users/baxterthehacker/events{/privacy}", + "received_events_url": "https://api.github.com/users/baxterthehacker/received_events", + "type": "User", + "site_admin": false + } +} diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/gitlab.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/gitlab.json index 741b2c0d..299258f3 100644 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/gitlab.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/gitlab.json @@ -1,65 +1,71 @@ { - "object_kind": "push", - "before": "95790bf891e76fee5e1747ab589903a6a1f80f22", - "after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", - "ref": "refs/heads/master", - "user_id": 4, - "user_name": "John Smith", - "user_email": "john@example.com", - "user_avatar": "https://s.gravatar.com/avatar/d4c74594d841139328695756648b6bd6?s=8://s.gravatar.com/avatar/d4c74594d841139328695756648b6bd6?s=80", - "project_id": 15, - "project":{ - "name":"Diaspora", - "description":"", - "web_url":"http://example.com/mike/diaspora", - "avatar_url":null, - "git_ssh_url":"git@example.com:mike/diaspora.git", - "git_http_url":"http://example.com/mike/diaspora.git", - "namespace":"Mike", - "visibility_level":0, - "path_with_namespace":"mike/diaspora", - "default_branch":"master", - "homepage":"http://example.com/mike/diaspora", - "url":"git@example.com:mike/diasporadiaspora.git", - "ssh_url":"git@example.com:mike/diaspora.git", - "http_url":"http://example.com/mike/diaspora.git" - }, - "repository":{ - "name": "Diaspora", - "url": "git@example.com:mike/diasporadiaspora.git", - "description": "", - "homepage": "http://example.com/mike/diaspora", - "git_http_url":"http://example.com/mike/diaspora.git", - "git_ssh_url":"git@example.com:mike/diaspora.git", - "visibility_level":0 - }, - "commits": [ - { - "id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", - "message": "Update Catalan translation to e38cb41.", - "timestamp": "2011-12-12T14:27:31+02:00", - "url": "http://example.com/mike/diaspora/commit/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", - "author": { - "name": "Jordi Mallach", - "email": "jordi@softcatala.org" - }, - "added": ["newapp.properties"], - "modified": ["application.yml"], - "removed": [] - }, - { - "id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", - "message": "fixed readme", - "timestamp": "2012-01-03T23:36:29+02:00", - "url": "http://example.com/mike/diaspora/commit/da1560886d4f094c3e6c9ef40349f7d38b5d27d7", - "author": { - "name": "GitLab dev user", - "email": "gitlabdev@dv6700.(none)" - }, - "added": [], - "modified": ["oldapp.yml"], - "removed": [] - } - ], - "total_commits_count": 4 -} \ No newline at end of file + "object_kind": "push", + "before": "95790bf891e76fee5e1747ab589903a6a1f80f22", + "after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", + "ref": "refs/heads/master", + "user_id": 4, + "user_name": "John Smith", + "user_email": "john@example.com", + "user_avatar": "https://s.gravatar.com/avatar/d4c74594d841139328695756648b6bd6?s=8://s.gravatar.com/avatar/d4c74594d841139328695756648b6bd6?s=80", + "project_id": 15, + "project": { + "name": "Diaspora", + "description": "", + "web_url": "http://example.com/mike/diaspora", + "avatar_url": null, + "git_ssh_url": "git@example.com:mike/diaspora.git", + "git_http_url": "http://example.com/mike/diaspora.git", + "namespace": "Mike", + "visibility_level": 0, + "path_with_namespace": "mike/diaspora", + "default_branch": "master", + "homepage": "http://example.com/mike/diaspora", + "url": "git@example.com:mike/diasporadiaspora.git", + "ssh_url": "git@example.com:mike/diaspora.git", + "http_url": "http://example.com/mike/diaspora.git" + }, + "repository": { + "name": "Diaspora", + "url": "git@example.com:mike/diasporadiaspora.git", + "description": "", + "homepage": "http://example.com/mike/diaspora", + "git_http_url": "http://example.com/mike/diaspora.git", + "git_ssh_url": "git@example.com:mike/diaspora.git", + "visibility_level": 0 + }, + "commits": [ + { + "id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", + "message": "Update Catalan translation to e38cb41.", + "timestamp": "2011-12-12T14:27:31+02:00", + "url": "http://example.com/mike/diaspora/commit/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", + "author": { + "name": "Jordi Mallach", + "email": "jordi@softcatala.org" + }, + "added": [ + "newapp.properties" + ], + "modified": [ + "application.yml" + ], + "removed": [] + }, + { + "id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", + "message": "fixed readme", + "timestamp": "2012-01-03T23:36:29+02:00", + "url": "http://example.com/mike/diaspora/commit/da1560886d4f094c3e6c9ef40349f7d38b5d27d7", + "author": { + "name": "GitLab dev user", + "email": "gitlabdev@dv6700.(none)" + }, + "added": [], + "modified": [ + "oldapp.yml" + ], + "removed": [] + } + ], + "total_commits_count": 4 +} diff --git a/spring-cloud-config-monitor/src/test/resources/pathsamples/gogs.json b/spring-cloud-config-monitor/src/test/resources/pathsamples/gogs.json index 59e1a2f2..b2f3c390 100755 --- a/spring-cloud-config-monitor/src/test/resources/pathsamples/gogs.json +++ b/spring-cloud-config-monitor/src/test/resources/pathsamples/gogs.json @@ -1,161 +1,157 @@ { - "ref": "refs/heads/changes", - "before": "9049f1265b7d61be4a8904a9a27120d2064dab3b", - "after": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "created": false, - "deleted": false, - "forced": false, - "base_ref": null, - "compare": "https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f", - "commits": [ - { - "id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "distinct": true, - "message": "Update README.md", - "timestamp": "2015-05-05T19:40:15-04:00", - "url": "https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "author": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com", - "username": "baxterthehacker" - }, - "committer": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com", - "username": "baxterthehacker" - }, - "added": [ - - ], - "removed": [ - - ], - "modified": [ - "README.md" - ] - } - ], - "head_commit": { - "id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "distinct": true, - "message": "Update README.md", - "timestamp": "2015-05-05T19:40:15-04:00", - "url": "https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", - "author": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com", - "username": "baxterthehacker" - }, - "committer": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com", - "username": "baxterthehacker" - }, - "added": [ - - ], - "removed": [ - - ], - "modified": [ - "README.md" - ] - }, - "repository": { - "id": 35129377, - "name": "public-repo", - "full_name": "baxterthehacker/public-repo", - "owner": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com" - }, - "private": false, - "html_url": "https://github.com/baxterthehacker/public-repo", - "description": "", - "fork": false, - "url": "https://github.com/baxterthehacker/public-repo", - "forks_url": "https://api.github.com/repos/baxterthehacker/public-repo/forks", - "keys_url": "https://api.github.com/repos/baxterthehacker/public-repo/keys{/key_id}", - "collaborators_url": "https://api.github.com/repos/baxterthehacker/public-repo/collaborators{/collaborator}", - "teams_url": "https://api.github.com/repos/baxterthehacker/public-repo/teams", - "hooks_url": "https://api.github.com/repos/baxterthehacker/public-repo/hooks", - "issue_events_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/events{/number}", - "events_url": "https://api.github.com/repos/baxterthehacker/public-repo/events", - "assignees_url": "https://api.github.com/repos/baxterthehacker/public-repo/assignees{/user}", - "branches_url": "https://api.github.com/repos/baxterthehacker/public-repo/branches{/branch}", - "tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/tags", - "blobs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/blobs{/sha}", - "git_tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/tags{/sha}", - "git_refs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/refs{/sha}", - "trees_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/trees{/sha}", - "statuses_url": "https://api.github.com/repos/baxterthehacker/public-repo/statuses/{sha}", - "languages_url": "https://api.github.com/repos/baxterthehacker/public-repo/languages", - "stargazers_url": "https://api.github.com/repos/baxterthehacker/public-repo/stargazers", - "contributors_url": "https://api.github.com/repos/baxterthehacker/public-repo/contributors", - "subscribers_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscribers", - "subscription_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscription", - "commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/commits{/sha}", - "git_commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/commits{/sha}", - "comments_url": "https://api.github.com/repos/baxterthehacker/public-repo/comments{/number}", - "issue_comment_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/comments{/number}", - "contents_url": "https://api.github.com/repos/baxterthehacker/public-repo/contents/{+path}", - "compare_url": "https://api.github.com/repos/baxterthehacker/public-repo/compare/{base}...{head}", - "merges_url": "https://api.github.com/repos/baxterthehacker/public-repo/merges", - "archive_url": "https://api.github.com/repos/baxterthehacker/public-repo/{archive_format}{/ref}", - "downloads_url": "https://api.github.com/repos/baxterthehacker/public-repo/downloads", - "issues_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues{/number}", - "pulls_url": "https://api.github.com/repos/baxterthehacker/public-repo/pulls{/number}", - "milestones_url": "https://api.github.com/repos/baxterthehacker/public-repo/milestones{/number}", - "notifications_url": "https://api.github.com/repos/baxterthehacker/public-repo/notifications{?since,all,participating}", - "labels_url": "https://api.github.com/repos/baxterthehacker/public-repo/labels{/name}", - "releases_url": "https://api.github.com/repos/baxterthehacker/public-repo/releases{/id}", - "created_at": 1430869212, - "updated_at": "2015-05-05T23:40:12Z", - "pushed_at": 1430869217, - "git_url": "git://github.com/baxterthehacker/public-repo.git", - "ssh_url": "git@github.com:baxterthehacker/public-repo.git", - "clone_url": "https://github.com/baxterthehacker/public-repo.git", - "svn_url": "https://github.com/baxterthehacker/public-repo", - "homepage": null, - "size": 0, - "stargazers_count": 0, - "watchers_count": 0, - "language": null, - "has_issues": true, - "has_downloads": true, - "has_wiki": true, - "has_pages": true, - "forks_count": 0, - "mirror_url": null, - "open_issues_count": 0, - "forks": 0, - "open_issues": 0, - "watchers": 0, - "default_branch": "master", - "stargazers": 0, - "master_branch": "master" - }, - "pusher": { - "name": "baxterthehacker", - "email": "baxterthehacker@users.noreply.github.com" - }, - "sender": { - "login": "baxterthehacker", - "id": 6752317, - "avatar_url": "https://avatars.githubusercontent.com/u/6752317?v=3", - "gravatar_id": "", - "url": "https://api.github.com/users/baxterthehacker", - "html_url": "https://github.com/baxterthehacker", - "followers_url": "https://api.github.com/users/baxterthehacker/followers", - "following_url": "https://api.github.com/users/baxterthehacker/following{/other_user}", - "gists_url": "https://api.github.com/users/baxterthehacker/gists{/gist_id}", - "starred_url": "https://api.github.com/users/baxterthehacker/starred{/owner}{/repo}", - "subscriptions_url": "https://api.github.com/users/baxterthehacker/subscriptions", - "organizations_url": "https://api.github.com/users/baxterthehacker/orgs", - "repos_url": "https://api.github.com/users/baxterthehacker/repos", - "events_url": "https://api.github.com/users/baxterthehacker/events{/privacy}", - "received_events_url": "https://api.github.com/users/baxterthehacker/received_events", - "type": "User", - "site_admin": false - } -} \ No newline at end of file + "ref": "refs/heads/changes", + "before": "9049f1265b7d61be4a8904a9a27120d2064dab3b", + "after": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "created": false, + "deleted": false, + "forced": false, + "base_ref": null, + "compare": "https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f", + "commits": [ + { + "id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "distinct": true, + "message": "Update README.md", + "timestamp": "2015-05-05T19:40:15-04:00", + "url": "https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "author": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com", + "username": "baxterthehacker" + }, + "committer": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com", + "username": "baxterthehacker" + }, + "added": [ + ], + "removed": [ + ], + "modified": [ + "README.md" + ] + } + ], + "head_commit": { + "id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "distinct": true, + "message": "Update README.md", + "timestamp": "2015-05-05T19:40:15-04:00", + "url": "https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c", + "author": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com", + "username": "baxterthehacker" + }, + "committer": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com", + "username": "baxterthehacker" + }, + "added": [ + ], + "removed": [ + ], + "modified": [ + "README.md" + ] + }, + "repository": { + "id": 35129377, + "name": "public-repo", + "full_name": "baxterthehacker/public-repo", + "owner": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com" + }, + "private": false, + "html_url": "https://github.com/baxterthehacker/public-repo", + "description": "", + "fork": false, + "url": "https://github.com/baxterthehacker/public-repo", + "forks_url": "https://api.github.com/repos/baxterthehacker/public-repo/forks", + "keys_url": "https://api.github.com/repos/baxterthehacker/public-repo/keys{/key_id}", + "collaborators_url": "https://api.github.com/repos/baxterthehacker/public-repo/collaborators{/collaborator}", + "teams_url": "https://api.github.com/repos/baxterthehacker/public-repo/teams", + "hooks_url": "https://api.github.com/repos/baxterthehacker/public-repo/hooks", + "issue_events_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/events{/number}", + "events_url": "https://api.github.com/repos/baxterthehacker/public-repo/events", + "assignees_url": "https://api.github.com/repos/baxterthehacker/public-repo/assignees{/user}", + "branches_url": "https://api.github.com/repos/baxterthehacker/public-repo/branches{/branch}", + "tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/tags", + "blobs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/blobs{/sha}", + "git_tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/tags{/sha}", + "git_refs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/refs{/sha}", + "trees_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/trees{/sha}", + "statuses_url": "https://api.github.com/repos/baxterthehacker/public-repo/statuses/{sha}", + "languages_url": "https://api.github.com/repos/baxterthehacker/public-repo/languages", + "stargazers_url": "https://api.github.com/repos/baxterthehacker/public-repo/stargazers", + "contributors_url": "https://api.github.com/repos/baxterthehacker/public-repo/contributors", + "subscribers_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscribers", + "subscription_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscription", + "commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/commits{/sha}", + "git_commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/commits{/sha}", + "comments_url": "https://api.github.com/repos/baxterthehacker/public-repo/comments{/number}", + "issue_comment_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/comments{/number}", + "contents_url": "https://api.github.com/repos/baxterthehacker/public-repo/contents/{+path}", + "compare_url": "https://api.github.com/repos/baxterthehacker/public-repo/compare/{base}...{head}", + "merges_url": "https://api.github.com/repos/baxterthehacker/public-repo/merges", + "archive_url": "https://api.github.com/repos/baxterthehacker/public-repo/{archive_format}{/ref}", + "downloads_url": "https://api.github.com/repos/baxterthehacker/public-repo/downloads", + "issues_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues{/number}", + "pulls_url": "https://api.github.com/repos/baxterthehacker/public-repo/pulls{/number}", + "milestones_url": "https://api.github.com/repos/baxterthehacker/public-repo/milestones{/number}", + "notifications_url": "https://api.github.com/repos/baxterthehacker/public-repo/notifications{?since,all,participating}", + "labels_url": "https://api.github.com/repos/baxterthehacker/public-repo/labels{/name}", + "releases_url": "https://api.github.com/repos/baxterthehacker/public-repo/releases{/id}", + "created_at": 1430869212, + "updated_at": "2015-05-05T23:40:12Z", + "pushed_at": 1430869217, + "git_url": "git://github.com/baxterthehacker/public-repo.git", + "ssh_url": "git@github.com:baxterthehacker/public-repo.git", + "clone_url": "https://github.com/baxterthehacker/public-repo.git", + "svn_url": "https://github.com/baxterthehacker/public-repo", + "homepage": null, + "size": 0, + "stargazers_count": 0, + "watchers_count": 0, + "language": null, + "has_issues": true, + "has_downloads": true, + "has_wiki": true, + "has_pages": true, + "forks_count": 0, + "mirror_url": null, + "open_issues_count": 0, + "forks": 0, + "open_issues": 0, + "watchers": 0, + "default_branch": "master", + "stargazers": 0, + "master_branch": "master" + }, + "pusher": { + "name": "baxterthehacker", + "email": "baxterthehacker@users.noreply.github.com" + }, + "sender": { + "login": "baxterthehacker", + "id": 6752317, + "avatar_url": "https://avatars.githubusercontent.com/u/6752317?v=3", + "gravatar_id": "", + "url": "https://api.github.com/users/baxterthehacker", + "html_url": "https://github.com/baxterthehacker", + "followers_url": "https://api.github.com/users/baxterthehacker/followers", + "following_url": "https://api.github.com/users/baxterthehacker/following{/other_user}", + "gists_url": "https://api.github.com/users/baxterthehacker/gists{/gist_id}", + "starred_url": "https://api.github.com/users/baxterthehacker/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/baxterthehacker/subscriptions", + "organizations_url": "https://api.github.com/users/baxterthehacker/orgs", + "repos_url": "https://api.github.com/users/baxterthehacker/repos", + "events_url": "https://api.github.com/users/baxterthehacker/events{/privacy}", + "received_events_url": "https://api.github.com/users/baxterthehacker/received_events", + "type": "User", + "site_admin": false + } +} diff --git a/spring-cloud-config-sample/pom.xml b/spring-cloud-config-sample/pom.xml index 1eb717d7..feb9fa94 100644 --- a/spring-cloud-config-sample/pom.xml +++ b/spring-cloud-config-sample/pom.xml @@ -1,10 +1,11 @@ - + 4.0.0 spring-cloud-config-sample - jar + jar spring-cloud-config-sample spring-cloud-config-server @@ -49,14 +50,14 @@ - - - maven-deploy-plugin - - true - - - + + + maven-deploy-plugin + + true + + + org.springframework.boot spring-boot-maven-plugin diff --git a/spring-cloud-config-sample/src/main/java/sample/Application.java b/spring-cloud-config-sample/src/main/java/sample/Application.java index 3f5bda63..d136828f 100644 --- a/spring-cloud-config-sample/src/main/java/sample/Application.java +++ b/spring-cloud-config-sample/src/main/java/sample/Application.java @@ -1,3 +1,18 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 sample; @@ -16,13 +31,13 @@ public class Application { @Autowired private Environment environment; - @RequestMapping("/") - public String query(@RequestParam("q") String q) { - return environment.getProperty(q); - } - public static void main(String[] args) { SpringApplication.run(Application.class, args); } + @RequestMapping("/") + public String query(@RequestParam("q") String q) { + return this.environment.getProperty(q); + } + } diff --git a/spring-cloud-config-sample/src/main/resources/application.yml b/spring-cloud-config-sample/src/main/resources/application.yml index 8e65496b..4e144d32 100644 --- a/spring-cloud-config-sample/src/main/resources/application.yml +++ b/spring-cloud-config-sample/src/main/resources/application.yml @@ -6,4 +6,4 @@ endpoints: logging: levels: org.springframework.boot.env.PropertySourcesLoader: TRACE - org.springframework.web: DEBUG \ No newline at end of file + org.springframework.web: DEBUG diff --git a/spring-cloud-config-sample/src/main/resources/bootstrap.yml b/spring-cloud-config-sample/src/main/resources/bootstrap.yml index 4b585619..e76ec2de 100644 --- a/spring-cloud-config-sample/src/main/resources/bootstrap.yml +++ b/spring-cloud-config-sample/src/main/resources/bootstrap.yml @@ -3,4 +3,4 @@ spring: name: bar cloud: config: - uri: http://localhost:${config.port:8888} \ No newline at end of file + uri: http://localhost:${config.port:8888} diff --git a/spring-cloud-config-sample/src/main/resources/bootstrapservercomposite.yml b/spring-cloud-config-sample/src/main/resources/bootstrapservercomposite.yml index 29f14d2d..d81dd611 100644 --- a/spring-cloud-config-sample/src/main/resources/bootstrapservercomposite.yml +++ b/spring-cloud-config-sample/src/main/resources/bootstrapservercomposite.yml @@ -9,4 +9,4 @@ spring: uri: ${repo1} bootstrap: true profiles: - active: composite \ No newline at end of file + active: composite diff --git a/spring-cloud-config-sample/src/test/java/sample/ApplicationBootstrapTests.java b/spring-cloud-config-sample/src/test/java/sample/ApplicationBootstrapTests.java index 7dccace2..a358c984 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ApplicationBootstrapTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ApplicationBootstrapTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 sample; import java.io.IOException; @@ -22,28 +38,33 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** - * Test for gh-975. - * org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name - * 'vaultEnvironmentRepositoryFactory' defined in - * org.springframework.cloud.config.server.config.CompositeRepositoryConfiguration: Unsatisfied dependency - * No qualifying bean of type 'javax.servlet.http.HttpServletRequest' available: + * Test for gh-975. org.springframework.beans.factory.UnsatisfiedDependencyException: + * Error creating bean with name 'vaultEnvironmentRepositoryFactory' defined in + * org.springframework.cloud.config.server.config.CompositeRepositoryConfiguration: + * Unsatisfied dependency No qualifying bean of type + * 'javax.servlet.http.HttpServletRequest' available. + * + * @author Spencer Gibb */ @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, -// Normally spring.cloud.config.enabled:true is the default but since we have the config -// server on the classpath we need to set it explicitly - properties = { "spring.cloud.config.enabled:true", "", - "management.security.enabled=false", "management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT) + // Normally spring.cloud.config.enabled:true is the default but since we have the + // config + // server on the classpath we need to set it explicitly + properties = { "spring.cloud.config.enabled:true", "", + "management.security.enabled=false", + "management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT) public class ApplicationBootstrapTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); private static int configPort = SocketUtils.findAvailableTcpPort(); + private static ConfigurableApplicationContext server; + @LocalServerPort private int port; - private static ConfigurableApplicationContext server; - @BeforeClass public static void startConfigServer() throws IOException { System.setProperty("spring.cloud.bootstrap.name", "bootstrapservercomposite"); @@ -69,20 +90,20 @@ public class ApplicationBootstrapTests { } } - @Test - @SuppressWarnings("unchecked") - public void contextLoads() { - Map res = new TestRestTemplate() - .getForObject("http://localhost:" + port + BASE_PATH + "/env/info.foo", Map.class); - assertThat(res).containsKey("propertySources"); - Map property = (Map) res.get("property"); - assertThat(property).containsEntry("value", "bar"); - } - public static void main(String[] args) throws IOException { configPort = 8888; startConfigServer(); SpringApplication.run(Application.class, args); } + @Test + @SuppressWarnings("unchecked") + public void contextLoads() { + Map res = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + BASE_PATH + "/env/info.foo", Map.class); + assertThat(res).containsKey("propertySources"); + Map property = (Map) res.get("property"); + assertThat(property).containsEntry("value", "bar"); + } + } diff --git a/spring-cloud-config-sample/src/test/java/sample/ApplicationFailFastTests.java b/spring-cloud-config-sample/src/test/java/sample/ApplicationFailFastTests.java index 9a09c09d..ccbfbbe5 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ApplicationFailFastTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ApplicationFailFastTests.java @@ -1,25 +1,43 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 sample; import org.junit.Test; + import org.springframework.boot.builder.SpringApplicationBuilder; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; public class ApplicationFailFastTests { @Test public void contextFails() { - try { - new SpringApplicationBuilder() - .sources(Application.class) - .run("--server.port=0", "--spring.cloud.config.enabled=true", - "--spring.cloud.config.fail-fast=true", - "--spring.cloud.config.uri=http://server-host-doesnt-exist:1234"); - fail("failFast option did not produce an exception"); - } catch (Exception e) { - assertTrue("Exception not caused by fail fast", e.getMessage().contains("fail fast")); - } - } + try { + new SpringApplicationBuilder().sources(Application.class).run( + "--server.port=0", "--spring.cloud.config.enabled=true", + "--spring.cloud.config.fail-fast=true", + "--spring.cloud.config.uri=http://server-host-doesnt-exist:1234"); + fail("failFast option did not produce an exception"); + } + catch (Exception e) { + assertThat(e.getMessage().contains("fail fast")) + .as("Exception not caused by fail fast").isTrue(); + } + } } diff --git a/spring-cloud-config-sample/src/test/java/sample/ApplicationTests.java b/spring-cloud-config-sample/src/test/java/sample/ApplicationTests.java index cad9a8b0..3827eef4 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ApplicationTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ApplicationTests.java @@ -1,9 +1,29 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 sample; +import java.io.IOException; +import java.util.Map; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.test.context.SpringBootTest; @@ -14,28 +34,28 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.SocketUtils; -import java.io.IOException; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, -// Normally spring.cloud.config.enabled:true is the default but since we have the config -// server on the classpath we need to set it explicitly - properties = { "spring.cloud.config.enabled:true", - "management.security.enabled=false", "management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT) + // Normally spring.cloud.config.enabled:true is the default but since we have the + // config + // server on the classpath we need to set it explicitly + properties = { "spring.cloud.config.enabled:true", + "management.security.enabled=false", + "management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT) public class ApplicationTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); private static int configPort = SocketUtils.findAvailableTcpPort(); + private static ConfigurableApplicationContext server; + @LocalServerPort private int port; - private static ConfigurableApplicationContext server; - @BeforeClass public static void startConfigServer() throws IOException { String baseDir = ConfigServerTestUtils @@ -46,8 +66,10 @@ public class ApplicationTests { org.springframework.cloud.config.server.ConfigServerApplication.class, "--server.port=" + configPort, "--spring.config.name=server", "--spring.cloud.config.server.git.uri=" + repo); - /*FIXME configPort = ((EmbeddedWebApplicationContext) server) - .getEmbeddedServletContainer().getPort();*/ + /* + * FIXME configPort = ((EmbeddedWebApplicationContext) server) + * .getEmbeddedServletContainer().getPort(); + */ System.setProperty("config.port", "" + configPort); } @@ -59,20 +81,20 @@ public class ApplicationTests { } } - @Test - @SuppressWarnings("unchecked") - public void contextLoads() { - Map res = new TestRestTemplate() - .getForObject("http://localhost:" + port + BASE_PATH + "/env/info.foo", Map.class); - assertThat(res).containsKey("propertySources"); - Map property = (Map) res.get("property"); - assertThat(property).containsEntry("value", "bar"); - } - public static void main(String[] args) throws IOException { configPort = 8888; startConfigServer(); SpringApplication.run(Application.class, args); } + @Test + @SuppressWarnings("unchecked") + public void contextLoads() { + Map res = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + BASE_PATH + "/env/info.foo", Map.class); + assertThat(res).containsKey("propertySources"); + Map property = (Map) res.get("property"); + assertThat(property).containsEntry("value", "bar"); + } + } diff --git a/spring-cloud-config-sample/src/test/java/sample/ServerNativeApplicationTests.java b/spring-cloud-config-sample/src/test/java/sample/ServerNativeApplicationTests.java index 890bee62..bfbbaee1 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ServerNativeApplicationTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ServerNativeApplicationTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 sample; import java.io.IOException; @@ -6,6 +22,7 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.context.SpringBootTest; @@ -15,54 +32,56 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, - properties = "spring.application.name:bad", webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = Application.class, properties = "spring.application.name:bad", webEnvironment = RANDOM_PORT) public class ServerNativeApplicationTests { private static int configPort = 0; + private static ConfigurableApplicationContext server; + @Autowired private ConfigurableEnvironment environment; @LocalServerPort private int port; - private static ConfigurableApplicationContext server; - @BeforeClass public static void startConfigServer() throws IOException { String repo = ConfigServerTestUtils.prepareLocalRepo(); server = SpringApplication.run( org.springframework.cloud.config.server.ConfigServerApplication.class, "--server.port=" + configPort, "--spring.config.name=server", - "--spring.cloud.config.server.git.uri=" + repo, "--spring.profiles.active=native"); - /*FIXME configPort = ((EmbeddedWebApplicationContext) server) - .getEmbeddedServletContainer().getPort();*/ + "--spring.cloud.config.server.git.uri=" + repo, + "--spring.profiles.active=native"); + /* + * FIXME configPort = ((EmbeddedWebApplicationContext) server) + * .getEmbeddedServletContainer().getPort(); + */ System.setProperty("config.port", "" + configPort); } @AfterClass public static void close() { System.clearProperty("config.port"); - if (server!=null) { + if (server != null) { server.close(); } } - @Test - public void contextLoads() { - // The remote config was bad so there is no bootstrap - assertFalse(this.environment.getPropertySources().contains("bootstrap")); - } - public static void main(String[] args) throws IOException { configPort = 8888; startConfigServer(); SpringApplication.run(Application.class, args); } + @Test + public void contextLoads() { + // The remote config was bad so there is no bootstrap + assertThat(this.environment.getPropertySources().contains("bootstrap")).isFalse(); + } + } diff --git a/spring-cloud-config-sample/src/test/resources/bad.yml b/spring-cloud-config-sample/src/test/resources/bad.yml index fdd9e04d..33598709 100644 --- a/spring-cloud-config-sample/src/test/resources/bad.yml +++ b/spring-cloud-config-sample/src/test/resources/bad.yml @@ -1,4 +1,4 @@ foo: -# whitespace error! - bar: spam - bucket: wham \ No newline at end of file + # whitespace error! + bar: spam + bucket: wham diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/application.yml b/spring-cloud-config-sample/src/test/resources/config-repo/application.yml index d6acc405..7a68a4bb 100644 --- a/spring-cloud-config-sample/src/test/resources/config-repo/application.yml +++ b/spring-cloud-config-sample/src/test/resources/config-repo/application.yml @@ -1,3 +1,3 @@ -info: +info: foo: bar raw: true diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/bar.properties b/spring-cloud-config-sample/src/test/resources/config-repo/bar.properties index 7daacd5d..ae3cdf5b 100644 --- a/spring-cloud-config-sample/src/test/resources/config-repo/bar.properties +++ b/spring-cloud-config-sample/src/test/resources/config-repo/bar.properties @@ -1 +1 @@ -foo: bar \ No newline at end of file +foo:bar diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/git/COMMIT_EDITMSG b/spring-cloud-config-sample/src/test/resources/config-repo/git/COMMIT_EDITMSG new file mode 100644 index 00000000..c8fcd951 --- /dev/null +++ b/spring-cloud-config-sample/src/test/resources/config-repo/git/COMMIT_EDITMSG @@ -0,0 +1 @@ +Updated diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/git/index b/spring-cloud-config-sample/src/test/resources/config-repo/git/index index 4874f2936079a3760b34d7dba2fa815209c2b257..5ede6d6c8080cb172876ad8756df95b0a7d6797f 100644 GIT binary patch literal 225 zcmZ?q402{*U|<5_n23;_28G97foYSyuNWAanHgKyix?OhmoP9ezkpx{>8gw+yH9Yt z9BQwqQ)c@=|N1@CGa(H8i3J5YnaPPInfZBomAN@U13~5pElCQ8(Gc_4V$jUvSZ8xT zy5qlwbUjC*v&NjFrL0v<6%2eyiA8z^MfnA(MJ1W3#X#d2LV{dffs`bJk%9r&!pV(a q{Qfj7lAN}s>OQ01N7i#UIdjUztl4H6?Gx6wc)fFjm4%wz%fA2~1WI54 literal 192 zcmZ?q402{*U|<5_;9Gy!sy&%f2%{MoIG7pujJX&X8kaCIFu#Cc2AOMXj 1406860717 -0700 +7df4a26d5437d9d4090cd5809967f870444cde8f b51bc19694589d21c06bab8a4f14660b3303d7b0 Marcin Grzejszczak 1549359437 +0100 commit: Updated diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/git/logs/refs/heads/raw b/spring-cloud-config-sample/src/test/resources/config-repo/git/logs/refs/heads/raw index c6423ee9..4c410395 100644 --- a/spring-cloud-config-sample/src/test/resources/config-repo/git/logs/refs/heads/raw +++ b/spring-cloud-config-sample/src/test/resources/config-repo/git/logs/refs/heads/raw @@ -1 +1,2 @@ 0000000000000000000000000000000000000000 7df4a26d5437d9d4090cd5809967f870444cde8f Dave Syer 1406860717 -0700 +7df4a26d5437d9d4090cd5809967f870444cde8f b51bc19694589d21c06bab8a4f14660b3303d7b0 Marcin Grzejszczak 1549359437 +0100 commit: Updated diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/git/objects/7a/68a4bbc80b44c287787e2306ff9fd7de35cc54 b/spring-cloud-config-sample/src/test/resources/config-repo/git/objects/7a/68a4bbc80b44c287787e2306ff9fd7de35cc54 new file mode 100644 index 0000000000000000000000000000000000000000..cd40d0e050f4052321e773f60f695b57ff7ce5eb GIT binary patch literal 43 zcmV+`0M!3@0ZYosPf{>4XUNP;%eUfEP)N(qw^B$-EaECkEVoi9DJo6n0sy?O3Z$+9 B5~2VA literal 0 HcmV?d00001 diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/git/objects/a1/9381f44efc80a21996b47adf012ef105ced909 b/spring-cloud-config-sample/src/test/resources/config-repo/git/objects/a1/9381f44efc80a21996b47adf012ef105ced909 new file mode 100644 index 0000000000000000000000000000000000000000..be1e3f09427d876cb2efe04550d77fc0e182392a GIT binary patch literal 97 zcmV-n0G|JN0V^p=O;xZkWiT`_Ff%bxNGvGG$xKcx$;{8wtIW+|sLEKf`vkYkq4tV8 zWw!tGuirC069QG5lvt!!P?TSgT2zvmTFkJ{=6-a?e+}t+jzVXRIYmoZtC%VPH~Aw4 DYYZ(O literal 0 HcmV?d00001 diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 b/spring-cloud-config-sample/src/test/resources/config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 new file mode 100644 index 0000000000000000000000000000000000000000..8e49e7509f7e7d9160992d80ce2f4a3af9c14c2b GIT binary patch literal 23 fcmbkYbP13CAO9B7@ literal 0 HcmV?d00001 diff --git a/spring-cloud-config-sample/src/test/resources/config-repo/git/refs/heads/raw b/spring-cloud-config-sample/src/test/resources/config-repo/git/refs/heads/raw index 4389eb3a..95f13194 100644 --- a/spring-cloud-config-sample/src/test/resources/config-repo/git/refs/heads/raw +++ b/spring-cloud-config-sample/src/test/resources/config-repo/git/refs/heads/raw @@ -1 +1 @@ -7df4a26d5437d9d4090cd5809967f870444cde8f +b51bc19694589d21c06bab8a4f14660b3303d7b0 diff --git a/spring-cloud-config-sample/src/test/resources/server.yml b/spring-cloud-config-sample/src/test/resources/server.yml index 84ae4e71..504a9a57 100644 --- a/spring-cloud-config-sample/src/test/resources/server.yml +++ b/spring-cloud-config-sample/src/test/resources/server.yml @@ -13,4 +13,4 @@ spring: server: port: 8888 management: - contextPath: /admin \ No newline at end of file + contextPath: /admin diff --git a/spring-cloud-config-server/pom.xml b/spring-cloud-config-server/pom.xml index 17542e9a..86dbce5b 100644 --- a/spring-cloud-config-server/pom.xml +++ b/spring-cloud-config-server/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 spring-cloud-config-server @@ -103,7 +104,8 @@ UTF-8 - org.springframework.cloud.config.server.ConfigServerApplication + org.springframework.cloud.config.server.ConfigServerApplication + diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ConfigServerApplication.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ConfigServerApplication.java index 6f026817..842669b9 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ConfigServerApplication.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ConfigServerApplication.java @@ -1,9 +1,30 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; +/** + * Configuration server application. + * + * @author Dave Syer + */ @Configuration @EnableAutoConfiguration @EnableConfigServer diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/EnableConfigServer.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/EnableConfigServer.java index b092791d..aa29e327 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/EnableConfigServer.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/EnableConfigServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.config.server; -import org.springframework.cloud.config.server.config.ConfigServerConfiguration; -import org.springframework.context.annotation.Import; +package org.springframework.cloud.config.server; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -24,6 +22,9 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.cloud.config.server.config.ConfigServerConfiguration; +import org.springframework.context.annotation.Import; + /** * @author Dave Syer * @author diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/bootstrap/ConfigServerBootstrapApplicationListener.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/bootstrap/ConfigServerBootstrapApplicationListener.java index e628961a..6996dbbb 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/bootstrap/ConfigServerBootstrapApplicationListener.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/bootstrap/ConfigServerBootstrapApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,32 +45,36 @@ import org.springframework.core.env.PropertySource; * @author Dave Syer * */ -public class ConfigServerBootstrapApplicationListener implements -ApplicationListener, Ordered { +public class ConfigServerBootstrapApplicationListener + implements ApplicationListener, Ordered { + /** + * Default order of the bootstrap application listener. + */ public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 4; private int order = DEFAULT_ORDER; - private PropertySource propertySource = new MapPropertySource( - "configServerClient", Collections. singletonMap( - "spring.cloud.config.enabled", "false")); - - public void setOrder(int order) { - this.order = order; - } + private PropertySource propertySource = new MapPropertySource("configServerClient", + Collections.singletonMap("spring.cloud.config.enabled", + "false")); @Override public int getOrder() { return this.order; } + public void setOrder(int order) { + this.order = order; + } + @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); if (!environment.resolvePlaceholders("${spring.cloud.config.enabled:false}") .equalsIgnoreCase("true")) { - if (!environment.getPropertySources().contains(this.propertySource.getName())) { + if (!environment.getPropertySources() + .contains(this.propertySource.getName())) { environment.getPropertySources().addLast(this.propertySource); } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/bootstrap/ConfigServerBootstrapConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/bootstrap/ConfigServerBootstrapConfiguration.java index f80631af..81544a01 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/bootstrap/ConfigServerBootstrapConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/bootstrap/ConfigServerBootstrapConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.bootstrap; import org.springframework.beans.factory.annotation.Autowired; @@ -29,11 +30,10 @@ import org.springframework.context.annotation.Import; import org.springframework.util.StringUtils; /** - * Bootstrap configuration to fetch external configuration from a (possibly - * remote) {@link EnvironmentRepository}. Off by default because it can delay - * startup, but can be enabled with - * spring.cloud.config.server.bootstrap=true. This would be useful, - * for example, if the config server were embedded in another app that wanted to + * Bootstrap configuration to fetch external configuration from a (possibly remote) + * {@link EnvironmentRepository}. Off by default because it can delay startup, but can be + * enabled with spring.cloud.config.server.bootstrap=true. This would be + * useful, for example, if the config server were embedded in another app that wanted to * be configured from the same repository as all the other clients. * * @author Dave Syer @@ -58,14 +58,15 @@ public class ConfigServerBootstrapConfiguration { @Bean public EnvironmentRepositoryPropertySourceLocator environmentRepositoryPropertySourceLocator() { - return new EnvironmentRepositoryPropertySourceLocator(this.repository, this.client.getName(), - this.client.getProfile(), getDefaultLabel()); + return new EnvironmentRepositoryPropertySourceLocator(this.repository, + this.client.getName(), this.client.getProfile(), getDefaultLabel()); } private String getDefaultLabel() { if (StringUtils.hasText(this.client.getLabel())) { return this.client.getLabel(); - } else if (StringUtils.hasText(this.server.getDefaultLabel())) { + } + else if (StringUtils.hasText(this.server.getDefaultLabel())) { return this.server.getDefaultLabel(); } return null; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeEnvironmentBeanFactoryPostProcessor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeEnvironmentBeanFactoryPostProcessor.java index fa817748..5e625752 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeEnvironmentBeanFactoryPostProcessor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeEnvironmentBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.composite; import java.lang.reflect.Type; @@ -31,12 +32,14 @@ import org.springframework.cloud.config.server.support.EnvironmentRepositoryProp import org.springframework.core.env.Environment; /** - * A {@link BeanFactoryPostProcessor} to register {@link EnvironmentRepository} {@link BeanDefinition}s based on the - * composite list configuration. + * A {@link BeanFactoryPostProcessor} to register {@link EnvironmentRepository} + * {@link BeanDefinition}s based on the composite list configuration. * * @author Dylan Roberts */ -public class CompositeEnvironmentBeanFactoryPostProcessor implements BeanFactoryPostProcessor { +public class CompositeEnvironmentBeanFactoryPostProcessor + implements BeanFactoryPostProcessor { + private Environment environment; public CompositeEnvironmentBeanFactoryPostProcessor(Environment environment) { @@ -44,35 +47,40 @@ public class CompositeEnvironmentBeanFactoryPostProcessor implements BeanFactory } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - List typePropertyList = CompositeUtils.getCompositeTypeList(environment); - for(int i = 0; i < typePropertyList.size(); i++) { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) + throws BeansException { + List typePropertyList = CompositeUtils + .getCompositeTypeList(this.environment); + for (int i = 0; i < typePropertyList.size(); i++) { String type = typePropertyList.get(i); String factoryName = CompositeUtils.getFactoryName(type, beanFactory); - - Type[] factoryTypes = CompositeUtils.getEnvironmentRepositoryFactoryTypeParams(beanFactory, factoryName); - Class propertiesClass = - (Class) factoryTypes[1]; - EnvironmentRepositoryProperties properties = bindProperties(i, propertiesClass, environment); + Type[] factoryTypes = CompositeUtils + .getEnvironmentRepositoryFactoryTypeParams(beanFactory, factoryName); + Class propertiesClass; + propertiesClass = (Class) factoryTypes[1]; + EnvironmentRepositoryProperties properties = bindProperties(i, + propertiesClass, this.environment); AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition(EnvironmentRepository.class) .setFactoryMethodOnBean("build", factoryName) - .addConstructorArgValue(properties) - .getBeanDefinition(); + .addConstructorArgValue(properties).getBeanDefinition(); String beanName = String.format("%s-env-repo%d", type, i); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; registry.registerBeanDefinition(beanName, beanDefinition); } } - private

P bindProperties( - int index, Class

propertiesClass, Environment environment) { + private

P bindProperties(int index, + Class

propertiesClass, Environment environment) { Binder binder = Binder.get(environment); - String environmentConfigurationPropertyName = String.format("spring.cloud.config.server.composite[%d]", index); - P properties = binder.bind(environmentConfigurationPropertyName, propertiesClass).orElseCreate(propertiesClass); + String environmentConfigurationPropertyName = String + .format("spring.cloud.config.server.composite[%d]", index); + P properties = binder.bind(environmentConfigurationPropertyName, propertiesClass) + .orElseCreate(propertiesClass); properties.setOrder(index + 1); return properties; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeUtils.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeUtils.java index 1f6879e4..00e23d8a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeUtils.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.composite; import java.lang.reflect.AnnotatedType; @@ -34,60 +35,81 @@ import org.springframework.core.type.MethodMetadata; /** * @author Dylan Roberts */ -public class CompositeUtils { +public final class CompositeUtils { - /** - * Returns list of values of the `type` field from the `spring.cloud.config.server.composite` collection. - */ - public static List getCompositeTypeList(Environment environment) { - return Binder.get(environment) - .bind("spring.cloud.config.server", CompositeConfig.class) - .get().getComposite().stream() - .map(map -> (String)map.get("type")) - .collect(Collectors.toList()); - } + private CompositeUtils() { + throw new IllegalStateException("Can't instantiate a utility class"); + } - static class CompositeConfig { - List> composite; + /** + * Returns list of values of the `type` field from the + * `spring.cloud.config.server.composite` collection. + * @param environment Spring Environment + * @return list of matching types + */ + public static List getCompositeTypeList(Environment environment) { + return Binder.get(environment) + .bind("spring.cloud.config.server", CompositeConfig.class).get() + .getComposite().stream().map(map -> (String) map.get("type")) + .collect(Collectors.toList()); + } - public List> getComposite() { - return composite; - } + /** + * Given a type of EnvironmentRepository (git, svn, native, etc...) returns the name + * of the factory bean. See {@link #getCompositeTypeList(Environment)} + * @param type type of a repository + * @param beanFactory Spring Bean Factory + * @return name of the factory bean + */ + public static String getFactoryName(String type, + ConfigurableListableBeanFactory beanFactory) { + String[] factoryNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( + beanFactory, EnvironmentRepositoryFactory.class, true, false); + return Arrays.stream(factoryNames).filter(n -> n.startsWith(type)).findFirst() + .orElse(null); + } - public void setComposite(List> composite) { - this.composite = composite; - } - } + /** + * Given a Factory Name return the generic type parameters of the factory (The actual + * repository class, and its properties class). + * @param beanFactory Spring Bean Factory + * @param factoryName name of the factory + * @return generic type params of the factory + */ + public static Type[] getEnvironmentRepositoryFactoryTypeParams( + ConfigurableListableBeanFactory beanFactory, String factoryName) { + MethodMetadata methodMetadata = (MethodMetadata) beanFactory + .getBeanDefinition(factoryName).getSource(); + Class factoryClass = null; + try { + factoryClass = Class.forName(methodMetadata.getReturnTypeName()); + } + catch (ClassNotFoundException e) { + throw new IllegalStateException(e); + } + Optional annotatedFactoryType = Arrays + .stream(factoryClass.getAnnotatedInterfaces()).filter(i -> { + ParameterizedType parameterizedType = (ParameterizedType) i.getType(); + return parameterizedType.getRawType() + .equals(EnvironmentRepositoryFactory.class); + }).findFirst(); + ParameterizedType factoryParameterizedType = (ParameterizedType) annotatedFactoryType + .orElse(factoryClass.getAnnotatedSuperclass()).getType(); + return factoryParameterizedType.getActualTypeArguments(); + } - /** - * Given a type of EnvironmentRepository (git, svn, native, etc...) returns the name of the factory bean. - * See {@link #getCompositeTypeList(Environment)} - */ - public static String getFactoryName(String type, ConfigurableListableBeanFactory beanFactory) { - String[] factoryNames = BeanFactoryUtils - .beanNamesForTypeIncludingAncestors(beanFactory, EnvironmentRepositoryFactory.class, true, false); - return Arrays.stream(factoryNames).filter(n -> n.startsWith(type)).findFirst().orElse(null); - } + static class CompositeConfig { - /** - * Given a Factory Name return the generic type parameters of the factory (The actual repository class, and its properties class)o - */ - public static Type[] getEnvironmentRepositoryFactoryTypeParams(ConfigurableListableBeanFactory beanFactory, String factoryName) { - MethodMetadata methodMetadata = (MethodMetadata) beanFactory.getBeanDefinition(factoryName).getSource(); - Class factoryClass = null; - try { - factoryClass = Class.forName(methodMetadata.getReturnTypeName()); - } catch (ClassNotFoundException e) { - throw new IllegalStateException(e); - } - Optional annotatedFactoryType = Arrays.stream(factoryClass.getAnnotatedInterfaces()) - .filter(i -> { - ParameterizedType parameterizedType = (ParameterizedType) i.getType(); - return parameterizedType.getRawType().equals(EnvironmentRepositoryFactory.class); - }).findFirst(); - ParameterizedType factoryParameterizedType = (ParameterizedType) annotatedFactoryType - .orElse(factoryClass.getAnnotatedSuperclass()).getType(); - return factoryParameterizedType.getActualTypeArguments(); - } + List> composite; + + public List> getComposite() { + return this.composite; + } + + public void setComposite(List> composite) { + this.composite = composite; + } + + } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/ConditionalOnMissingSearchPathLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/ConditionalOnMissingSearchPathLocator.java index 897c2276..bf858118 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/ConditionalOnMissingSearchPathLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/ConditionalOnMissingSearchPathLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.composite; import java.lang.annotation.Documented; @@ -31,4 +32,5 @@ import org.springframework.context.annotation.Conditional; @Documented @Conditional(OnSearchPathLocatorPresent.class) public @interface ConditionalOnMissingSearchPathLocator { + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/ConditionalOnSearchPathLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/ConditionalOnSearchPathLocator.java index 621f888c..c4091806 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/ConditionalOnSearchPathLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/ConditionalOnSearchPathLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.composite; import java.lang.annotation.Documented; @@ -31,4 +32,5 @@ import org.springframework.context.annotation.Conditional; @Documented @Conditional(OnSearchPathLocatorPresent.class) public @interface ConditionalOnSearchPathLocator { + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/OnSearchPathLocatorPresent.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/OnSearchPathLocatorPresent.java index e1798578..b86a7139 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/OnSearchPathLocatorPresent.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/OnSearchPathLocatorPresent.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.composite; import java.lang.reflect.Type; @@ -32,29 +33,40 @@ import org.springframework.core.type.AnnotatedTypeMetadata; * @author Dylan Roberts */ public class OnSearchPathLocatorPresent extends SpringBootCondition { + @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - List types = CompositeUtils.getCompositeTypeList(context.getEnvironment()); + public ConditionOutcome getMatchOutcome(ConditionContext context, + AnnotatedTypeMetadata metadata) { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + List types = CompositeUtils + .getCompositeTypeList(context.getEnvironment()); - // get EnvironmentRepository types from registered factories - List> repositoryTypes = new ArrayList<>(); - for (String type : types) { - String factoryName = CompositeUtils.getFactoryName(type, beanFactory); - Type[] actualTypeArguments = CompositeUtils.getEnvironmentRepositoryFactoryTypeParams(beanFactory, factoryName); - Class repositoryType = - (Class) actualTypeArguments[0]; - repositoryTypes.add(repositoryType); - } + // get EnvironmentRepository types from registered factories + List> repositoryTypes = new ArrayList<>(); + for (String type : types) { + String factoryName = CompositeUtils.getFactoryName(type, beanFactory); + Type[] actualTypeArguments = CompositeUtils + .getEnvironmentRepositoryFactoryTypeParams(beanFactory, factoryName); + Class repositoryType; + repositoryType = (Class) actualTypeArguments[0]; + repositoryTypes.add(repositoryType); + } + + boolean required = metadata + .isAnnotated(ConditionalOnSearchPathLocator.class.getName()); + boolean foundSearchPathLocator = repositoryTypes.stream() + .anyMatch(SearchPathLocator.class::isAssignableFrom); + if (required && !foundSearchPathLocator) { + return ConditionOutcome.noMatch( + ConditionMessage.forCondition(ConditionalOnSearchPathLocator.class) + .notAvailable(SearchPathLocator.class.getTypeName())); + } + if (!required && foundSearchPathLocator) { + return ConditionOutcome.noMatch(ConditionMessage + .forCondition(ConditionalOnMissingSearchPathLocator.class) + .available(SearchPathLocator.class.getTypeName())); + } + return ConditionOutcome.match(); + } - boolean required = metadata.isAnnotated(ConditionalOnSearchPathLocator.class.getName()); - boolean foundSearchPathLocator = repositoryTypes.stream().anyMatch(SearchPathLocator.class::isAssignableFrom); - if (required && !foundSearchPathLocator) { - return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSearchPathLocator.class).notAvailable(SearchPathLocator.class.getTypeName())); - } - if (!required && foundSearchPathLocator) { - return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingSearchPathLocator.class).available(SearchPathLocator.class.getTypeName())); - } - return ConditionOutcome.match(); - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/CompositeConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/CompositeConfiguration.java index 0b9f2918..aeac6945 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/CompositeConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/CompositeConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.config; import java.util.ArrayList; @@ -42,14 +43,14 @@ public class CompositeConfiguration { @Primary @ConditionalOnBean(SearchPathLocator.class) public SearchPathCompositeEnvironmentRepository searchPathCompositeEnvironmentRepository() { - return new SearchPathCompositeEnvironmentRepository(environmentRepos); + return new SearchPathCompositeEnvironmentRepository(this.environmentRepos); } @Bean @Primary @ConditionalOnMissingBean(SearchPathLocator.class) public CompositeEnvironmentRepository compositeEnvironmentRepository() { - return new CompositeEnvironmentRepository(environmentRepos); + return new CompositeEnvironmentRepository(this.environmentRepos); } @Autowired diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerAutoConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerAutoConfiguration.java index 0d36c9e6..7b2bf910 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerAutoConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT 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.springframework.cloud.config.server.config; @@ -28,8 +27,9 @@ import org.springframework.context.annotation.Import; @Configuration @ConditionalOnBean(ConfigServerConfiguration.Marker.class) @EnableConfigurationProperties(ConfigServerProperties.class) -@Import({ EnvironmentRepositoryConfiguration.class, CompositeConfiguration.class, ResourceRepositoryConfiguration.class, - ConfigServerEncryptionConfiguration.class, ConfigServerMvcConfiguration.class }) +@Import({ EnvironmentRepositoryConfiguration.class, CompositeConfiguration.class, + ResourceRepositoryConfiguration.class, ConfigServerEncryptionConfiguration.class, + ConfigServerMvcConfiguration.class }) public class ConfigServerAutoConfiguration { } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerConfiguration.java index 49465fcd..ed7bdc30 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT 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.springframework.cloud.config.server.config; @@ -25,10 +24,14 @@ import org.springframework.context.annotation.Configuration; */ @Configuration public class ConfigServerConfiguration { - class Marker {} @Bean public Marker enableConfigServerMarker() { return new Marker(); } + + class Marker { + + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerEncryptionConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerEncryptionConfiguration.java index 7200bb33..c6c96e16 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerEncryptionConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerEncryptionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import org.springframework.context.annotation.Configuration; @Configuration public class ConfigServerEncryptionConfiguration { - @Autowired(required=false) + @Autowired(required = false) private TextEncryptorLocator encryptor; @Autowired diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicator.java index c462f47a..3959546b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicator.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.config; import java.util.ArrayList; @@ -11,6 +27,7 @@ import javax.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -26,7 +43,7 @@ import org.springframework.util.CollectionUtils; public class ConfigServerHealthIndicator extends AbstractHealthIndicator { private static Log logger = LogFactory.getLog(ConfigServerHealthIndicator.class); - + private EnvironmentRepository environmentRepository; private Map repositories = new LinkedHashMap<>(); @@ -48,16 +65,19 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator { List> details = new ArrayList<>(); for (String name : this.repositories.keySet()) { Repository repository = this.repositories.get(name); - String application = (repository.getName() == null)? name : repository.getName(); + String application = (repository.getName() == null) ? name + : repository.getName(); String profiles = repository.getProfiles(); try { - Environment environment = this.environmentRepository.findOne(application, profiles, repository.getLabel()); + Environment environment = this.environmentRepository.findOne(application, + profiles, repository.getLabel()); HashMap detail = new HashMap<>(); detail.put("name", environment.getName()); detail.put("label", environment.getLabel()); - if (environment.getProfiles() != null && environment.getProfiles().length > 0) { + if (environment.getProfiles() != null + && environment.getProfiles().length > 0) { detail.put("profiles", Arrays.asList(environment.getProfiles())); } @@ -69,7 +89,8 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator { detail.put("sources", sources); } details.add(detail); - } catch (Exception e) { + } + catch (Exception e) { logger.debug("Could not read repository: " + application, e); HashMap map = new HashMap<>(); map.put("application", application); @@ -91,12 +112,19 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator { this.repositories = repositories; } + /** + * Repository properties. + */ public static class Repository { + private String name; + private String profiles = "default"; + private String label; - public Repository() { } + public Repository() { + } public String getName() { return this.name; @@ -121,5 +149,7 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator { public void setLabel(String label) { this.label = label; } + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerMvcConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerMvcConfiguration.java index 4990f17b..37d3859c 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerMvcConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerMvcConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,8 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.config; +import com.fasterxml.jackson.databind.ObjectMapper; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; @@ -30,8 +33,6 @@ import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import com.fasterxml.jackson.databind.ObjectMapper; - /** * @author Dave Syer * @author Roy Clarkson @@ -54,8 +55,10 @@ public class ConfigServerMvcConfiguration extends WebMvcConfigurerAdapter { } @Bean - public EnvironmentController environmentController(EnvironmentRepository envRepository, ConfigServerProperties server) { - EnvironmentController controller = new EnvironmentController(encrypted(envRepository, server), this.objectMapper); + public EnvironmentController environmentController( + EnvironmentRepository envRepository, ConfigServerProperties server) { + EnvironmentController controller = new EnvironmentController( + encrypted(envRepository, server), this.objectMapper); controller.setStripDocumentFromYaml(server.isStripDocumentFromYaml()); controller.setAcceptEmpty(server.isAcceptEmpty()); return controller; @@ -63,16 +66,19 @@ public class ConfigServerMvcConfiguration extends WebMvcConfigurerAdapter { @Bean @ConditionalOnBean(ResourceRepository.class) - public ResourceController resourceController(ResourceRepository repository, EnvironmentRepository envRepository, ConfigServerProperties server) { + public ResourceController resourceController(ResourceRepository repository, + EnvironmentRepository envRepository, ConfigServerProperties server) { ResourceController controller = new ResourceController(repository, encrypted(envRepository, server)); return controller; } - private EnvironmentRepository encrypted(EnvironmentRepository envRepository, ConfigServerProperties server) { + private EnvironmentRepository encrypted(EnvironmentRepository envRepository, + ConfigServerProperties server) { EnvironmentEncryptorEnvironmentRepository encrypted = new EnvironmentEncryptorEnvironmentRepository( envRepository, this.environmentEncryptor); encrypted.setOverrides(server.getOverrides()); return encrypted; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerProperties.java index 261c4574..a7b44d68 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.config; import java.util.LinkedHashMap; @@ -56,8 +57,9 @@ public class ConfigServerProperties { * should be returned in "native" form. */ private boolean stripDocumentFromYaml = true; + /** - * Flag to indicate that If HTTP 404 needs to be sent if Application is not Found + * Flag to indicate that If HTTP 404 needs to be sent if Application is not Found. */ private boolean acceptEmpty = true; @@ -72,7 +74,8 @@ public class ConfigServerProperties { private String defaultProfile = "default"; /** - * Decryption configuration for when server handles encrypted properties before sending them to clients. + * Decryption configuration for when server handles encrypted properties before + * sending them to clients. */ private Encrypt encrypt = new Encrypt(); @@ -119,7 +122,7 @@ public class ConfigServerProperties { public void setStripDocumentFromYaml(boolean stripDocumentFromYaml) { this.stripDocumentFromYaml = stripDocumentFromYaml; } - + public boolean isAcceptEmpty() { return this.acceptEmpty; } @@ -127,6 +130,7 @@ public class ConfigServerProperties { public void setAcceptEmpty(boolean acceptEmpty) { this.acceptEmpty = acceptEmpty; } + public String getDefaultApplicationName() { return this.defaultApplicationName; } @@ -143,7 +147,11 @@ public class ConfigServerProperties { this.defaultProfile = defaultProfile; } + /** + * Encryption properties. + */ public static class Encrypt { + /** * Enable decryption of environment properties before sending to client. */ @@ -156,5 +164,7 @@ public class ConfigServerProperties { public void setEnabled(boolean enabled) { this.enabled = enabled; } + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/CredhubConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/CredhubConfiguration.java index f1535f5d..43351a74 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/CredhubConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/CredhubConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.config; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EncryptionAutoConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EncryptionAutoConfiguration.java index 3782064f..c63cc84e 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EncryptionAutoConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EncryptionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,7 +73,7 @@ public class EncryptionAutoConfiguration { public EnvironmentEncryptor environmentEncryptor() { TextEncryptorLocator locator = this.locator; if (locator == null) { - locator = new SingleTextEncryptorLocator(encryptor); + locator = new SingleTextEncryptorLocator(this.encryptor); } return new CipherEnvironmentEncryptor(locator); } @@ -120,7 +120,7 @@ class SingleTextEncryptorConfiguration { @Bean public SingleTextEncryptorLocator textEncryptorLocator() { - return new SingleTextEncryptorLocator(encryptor); + return new SingleTextEncryptorLocator(this.encryptor); } } @@ -137,8 +137,8 @@ class DefaultTextEncryptorConfiguration { @Bean public TextEncryptor defaultTextEncryptor() { - if (locator != null) { - return new LocatorTextEncryptor(locator); + if (this.locator != null) { + return new LocatorTextEncryptor(this.locator); } if (StringUtils.hasText(this.key.getKey())) { return new EncryptorFactory(this.key.getSalt()).create(this.key.getKey()); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.java index 4077405a..06ab90d1 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.config; -import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Optional; +import javax.servlet.http.HttpServletRequest; + import org.apache.http.client.HttpClient; import org.eclipse.jgit.api.TransportConfigCallback; import org.tmatesoft.svn.core.SVNException; @@ -78,12 +80,16 @@ import org.springframework.jdbc.core.JdbcTemplate; * @author Alberto C. Ríos */ @Configuration -@EnableConfigurationProperties({ SvnKitEnvironmentProperties.class, CredhubEnvironmentProperties.class, - JdbcEnvironmentProperties.class, NativeEnvironmentProperties.class, VaultEnvironmentProperties.class }) -@Import({ CompositeRepositoryConfiguration.class, JdbcRepositoryConfiguration.class, VaultRepositoryConfiguration.class, - CredhubConfiguration.class, CredhubRepositoryConfiguration.class, SvnRepositoryConfiguration.class, - NativeRepositoryConfiguration.class, GitRepositoryConfiguration.class, DefaultRepositoryConfiguration.class }) +@EnableConfigurationProperties({ SvnKitEnvironmentProperties.class, + CredhubEnvironmentProperties.class, JdbcEnvironmentProperties.class, + NativeEnvironmentProperties.class, VaultEnvironmentProperties.class }) +@Import({ CompositeRepositoryConfiguration.class, JdbcRepositoryConfiguration.class, + VaultRepositoryConfiguration.class, CredhubConfiguration.class, + CredhubRepositoryConfiguration.class, SvnRepositoryConfiguration.class, + NativeRepositoryConfiguration.class, GitRepositoryConfiguration.class, + DefaultRepositoryConfiguration.class }) public class EnvironmentRepositoryConfiguration { + @Bean @ConditionalOnProperty(value = "spring.cloud.config.server.health.enabled", matchIfMissing = true) public ConfigServerHealthIndicator configServerHealthIndicator( @@ -98,13 +104,14 @@ public class EnvironmentRepositoryConfiguration { } @Configuration - @ConditionalOnProperty(value = "spring.cloud.config.server.consul.watch.enabled") + @ConditionalOnProperty("spring.cloud.config.server.consul.watch.enabled") protected static class ConsulEnvironmentWatchConfiguration { @Bean public EnvironmentWatch environmentWatch() { return new ConsulEnvironmentWatch(); } + } @Configuration @@ -115,72 +122,83 @@ public class EnvironmentRepositoryConfiguration { public EnvironmentWatch environmentWatch() { return new EnvironmentWatch.Default(); } + } - @Configuration - @ConditionalOnClass(TransportConfigCallback.class) - static class JGitFactoryConfig { + @Configuration + @ConditionalOnClass(TransportConfigCallback.class) + static class JGitFactoryConfig { - @Bean - public MultipleJGitEnvironmentRepositoryFactory gitEnvironmentRepositoryFactory( - ConfigurableEnvironment environment, ConfigServerProperties server, - Optional jgitHttpConnectionFactory, - Optional customTransportConfigCallback) { - return new MultipleJGitEnvironmentRepositoryFactory(environment, server, jgitHttpConnectionFactory, - customTransportConfigCallback); - } - } + @Bean + public MultipleJGitEnvironmentRepositoryFactory gitEnvironmentRepositoryFactory( + ConfigurableEnvironment environment, ConfigServerProperties server, + Optional jgitHttpConnectionFactory, + Optional customTransportConfigCallback) { + return new MultipleJGitEnvironmentRepositoryFactory(environment, server, + jgitHttpConnectionFactory, customTransportConfigCallback); + } - @Configuration - @ConditionalOnClass({ HttpClient.class, TransportConfigCallback.class }) - static class JGitHttpClientConfig { + } - @Bean - public ConfigurableHttpConnectionFactory httpClientConnectionFactory() { - return new HttpClientConfigurableHttpConnectionFactory(); - } - } + @Configuration + @ConditionalOnClass({ HttpClient.class, TransportConfigCallback.class }) + static class JGitHttpClientConfig { - @Configuration - @ConditionalOnClass(SVNException.class) - static class SvnFactoryConfig { - @Bean - public SvnEnvironmentRepositoryFactory svnEnvironmentRepositoryFactory(ConfigurableEnvironment environment, - ConfigServerProperties server) { - return new SvnEnvironmentRepositoryFactory(environment, server); - } - } + @Bean + public ConfigurableHttpConnectionFactory httpClientConnectionFactory() { + return new HttpClientConfigurableHttpConnectionFactory(); + } - @Configuration - static class VaultFactoryConfig { + } - @Bean - public VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory( - ObjectProvider request, EnvironmentWatch watch, - Optional vaultRestTemplateFactory) { - return new VaultEnvironmentRepositoryFactory(request, watch, vaultRestTemplateFactory); - } - } + @Configuration + @ConditionalOnClass(SVNException.class) + static class SvnFactoryConfig { - @Configuration - @ConditionalOnClass(HttpClient.class) - static class VaultHttpClientConfig { + @Bean + public SvnEnvironmentRepositoryFactory svnEnvironmentRepositoryFactory( + ConfigurableEnvironment environment, ConfigServerProperties server) { + return new SvnEnvironmentRepositoryFactory(environment, server); + } - @Bean - public VaultEnvironmentRepositoryFactory.VaultRestTemplateFactory vaultRestTemplateFactory() { - return new HttpClientVaultRestTemplateFactory(); - } - } + } - @Configuration - @ConditionalOnClass(JdbcTemplate.class) - static class JdbcFactoryConfig { - @Bean - @ConditionalOnBean(JdbcTemplate.class) - public JdbcEnvironmentRepositoryFactory jdbcEnvironmentRepositoryFactory(JdbcTemplate jdbc) { - return new JdbcEnvironmentRepositoryFactory(jdbc); - } - } + @Configuration + static class VaultFactoryConfig { + + @Bean + public VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory( + ObjectProvider request, EnvironmentWatch watch, + Optional vaultRestTemplateFactory) { + return new VaultEnvironmentRepositoryFactory(request, watch, + vaultRestTemplateFactory); + } + + } + + @Configuration + @ConditionalOnClass(HttpClient.class) + static class VaultHttpClientConfig { + + @Bean + public VaultEnvironmentRepositoryFactory.VaultRestTemplateFactory vaultRestTemplateFactory() { + return new HttpClientVaultRestTemplateFactory(); + } + + } + + @Configuration + @ConditionalOnClass(JdbcTemplate.class) + static class JdbcFactoryConfig { + + @Bean + @ConditionalOnBean(JdbcTemplate.class) + public JdbcEnvironmentRepositoryFactory jdbcEnvironmentRepositoryFactory( + JdbcTemplate jdbc) { + return new JdbcEnvironmentRepositoryFactory(jdbc); + } + + } @Configuration @ConditionalOnClass(CredHubOperations.class) @@ -189,24 +207,29 @@ public class EnvironmentRepositoryConfiguration { @Bean public CredhubEnvironmentRepositoryFactory credhubEnvironmentRepositoryFactory( Optional credHubOperations) { - return new CredhubEnvironmentRepositoryFactory(credHubOperations.orElse(null)); + return new CredhubEnvironmentRepositoryFactory( + credHubOperations.orElse(null)); } + } - @Configuration - static class NativeFactoryConfig { - @Bean - public NativeEnvironmentRepositoryFactory nativeEnvironmentRepositoryFactory(ConfigurableEnvironment environment, - ConfigServerProperties properties) { - return new NativeEnvironmentRepositoryFactory(environment, properties); - } - } + @Configuration + static class NativeFactoryConfig { + + @Bean + public NativeEnvironmentRepositoryFactory nativeEnvironmentRepositoryFactory( + ConfigurableEnvironment environment, ConfigServerProperties properties) { + return new NativeEnvironmentRepositoryFactory(environment, properties); + } + + } } @Configuration @ConditionalOnMissingBean(value = EnvironmentRepository.class, search = SearchStrategy.CURRENT) class DefaultRepositoryConfiguration { + @Autowired private ConfigurableEnvironment environment; @@ -218,10 +241,11 @@ class DefaultRepositoryConfiguration { @Bean public MultipleJGitEnvironmentRepository defaultEnvironmentRepository( - MultipleJGitEnvironmentRepositoryFactory gitEnvironmentRepositoryFactory, + MultipleJGitEnvironmentRepositoryFactory gitEnvironmentRepositoryFactory, MultipleJGitEnvironmentProperties environmentProperties) throws Exception { return gitEnvironmentRepositoryFactory.build(environmentProperties); } + } @Configuration @@ -230,15 +254,18 @@ class DefaultRepositoryConfiguration { class NativeRepositoryConfiguration { @Bean - public NativeEnvironmentRepository nativeEnvironmentRepository(NativeEnvironmentRepositoryFactory factory, + public NativeEnvironmentRepository nativeEnvironmentRepository( + NativeEnvironmentRepositoryFactory factory, NativeEnvironmentProperties environmentProperties) { - return factory.build(environmentProperties); + return factory.build(environmentProperties); } + } @Configuration @Profile("git") class GitRepositoryConfiguration extends DefaultRepositoryConfiguration { + } @Configuration @@ -246,10 +273,12 @@ class GitRepositoryConfiguration extends DefaultRepositoryConfiguration { class SvnRepositoryConfiguration { @Bean - public SvnKitEnvironmentRepository svnKitEnvironmentRepository(SvnKitEnvironmentProperties environmentProperties, - SvnEnvironmentRepositoryFactory factory) { + public SvnKitEnvironmentRepository svnKitEnvironmentRepository( + SvnKitEnvironmentProperties environmentProperties, + SvnEnvironmentRepositoryFactory factory) { return factory.build(environmentProperties); } + } @Configuration @@ -257,11 +286,12 @@ class SvnRepositoryConfiguration { class VaultRepositoryConfiguration { @Bean - public VaultEnvironmentRepository vaultEnvironmentRepository(VaultEnvironmentRepositoryFactory factory, - VaultEnvironmentProperties environmentProperties) - throws Exception { + public VaultEnvironmentRepository vaultEnvironmentRepository( + VaultEnvironmentRepositoryFactory factory, + VaultEnvironmentProperties environmentProperties) throws Exception { return factory.build(environmentProperties); } + } @Configuration @@ -269,10 +299,12 @@ class VaultRepositoryConfiguration { class CredhubRepositoryConfiguration { @Bean - public CredhubEnvironmentRepository credhubEnvironmentRepository(CredhubEnvironmentRepositoryFactory factory, - CredhubEnvironmentProperties environmentProperties) { + public CredhubEnvironmentRepository credhubEnvironmentRepository( + CredhubEnvironmentRepositoryFactory factory, + CredhubEnvironmentProperties environmentProperties) { return factory.build(environmentProperties); } + } @Configuration @@ -282,10 +314,12 @@ class JdbcRepositoryConfiguration { @Bean @ConditionalOnBean(JdbcTemplate.class) - public JdbcEnvironmentRepository jdbcEnvironmentRepository(JdbcEnvironmentRepositoryFactory factory, - JdbcEnvironmentProperties environmentProperties) { + public JdbcEnvironmentRepository jdbcEnvironmentRepository( + JdbcEnvironmentRepositoryFactory factory, + JdbcEnvironmentProperties environmentProperties) { return factory.build(environmentProperties); } + } @Configuration @@ -313,4 +347,5 @@ class CompositeRepositoryConfiguration { List environmentRepositories) throws Exception { return new CompositeEnvironmentRepository(environmentRepositories); } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ResourceRepositoryConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ResourceRepositoryConfiguration.java index 4498c772..6c96d352 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ResourceRepositoryConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ResourceRepositoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -38,4 +39,5 @@ public class ResourceRepositoryConfiguration { public ResourceRepository resourceRepository(SearchPathLocator service) { return new GenericResourceRepository(service); } -} \ No newline at end of file + +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/diagnostics/GitUriFailureAnalyzer.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/diagnostics/GitUriFailureAnalyzer.java index 1fc04280..8d63fe84 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/diagnostics/GitUriFailureAnalyzer.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/diagnostics/GitUriFailureAnalyzer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.diagnostics; import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; @@ -7,16 +23,25 @@ import org.springframework.cloud.config.server.environment.JGitEnvironmentReposi /** * @author Ryan Baxter */ -public class GitUriFailureAnalyzer extends AbstractFailureAnalyzer { +public class GitUriFailureAnalyzer + extends AbstractFailureAnalyzer { + /** + * Description of the failure. + */ public static final String DESCRIPTION = "Invalid config server configuration."; - public static final String ACTION = "If you are using the git profile, you need to set a Git URI in your " + - "configuration. If you are using a native profile and have spring.cloud.config.server.bootstrap=true, " + - "you need to use a composite configuration."; + + /** + * Action to take for git failure. + */ + public static final String ACTION = "If you are using the git profile, you need to set a Git URI in your " + + "configuration. If you are using a native profile and have spring.cloud.config.server.bootstrap=true, " + + "you need to use a composite configuration."; @Override - protected FailureAnalysis analyze(Throwable rootFailure, IllegalStateException cause) { - if(JGitEnvironmentRepository.MESSAGE.equalsIgnoreCase(cause.getMessage())) { + protected FailureAnalysis analyze(Throwable rootFailure, + IllegalStateException cause) { + if (JGitEnvironmentRepository.MESSAGE.equalsIgnoreCase(cause.getMessage())) { return new FailureAnalysis(DESCRIPTION, ACTION, cause); } return null; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptor.java index 0e5b40fa..b6ce5357 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.environment.PropertySource; @@ -64,24 +65,28 @@ public class CipherEnvironmentEncryptor implements EnvironmentEncryptor { for (Map.Entry entry : new LinkedHashSet<>(map.entrySet())) { Object key = entry.getKey(); String name = key.toString(); - if(entry.getValue() != null && entry.getValue().toString().startsWith("{cipher}")){ + if (entry.getValue() != null + && entry.getValue().toString().startsWith("{cipher}")) { String value = entry.getValue().toString(); map.remove(key); try { value = value.substring("{cipher}".length()); - value = encryptor.locate( - this.helper.getEncryptorKeys(name, StringUtils - .arrayToCommaDelimitedString(environment - .getProfiles()), value)).decrypt(this.helper.stripPrefix(value)); + value = encryptor + .locate(this.helper.getEncryptorKeys(name, + StringUtils.arrayToCommaDelimitedString( + environment.getProfiles()), + value)) + .decrypt(this.helper.stripPrefix(value)); } catch (Exception e) { value = ""; name = "invalid." + name; - String message = "Cannot decrypt key: " + key + " (" + e.getClass() - + ": " + e.getMessage() + ")"; + String message = "Cannot decrypt key: " + key + " (" + + e.getClass() + ": " + e.getMessage() + ")"; if (logger.isDebugEnabled()) { logger.debug(message, e); - } else if (logger.isWarnEnabled()) { + } + else if (logger.isWarnEnabled()) { logger.warn(message); } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EncryptionController.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EncryptionController.java index 1241cdd9..01281a29 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EncryptionController.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EncryptionController.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.encryption; import java.io.UnsupportedEncodingException; @@ -38,7 +39,6 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** @@ -125,8 +125,7 @@ public class EncryptionController { @RequestBody String data, @RequestHeader("Content-Type") MediaType type) { checkEncryptorInstalled(name, profiles); String input = stripFormData(data, type, false); - Map keys = this.helper.getEncryptorKeys(name, profiles, - input); + Map keys = this.helper.getEncryptorKeys(name, profiles, input); String textToEncrypt = this.helper.stripPrefix(input); String encrypted = this.helper.addPrefix(keys, this.encryptor.locate(keys).encrypt(textToEncrypt)); @@ -154,7 +153,7 @@ public class EncryptionController { logger.info("Decrypted cipher data"); return decrypted; } - catch (IllegalArgumentException|IllegalStateException e) { + catch (IllegalArgumentException | IllegalStateException e) { logger.error("Cannot decrypt key:" + name + ", value:" + data, e); throw new InvalidCipherException(); } @@ -217,7 +216,7 @@ public class EncryptionController { body.put("description", "No key was installed for encryption service"); return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); } - + @ExceptionHandler(EncryptionTooWeakException.class) public ResponseEntity> encryptionTooWeak() { Map body = new HashMap<>(); @@ -238,16 +237,20 @@ public class EncryptionController { @SuppressWarnings("serial") class KeyNotInstalledException extends RuntimeException { + } @SuppressWarnings("serial") class KeyNotAvailableException extends RuntimeException { + } @SuppressWarnings("serial") class EncryptionTooWeakException extends RuntimeException { + } @SuppressWarnings("serial") class InvalidCipherException extends RuntimeException { + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentEncryptor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentEncryptor.java index 623f5b9b..2bd6c920 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentEncryptor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentEncryptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,5 +26,7 @@ import org.springframework.cloud.config.environment.Environment; * */ public interface EnvironmentEncryptor { + Environment decrypt(Environment environment); + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelper.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelper.java index dca6c40c..d5f3e287 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelper.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,13 @@ class EnvironmentPrefixHelper { * Extract keys for looking up a {@link TextEncryptor} from the input text in the form * of a prefix of zero or many {name:value} pairs. The name and profiles * properties are always added to the keys (replacing any provided in the inputs). + * @param name application name + * @param profiles list of profiles + * @param text text to cipher + * @return encryptor keys */ - public Map getEncryptorKeys(String name, String profiles, String text) { + public Map getEncryptorKeys(String name, String profiles, + String text) { Map keys = new LinkedHashMap(); @@ -98,6 +103,9 @@ class EnvironmentPrefixHelper { * {name:value} pairs. The "name" and "profiles" keys are special in that * they are stripped since that information is always available when deriving the keys * in {@link #getEncryptorKeys(String, String, String)}. + * @param keys name, value pairs + * @param input input to append + * @return prefixed input */ public String addPrefix(Map keys, String input) { keys.remove(NAME); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/KeyStoreTextEncryptorLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/KeyStoreTextEncryptorLocator.java index 5192dea5..6edf5643 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/KeyStoreTextEncryptorLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/KeyStoreTextEncryptorLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,9 @@ public class KeyStoreTextEncryptorLocator implements TextEncryptorLocator { private SecretLocator secretLocator = new PassthruSecretLocator(); private RsaAlgorithm rsaAlgorithm = RsaAlgorithm.DEFAULT; + private boolean strong = false; + private String salt = "deadbeef"; public KeyStoreTextEncryptorLocator(KeyStoreKeyFactory keys, String defaultSecret, @@ -81,8 +83,9 @@ public class KeyStoreTextEncryptorLocator implements TextEncryptorLocator { public TextEncryptor locate(Map keys) { String alias = keys.containsKey(KEY) ? keys.get(KEY) : this.defaultAlias; String secret = keys.containsKey(SECRET) ? keys.get(SECRET) : this.defaultSecret; - return new RsaSecretEncryptor(this.keys.getKeyPair(alias, - this.secretLocator.locate(secret)), this.rsaAlgorithm, this.salt, this.strong); + return new RsaSecretEncryptor( + this.keys.getKeyPair(alias, this.secretLocator.locate(secret)), + this.rsaAlgorithm, this.salt, this.strong); } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/LocatorTextEncryptor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/LocatorTextEncryptor.java index 053c0b4d..b4ad7755 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/LocatorTextEncryptor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/LocatorTextEncryptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,20 +36,20 @@ public class LocatorTextEncryptor implements TextEncryptor { @Override public String encrypt(String text) { - Map keys = helper.getEncryptorKeys("configserver", "default", + Map keys = this.helper.getEncryptorKeys("configserver", "default", text); - return getLocator().locate(keys).encrypt(helper.stripPrefix(text)); + return getLocator().locate(keys).encrypt(this.helper.stripPrefix(text)); } private TextEncryptorLocator getLocator() { - return locator; + return this.locator; } @Override public String decrypt(String encryptedText) { - Map keys = helper.getEncryptorKeys("configserver", "default", + Map keys = this.helper.getEncryptorKeys("configserver", "default", encryptedText); - return getLocator().locate(keys).decrypt(helper.stripPrefix(encryptedText)); + return getLocator().locate(keys).decrypt(this.helper.stripPrefix(encryptedText)); } -} \ No newline at end of file +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/PassthruSecretLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/PassthruSecretLocator.java index af2a24d3..028f8de8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/PassthruSecretLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/PassthruSecretLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ public class PassthruSecretLocator implements SecretLocator { @Override public char[] locate(String secret) { - return secret==null ? new char[0] : secret.toCharArray(); + return secret == null ? new char[0] : secret.toCharArray(); } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/SecretLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/SecretLocator.java index 9e543fa3..3c19ec7e 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/SecretLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/SecretLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/SingleTextEncryptorLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/SingleTextEncryptorLocator.java index 210bf344..f60d631e 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/SingleTextEncryptorLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/SingleTextEncryptorLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/TextEncryptorLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/TextEncryptorLocator.java index b4b2134a..d69bb105 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/TextEncryptorLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/TextEncryptorLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,6 @@ import org.springframework.security.crypto.encrypt.TextEncryptor; */ public interface TextEncryptorLocator { - TextEncryptor locate(Map keys); + TextEncryptor locate(Map keys); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/AbstractScmEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/AbstractScmEnvironmentRepository.java index 7c2cf7ae..8ede428b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/AbstractScmEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/AbstractScmEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.cloud.config.environment.Environment; @@ -29,21 +30,24 @@ public abstract class AbstractScmEnvironmentRepository extends AbstractScmAccess implements EnvironmentRepository, SearchPathLocator, Ordered { private EnvironmentCleaner cleaner = new EnvironmentCleaner(); + private int order = Ordered.LOWEST_PRECEDENCE; public AbstractScmEnvironmentRepository(ConfigurableEnvironment environment) { super(environment); } - public AbstractScmEnvironmentRepository(ConfigurableEnvironment environment, AbstractScmAccessorProperties properties) { + public AbstractScmEnvironmentRepository(ConfigurableEnvironment environment, + AbstractScmAccessorProperties properties) { super(environment, properties); this.order = properties.getOrder(); } @Override - public synchronized Environment findOne(String application, String profile, String label) { - NativeEnvironmentRepository delegate = new NativeEnvironmentRepository(getEnvironment(), - new NativeEnvironmentProperties()); + public synchronized Environment findOne(String application, String profile, + String label) { + NativeEnvironmentRepository delegate = new NativeEnvironmentRepository( + getEnvironment(), new NativeEnvironmentProperties()); Locations locations = getLocations(application, profile, label); delegate.setSearchLocations(locations.getLocations()); Environment result = delegate.findOne(application, profile, ""); @@ -55,10 +59,11 @@ public abstract class AbstractScmEnvironmentRepository extends AbstractScmAccess @Override public int getOrder() { - return order; + return this.order; } public void setOrder(int order) { this.order = order; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java index c81c5668..ea23705a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.Collections; @@ -22,7 +23,9 @@ import org.springframework.cloud.config.environment.Environment; import org.springframework.core.OrderComparator; /** - * An {@link EnvironmentRepository} composed of multiple ordered {@link EnvironmentRepository}s. + * An {@link EnvironmentRepository} composed of multiple ordered + * {@link EnvironmentRepository}s. + * * @author Ryan Baxter */ public class CompositeEnvironmentRepository implements EnvironmentRepository { @@ -31,27 +34,34 @@ public class CompositeEnvironmentRepository implements EnvironmentRepository { /** * Creates a new {@link CompositeEnvironmentRepository}. - * @param environmentRepositories The list of {@link EnvironmentRepository}s to create the composite from. + * @param environmentRepositories The list of {@link EnvironmentRepository}s to create + * the composite from. */ - public CompositeEnvironmentRepository(List environmentRepositories) { - //Sort the environment repositories by the priority + public CompositeEnvironmentRepository( + List environmentRepositories) { + // Sort the environment repositories by the priority Collections.sort(environmentRepositories, OrderComparator.INSTANCE); this.environmentRepositories = environmentRepositories; } @Override public Environment findOne(String application, String profile, String label) { - Environment env = new Environment(application, new String[]{profile}, label, null, null); - if(environmentRepositories.size() == 1) { - Environment envRepo = environmentRepositories.get(0).findOne(application, profile, label); + Environment env = new Environment(application, new String[] { profile }, label, + null, null); + if (this.environmentRepositories.size() == 1) { + Environment envRepo = this.environmentRepositories.get(0).findOne(application, + profile, label); env.addAll(envRepo.getPropertySources()); env.setVersion(envRepo.getVersion()); env.setState(envRepo.getState()); - } else { - for (EnvironmentRepository repo : environmentRepositories) { - env.addAll(repo.findOne(application, profile, label).getPropertySources()); + } + else { + for (EnvironmentRepository repo : this.environmentRepositories) { + env.addAll( + repo.findOne(application, profile, label).getPropertySources()); } } return env; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactory.java index 2b162c4f..7880090d 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.eclipse.jgit.transport.http.HttpConnectionFactory; @@ -21,5 +22,8 @@ import org.eclipse.jgit.transport.http.HttpConnectionFactory; * @author Dylan Roberts */ public interface ConfigurableHttpConnectionFactory extends HttpConnectionFactory { - void addConfiguration(MultipleJGitEnvironmentProperties environmentProperties) throws Exception; + + void addConfiguration(MultipleJGitEnvironmentProperties environmentProperties) + throws Exception; + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConsulEnvironmentWatch.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConsulEnvironmentWatch.java index cafb973b..e88d3508 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConsulEnvironmentWatch.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConsulEnvironmentWatch.java @@ -1,11 +1,29 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.environment; import java.util.ArrayList; import java.util.List; + import javax.validation.constraints.NotNull; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; @@ -23,15 +41,25 @@ import org.springframework.web.client.RestTemplate; @ConfigurationProperties("spring.cloud.config.server.consul.watch") public class ConsulEnvironmentWatch implements EnvironmentWatch { + /** + * Consul index header name. + */ public static final String CONSUL_INDEX = "X-Consul-Index"; + + /** + * Consul token header name. + */ public static final String CONSUL_TOKEN = "X-Consul-Token"; - private static Log LOG = LogFactory.getLog(ConsulEnvironmentWatch.class); + /** + * Response types. + */ + public static final ParameterizedTypeReference> RESPONSE_TYPE = new ParameterizedTypeReference>() { + }; private static final String WATCH_URL = "{scheme}://{host}:{port}/v1/kv/{path}?keys&recurse&wait={wait}&index={index}"; - public static final ParameterizedTypeReference> RESPONSE_TYPE = new ParameterizedTypeReference>() { - }; + private static Log LOG = LogFactory.getLog(ConsulEnvironmentWatch.class); private RestTemplate restTemplate = new RestTemplate(); @@ -66,12 +94,12 @@ public class ConsulEnvironmentWatch implements EnvironmentWatch { params.add(String.valueOf(this.port)); params.add(this.path); params.add(this.wait); - params.add (StringUtils.hasText(state) ? state : ""); + params.add(StringUtils.hasText(state) ? state : ""); try { HttpHeaders headers = new HttpHeaders(); - if (StringUtils.hasText(token)) { - headers.add(CONSUL_TOKEN, token); + if (StringUtils.hasText(this.token)) { + headers.add(CONSUL_TOKEN, this.token); } HttpEntity request = new HttpEntity<>(headers); ResponseEntity> response = this.restTemplate.exchange(WATCH_URL, @@ -123,4 +151,5 @@ public class ConsulEnvironmentWatch implements EnvironmentWatch { public void setToken(String token) { this.token = token; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentProperties.java index 5136633d..81a7d4cb 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -28,7 +29,7 @@ public class CredhubEnvironmentProperties implements EnvironmentRepositoryProper private int order = Ordered.LOWEST_PRECEDENCE; public int getOrder() { - return order; + return this.order; } @Override @@ -36,4 +37,4 @@ public class CredhubEnvironmentProperties implements EnvironmentRepositoryProper this.order = order; } -} \ No newline at end of file +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepository.java index 08a91534..0c3d1bba 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.HashMap; @@ -50,7 +51,8 @@ public class CredhubEnvironmentRepository implements EnvironmentRepository { String[] profiles = StringUtils.commaDelimitedListToStringArray(profilesList); - Environment environment = new Environment(application, profiles, label, null, null); + Environment environment = new Environment(application, profiles, label, null, + null); Map properties = new HashMap<>(); for (String profile : profiles) { properties.putAll(findProperties(application, profile, label)); @@ -60,21 +62,17 @@ public class CredhubEnvironmentRepository implements EnvironmentRepository { return environment; } - private Map findProperties(String application, String profile, String label) { + private Map findProperties(String application, String profile, + String label) { String path = "/" + application + "/" + profile + "/" + label; - return credHubOperations - .credentials() - .findByPath(path) - .stream() + return this.credHubOperations.credentials().findByPath(path).stream() .map(credentialSummary -> credentialSummary.getName().getName()) - .map(name -> - credHubOperations - .credentials() - .getByName(new SimpleCredentialName(name), JsonCredential.class)) + .map(name -> this.credHubOperations.credentials() + .getByName(new SimpleCredentialName(name), JsonCredential.class)) .map(CredentialDetails::getValue) .flatMap(jsonCredential -> jsonCredential.entrySet().stream()) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b)); } -} \ No newline at end of file +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryFactory.java index b562812a..9c45da11 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.credhub.core.CredHubOperations; @@ -20,8 +21,8 @@ import org.springframework.credhub.core.CredHubOperations; /** * @author Alberto C. Ríos */ -public class CredhubEnvironmentRepositoryFactory implements EnvironmentRepositoryFactory { +public class CredhubEnvironmentRepositoryFactory implements + EnvironmentRepositoryFactory { private CredHubOperations credhubOperations; @@ -30,8 +31,9 @@ public class CredhubEnvironmentRepositoryFactory implements EnvironmentRepositor } @Override - public CredhubEnvironmentRepository build(CredhubEnvironmentProperties environmentProperties) { - return new CredhubEnvironmentRepository(credhubOperations); + public CredhubEnvironmentRepository build( + CredhubEnvironmentProperties environmentProperties) { + return new CredhubEnvironmentRepository(this.credhubOperations); } -} \ No newline at end of file +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentCleaner.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentCleaner.java index 192077cd..37462b2c 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentCleaner.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentCleaner.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.cloud.config.environment.Environment; @@ -35,4 +36,4 @@ public class EnvironmentCleaner { return result; } -} \ No newline at end of file +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java index 29a6f049..d90e7bff 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.IOException; @@ -29,7 +30,6 @@ import java.util.TreeMap; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.ObjectMapper; - import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Tag; @@ -66,9 +66,11 @@ import static org.springframework.cloud.config.server.support.EnvironmentPropert public class EnvironmentController { private EnvironmentRepository repository; + private ObjectMapper objectMapper; private boolean stripDocument = true; + private boolean acceptEmpty = true; public EnvironmentController(EnvironmentRepository repository) { @@ -84,7 +86,6 @@ public class EnvironmentController { /** * Flag to indicate that YAML documents which are not a map should be stripped of the * "document" prefix that is added by Spring (to facilitate conversion to Properties). - * * @param stripDocument the flag to set */ public void setStripDocumentFromYaml(boolean stripDocument) { @@ -92,14 +93,13 @@ public class EnvironmentController { } /** - * Flag to indicate that If HTTP 404 needs to be sent if Application is not Found - * + * Flag to indicate that If HTTP 404 needs to be sent if Application is not Found. * @param acceptEmpty the flag to set */ public void setAcceptEmpty(boolean acceptEmpty) { this.acceptEmpty = acceptEmpty; } - + @RequestMapping("/{name}/{profiles:.*[^-].*}") public Environment defaultLabel(@PathVariable String name, @PathVariable String profiles) { @@ -120,8 +120,9 @@ public class EnvironmentController { label = label.replace("(_)", "/"); } Environment environment = this.repository.findOne(name, profiles, label); - if(!acceptEmpty && (environment == null || environment.getPropertySources().isEmpty())){ - throw new EnvironmentNotFoundException("Profile Not found"); + if (!this.acceptEmpty + && (environment == null || environment.getPropertySources().isEmpty())) { + throw new EnvironmentNotFoundException("Profile Not found"); } return environment; } @@ -222,13 +223,14 @@ public class EnvironmentController { } /** - * Method {@code convertToMap} converts an {@code Environment} to a nested Map which represents a yml/json structure. - * + * Method {@code convertToMap} converts an {@code Environment} to a nested Map which + * represents a yml/json structure. * @param input the environment to be converted * @return the nested map containing the environment's properties */ private Map convertToMap(Environment input) { - // First use the current convertToProperties to get a flat Map from the environment + // First use the current convertToProperties to get a flat Map from the + // environment Map properties = convertToProperties(input); // The root map which holds all the first level properties @@ -331,11 +333,11 @@ public class EnvironmentController { } /** - * Class {@code PropertyNavigator} is used to navigate through the property key and create necessary Maps and Lists - * making up the nested structure to finally set the property value at the leaf node. + * Class {@code PropertyNavigator} is used to navigate through the property key and + * create necessary Maps and Lists making up the nested structure to finally set the + * property value at the leaf node. *

- * The following rules in yml/json are implemented: - *

+	 * The following rules in yml/json are implemented: 
 	 * 1. an array element can be:
 	 *    - a value (leaf)
 	 *    - a map
@@ -346,23 +348,23 @@ public class EnvironmentController {
 	 *    - an array
 	 * 
*/ - private static class PropertyNavigator { - - private enum NodeType {LEAF, MAP, ARRAY} + private static final class PropertyNavigator { private final String propertyKey; + private int currentPos; + private NodeType valueType; private PropertyNavigator(String propertyKey) { this.propertyKey = propertyKey; - currentPos = -1; - valueType = NodeType.MAP; + this.currentPos = -1; + this.valueType = NodeType.MAP; } private void setMapValue(Map map, Object value) { String key = getKey(); - if (NodeType.MAP.equals(valueType)) { + if (NodeType.MAP.equals(this.valueType)) { @SuppressWarnings("unchecked") Map nestedMap = (Map) map.get(key); if (nestedMap == null) { @@ -370,7 +372,8 @@ public class EnvironmentController { map.put(key, nestedMap); } setMapValue(nestedMap, value); - } else if (NodeType.ARRAY.equals(valueType)) { + } + else if (NodeType.ARRAY.equals(this.valueType)) { @SuppressWarnings("unchecked") List list = (List) map.get(key); if (list == null) { @@ -378,7 +381,8 @@ public class EnvironmentController { map.put(key, list); } setListValue(list, value); - } else { + } + else { map.put(key, value); } } @@ -389,7 +393,7 @@ public class EnvironmentController { while (list.size() <= index) { list.add(null); } - if (NodeType.MAP.equals(valueType)) { + if (NodeType.MAP.equals(this.valueType)) { @SuppressWarnings("unchecked") Map map = (Map) list.get(index); if (map == null) { @@ -397,7 +401,8 @@ public class EnvironmentController { list.set(index, map); } setMapValue(map, value); - } else if (NodeType.ARRAY.equals(valueType)) { + } + else if (NodeType.ARRAY.equals(this.valueType)) { @SuppressWarnings("unchecked") List nestedList = (List) list.get(index); if (nestedList == null) { @@ -405,43 +410,50 @@ public class EnvironmentController { list.set(index, nestedList); } setListValue(nestedList, value); - } else { + } + else { list.set(index, value); } } private int getIndex() { // Consider [ - int start = currentPos + 1; + int start = this.currentPos + 1; - for (int i = start; i < propertyKey.length(); i++) { - char c = propertyKey.charAt(i); + for (int i = start; i < this.propertyKey.length(); i++) { + char c = this.propertyKey.charAt(i); if (c == ']') { - currentPos = i; + this.currentPos = i; break; - } else if (!Character.isDigit(c)) { - throw new IllegalArgumentException("Invalid key: " + propertyKey); + } + else if (!Character.isDigit(c)) { + throw new IllegalArgumentException( + "Invalid key: " + this.propertyKey); } } // If no closing ] or if '[]' - if (currentPos < start || currentPos == start) { - throw new IllegalArgumentException("Invalid key: " + propertyKey); - } else { - int index = Integer.parseInt(propertyKey.substring(start, currentPos)); + if (this.currentPos < start || this.currentPos == start) { + throw new IllegalArgumentException("Invalid key: " + this.propertyKey); + } + else { + int index = Integer + .parseInt(this.propertyKey.substring(start, this.currentPos)); // Skip the closing ] - currentPos++; - if (currentPos == propertyKey.length()) { - valueType = NodeType.LEAF; - } else { - switch (propertyKey.charAt(currentPos)) { - case '.': - valueType = NodeType.MAP; - break; - case '[': - valueType = NodeType.ARRAY; - break; - default: - throw new IllegalArgumentException("Invalid key: " + propertyKey); + this.currentPos++; + if (this.currentPos == this.propertyKey.length()) { + this.valueType = NodeType.LEAF; + } + else { + switch (this.propertyKey.charAt(this.currentPos)) { + case '.': + this.valueType = NodeType.MAP; + break; + case '[': + this.valueType = NodeType.ARRAY; + break; + default: + throw new IllegalArgumentException( + "Invalid key: " + this.propertyKey); } } return index; @@ -450,28 +462,39 @@ public class EnvironmentController { private String getKey() { // Consider initial value or previous char '.' or '[' - int start = currentPos + 1; - for (int i = start; i < propertyKey.length(); i++) { - char currentChar = propertyKey.charAt(i); + int start = this.currentPos + 1; + for (int i = start; i < this.propertyKey.length(); i++) { + char currentChar = this.propertyKey.charAt(i); if (currentChar == '.') { - valueType = NodeType.MAP; - currentPos = i; + this.valueType = NodeType.MAP; + this.currentPos = i; break; - } else if (currentChar == '[') { - valueType = NodeType.ARRAY; - currentPos = i; + } + else if (currentChar == '[') { + this.valueType = NodeType.ARRAY; + this.currentPos = i; break; } } // If there's no delimiter then it's a key of a leaf - if (currentPos < start) { - currentPos = propertyKey.length(); - valueType = NodeType.LEAF; - // Else if we encounter '..' or '.[' or start of the property is . or [ then it's invalid - } else if (currentPos == start) { - throw new IllegalArgumentException("Invalid key: " + propertyKey); + if (this.currentPos < start) { + this.currentPos = this.propertyKey.length(); + this.valueType = NodeType.LEAF; + // Else if we encounter '..' or '.[' or start of the property is . or [ + // then it's invalid } - return propertyKey.substring(start, currentPos); + else if (this.currentPos == start) { + throw new IllegalArgumentException("Invalid key: " + this.propertyKey); + } + return this.propertyKey.substring(start, this.currentPos); } + + private enum NodeType { + + LEAF, MAP, ARRAY + + } + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepository.java index c653a75f..0c9dfcb8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,6 +34,7 @@ import org.springframework.cloud.config.server.encryption.EnvironmentEncryptor; public class EnvironmentEncryptorEnvironmentRepository implements EnvironmentRepository { private EnvironmentRepository delegate; + private EnvironmentEncryptor environmentEncryptor; private Map overrides = new LinkedHashMap<>(); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentNotFoundException.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentNotFoundException.java index 31908c89..02546f45 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentNotFoundException.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentNotFoundException.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** - * @author Chids - * + * @author Chidambaram Sundaram */ @SuppressWarnings("serial") -@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Application Not Found") +@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Application Not Found") public class EnvironmentNotFoundException extends RuntimeException { public EnvironmentNotFoundException(String string) { diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepository.java index 5d43fcc8..559b1bd5 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.cloud.config.environment.Environment; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryFactory.java index 9a862cb6..f8f55732 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.cloud.config.server.support.EnvironmentRepositoryProperties; /** + * @param {@link EnvironmentRepository} type + * @param

{@link EnvironmentRepositoryProperties} type * @author Dylan Roberts */ public interface EnvironmentRepositoryFactory { + T build(P environmentProperties) throws Exception; + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryPropertySourceLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryPropertySourceLocator.java index f4b2bb88..79c522cf 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryPropertySourceLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryPropertySourceLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.Map; @@ -25,15 +26,17 @@ import org.springframework.core.env.MapPropertySource; /** * A PropertySourceLocator that reads from an EnvironmentRepository. - * - * @author Dave Syer * + * @author Dave Syer */ public class EnvironmentRepositoryPropertySourceLocator implements PropertySourceLocator { private EnvironmentRepository repository; + private String name; + private String profiles; + private String label; public EnvironmentRepositoryPropertySourceLocator(EnvironmentRepository repository, @@ -45,10 +48,11 @@ public class EnvironmentRepositoryPropertySourceLocator implements PropertySourc } @Override - public org.springframework.core.env.PropertySource locate(Environment environment) { + public org.springframework.core.env.PropertySource locate( + Environment environment) { CompositePropertySource composite = new CompositePropertySource("configService"); - for (PropertySource source : repository.findOne(name, profiles, label) - .getPropertySources()) { + for (PropertySource source : this.repository + .findOne(this.name, this.profiles, this.label).getPropertySources()) { @SuppressWarnings("unchecked") Map map = (Map) source.getSource(); composite.addPropertySource(new MapPropertySource(source.getName(), map)); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentWatch.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentWatch.java index 6a624969..8eb965a5 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentWatch.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentWatch.java @@ -1,16 +1,38 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.environment; /** * @author Spencer Gibb */ public interface EnvironmentWatch { + String watch(String state); + /** + * Default implementation of the {@link EnvironmentWatch}. + */ class Default implements EnvironmentWatch { @Override public String watch(String state) { return null; } + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactory.java index 44b46cb6..2e3b25c0 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.IOException; @@ -20,7 +21,6 @@ import java.net.Proxy; import java.net.URL; import java.security.GeneralSecurityException; import java.util.ArrayList; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; @@ -44,104 +44,114 @@ import static java.util.stream.Collectors.toMap; /** * @author Dylan Roberts */ -public class HttpClientConfigurableHttpConnectionFactory implements ConfigurableHttpConnectionFactory { - Log log = LogFactory.getLog(getClass()); +public class HttpClientConfigurableHttpConnectionFactory + implements ConfigurableHttpConnectionFactory { - private static final String PLACEHOLDER_PATTERN = "\\{(\\w+)}"; + private static final String PLACEHOLDER_PATTERN = "\\{(\\w+)}"; - Map httpClientBuildersByUri = new LinkedHashMap<>(); + Log log = LogFactory.getLog(getClass()); - @Override - public void addConfiguration(MultipleJGitEnvironmentProperties environmentProperties) - throws GeneralSecurityException { - addHttpClient(environmentProperties); - for (JGitEnvironmentProperties repo : environmentProperties.getRepos().values()) { - addHttpClient(repo); - } - } + Map httpClientBuildersByUri = new LinkedHashMap<>(); - @Override - public HttpConnection create(URL url) throws IOException { - return create(url, null); - } + @Override + public void addConfiguration(MultipleJGitEnvironmentProperties environmentProperties) + throws GeneralSecurityException { + addHttpClient(environmentProperties); + for (JGitEnvironmentProperties repo : environmentProperties.getRepos().values()) { + addHttpClient(repo); + } + } - @Override - public HttpConnection create(URL url, Proxy proxy) throws IOException { - return new HttpClientConnection(url.toString(), null, lookupHttpClientBuilder(url).build()); - } + @Override + public HttpConnection create(URL url) throws IOException { + return create(url, null); + } - private void addHttpClient(JGitEnvironmentProperties properties) throws GeneralSecurityException { - if (properties.getUri() != null && properties.getUri().startsWith("http")) { - httpClientBuildersByUri.put(properties.getUri(), HttpClientSupport.builder(properties)); - } - } + @Override + public HttpConnection create(URL url, Proxy proxy) throws IOException { + return new HttpClientConnection(url.toString(), null, + lookupHttpClientBuilder(url).build()); + } - private HttpClientBuilder lookupHttpClientBuilder(final URL url) { - Map builderMap = httpClientBuildersByUri.entrySet().stream().filter(entry -> { - String key = entry.getKey(); - String spec = getUrlWithPlaceholders(url, key); - if (spec.equals(key)) { - return true; - } - int index = spec.lastIndexOf("/"); - while (index != -1) { - spec = spec.substring(0, index); - if (spec.equals(key)) { - return true; - } - index = spec.lastIndexOf("/"); - } - return false; - }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); + private void addHttpClient(JGitEnvironmentProperties properties) + throws GeneralSecurityException { + if (properties.getUri() != null && properties.getUri().startsWith("http")) { + this.httpClientBuildersByUri.put(properties.getUri(), + HttpClientSupport.builder(properties)); + } + } - if (builderMap.isEmpty()) { - log.warn(String.format("No custom http config found for URL: %s", url)); - return HttpClients.custom(); - } - if (builderMap.size() > 1) { - log.error(String.format("More than one git repo URL template matched URL: %s, proxy and skipSslValidation config won't be applied. Matched templates: %s", url, builderMap.keySet().stream().collect(Collectors.joining(", ")))); - return HttpClients.custom(); - } - return new ArrayList<>(builderMap.values()).get(0); - } + private HttpClientBuilder lookupHttpClientBuilder(final URL url) { + Map builderMap = this.httpClientBuildersByUri + .entrySet().stream().filter(entry -> { + String key = entry.getKey(); + String spec = getUrlWithPlaceholders(url, key); + if (spec.equals(key)) { + return true; + } + int index = spec.lastIndexOf("/"); + while (index != -1) { + spec = spec.substring(0, index); + if (spec.equals(key)) { + return true; + } + index = spec.lastIndexOf("/"); + } + return false; + }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); - private String getUrlWithPlaceholders(URL url, String key) { - String spec = url.toString(); - String[] tokens = key.split(PLACEHOLDER_PATTERN); - if (tokens.length > 1) { - List placeholders = getPlaceholders(key); - List values = getValues(spec, tokens); - if (placeholders.size() == values.size()) { - for (int i = 0; i < values.size(); i++) { - spec = spec.replace(values.get(i), String.format("{%s}", placeholders.get(i))); - } - } - } - return spec; - } + if (builderMap.isEmpty()) { + this.log.warn(String.format("No custom http config found for URL: %s", url)); + return HttpClients.custom(); + } + if (builderMap.size() > 1) { + this.log.error(String.format( + "More than one git repo URL template matched URL:" + + " %s, proxy and skipSslValidation config won't be applied. Matched templates: %s", + url, builderMap.keySet().stream().collect(Collectors.joining(", ")))); + return HttpClients.custom(); + } + return new ArrayList<>(builderMap.values()).get(0); + } - private List getValues(String spec, String[] tokens) { - List values = new LinkedList<>(); - for (String token : tokens) { - String[] valueTokens = spec.split(token); - if (!StringUtils.isEmpty(valueTokens[0])) { - values.add(valueTokens[0]); - } - if (valueTokens.length > 1) { - spec = valueTokens[1]; - } - } - return values; - } + private String getUrlWithPlaceholders(URL url, String key) { + String spec = url.toString(); + String[] tokens = key.split(PLACEHOLDER_PATTERN); + if (tokens.length > 1) { + List placeholders = getPlaceholders(key); + List values = getValues(spec, tokens); + if (placeholders.size() == values.size()) { + for (int i = 0; i < values.size(); i++) { + spec = spec.replace(values.get(i), + String.format("{%s}", placeholders.get(i))); + } + } + } + return spec; + } - private List getPlaceholders(String key) { - Pattern pattern = Pattern.compile(PLACEHOLDER_PATTERN); - Matcher matcher = pattern.matcher(key); - List placeholders = new LinkedList<>(); - while (matcher.find()) { - placeholders.add(matcher.group(1)); - } - return placeholders; - } + private List getValues(String spec, String[] tokens) { + List values = new LinkedList<>(); + for (String token : tokens) { + String[] valueTokens = spec.split(token); + if (!StringUtils.isEmpty(valueTokens[0])) { + values.add(valueTokens[0]); + } + if (valueTokens.length > 1) { + spec = valueTokens[1]; + } + } + return values; + } + + private List getPlaceholders(String key) { + Pattern pattern = Pattern.compile(PLACEHOLDER_PATTERN); + Matcher matcher = pattern.matcher(key); + List placeholders = new LinkedList<>(); + while (matcher.find()) { + placeholders.add(matcher.group(1)); + } + return placeholders; + } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientVaultRestTemplateFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientVaultRestTemplateFactory.java index dab95a6d..916de085 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientVaultRestTemplateFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientVaultRestTemplateFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.security.GeneralSecurityException; import org.apache.http.client.HttpClient; -import org.apache.http.impl.client.CloseableHttpClient; import org.springframework.cloud.config.server.support.HttpClientSupport; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; @@ -27,11 +27,14 @@ import org.springframework.web.client.RestTemplate; /** * @author Dylan Roberts */ -public class HttpClientVaultRestTemplateFactory implements VaultEnvironmentRepositoryFactory.VaultRestTemplateFactory { +public class HttpClientVaultRestTemplateFactory + implements VaultEnvironmentRepositoryFactory.VaultRestTemplateFactory { + + @Override + public RestTemplate build(VaultEnvironmentProperties environmentProperties) + throws GeneralSecurityException { + HttpClient httpClient = HttpClientSupport.builder(environmentProperties).build(); + return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); + } - @Override - public RestTemplate build(VaultEnvironmentProperties environmentProperties) throws GeneralSecurityException { - HttpClient httpClient = HttpClientSupport.builder(environmentProperties).build(); - return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentProperties.java index 065933a7..a1458e33 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.HashMap; import java.util.Map; + import javax.validation.constraints.Pattern; import org.springframework.cloud.config.server.proxy.ProxyHostProperties; @@ -28,20 +30,33 @@ import org.springframework.cloud.config.server.support.HttpEnvironmentRepository * @author Gareth Clay */ public class JGitEnvironmentProperties extends AbstractScmAccessorProperties - implements HttpEnvironmentRepositoryProperties { - private static final String DEFAULT_LABEL = "master"; + implements HttpEnvironmentRepositoryProperties { - /** Flag to indicate that the repository should be cloned on startup (not on demand). Generally leads to slower startup but faster first query. */ - private boolean cloneOnStart = false; + private static final String DEFAULT_LABEL = "master"; - /** Flag to indicate that the repository should force pull. If true discard any local changes and take from remote repository. */ - private boolean forcePull; + /** + * Flag to indicate that the repository should be cloned on startup (not on demand). + * Generally leads to slower startup but faster first query. + */ + private boolean cloneOnStart = false; - /** Timeout (in seconds) for obtaining HTTP or SSH connection (if applicable), defaults to 5 seconds. */ - private int timeout = 5; + /** + * Flag to indicate that the repository should force pull. If true discard any local + * changes and take from remote repository. + */ + private boolean forcePull; - /** Flag to indicate that the branch should be deleted locally if it's origin tracked branch was removed. */ - private boolean deleteUntrackedBranches = false; + /** + * Timeout (in seconds) for obtaining HTTP or SSH connection (if applicable), defaults + * to 5 seconds. + */ + private int timeout = 5; + + /** + * Flag to indicate that the branch should be deleted locally if it's origin tracked + * branch was removed. + */ + private boolean deleteUntrackedBranches = false; /** * Flag to indicate that SSL certificate validation should be bypassed when @@ -49,171 +64,177 @@ public class JGitEnvironmentProperties extends AbstractScmAccessorProperties */ private boolean skipSslValidation = false; - /** - * Time (in seconds) between refresh of the git repository - */ - private int refreshRate = 0; + /** + * Time (in seconds) between refresh of the git repository. + */ + private int refreshRate = 0; - /** - * Valid SSH private key. Must be set if ignoreLocalSshSettings is true and Git URI is SSH format. - */ - private String privateKey; + /** + * Valid SSH private key. Must be set if ignoreLocalSshSettings is true and Git URI is + * SSH format. + */ + private String privateKey; - /** - * One of ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, or ecdsa-sha2-nistp521. Must be set if hostKey is also set. - */ - private String hostKeyAlgorithm; + /** + * One of ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, or + * ecdsa-sha2-nistp521. Must be set if hostKey is also set. + */ + private String hostKeyAlgorithm; - /** - * Valid SSH host key. Must be set if hostKeyAlgorithm is also set. - */ - private String hostKey; + /** + * Valid SSH host key. Must be set if hostKeyAlgorithm is also set. + */ + private String hostKey; - /** - * Location of custom .known_hosts file. - */ - private String knownHostsFile; + /** + * Location of custom .known_hosts file. + */ + private String knownHostsFile; - /** - * Override server authentication method order. This should allow for evading login prompts if server has keyboard-interactive authentication before the publickey method. - */ - @Pattern(regexp = "([\\w -]+,)*([\\w -]+)") - private String preferredAuthentications; + /** + * Override server authentication method order. This should allow for evading login + * prompts if server has keyboard-interactive authentication before the publickey + * method. + */ + @Pattern(regexp = "([\\w -]+,)*([\\w -]+)") + private String preferredAuthentications; - /** - * If true, use property-based instead of file-based SSH config. - */ - private boolean ignoreLocalSshSettings; + /** + * If true, use property-based instead of file-based SSH config. + */ + private boolean ignoreLocalSshSettings; - /** - * If false, ignore errors with host key - */ - private boolean strictHostKeyChecking = true; + /** + * If false, ignore errors with host key. + */ + private boolean strictHostKeyChecking = true; - /** - * HTTP proxy configuration. - */ - private Map proxy = new HashMap<>(); + /** + * HTTP proxy configuration. + */ + private Map proxy = new HashMap<>(); - public JGitEnvironmentProperties() { - super(); - setDefaultLabel(DEFAULT_LABEL); - } + public JGitEnvironmentProperties() { + super(); + setDefaultLabel(DEFAULT_LABEL); + } - public boolean isCloneOnStart() { - return cloneOnStart; - } + public boolean isCloneOnStart() { + return this.cloneOnStart; + } - public void setCloneOnStart(boolean cloneOnStart) { - this.cloneOnStart = cloneOnStart; - } + public void setCloneOnStart(boolean cloneOnStart) { + this.cloneOnStart = cloneOnStart; + } - public boolean isForcePull() { - return forcePull; - } + public boolean isForcePull() { + return this.forcePull; + } - public void setForcePull(boolean forcePull) { - this.forcePull = forcePull; - } + public void setForcePull(boolean forcePull) { + this.forcePull = forcePull; + } - @Override - public int getTimeout() { - return timeout; - } + @Override + public int getTimeout() { + return this.timeout; + } - public void setTimeout(int timeout) { - this.timeout = timeout; - } + public void setTimeout(int timeout) { + this.timeout = timeout; + } - public boolean isDeleteUntrackedBranches() { - return deleteUntrackedBranches; - } + public boolean isDeleteUntrackedBranches() { + return this.deleteUntrackedBranches; + } - public void setDeleteUntrackedBranches(boolean deleteUntrackedBranches) { - this.deleteUntrackedBranches = deleteUntrackedBranches; - } + public void setDeleteUntrackedBranches(boolean deleteUntrackedBranches) { + this.deleteUntrackedBranches = deleteUntrackedBranches; + } - public int getRefreshRate() { - return refreshRate; - } + public int getRefreshRate() { + return this.refreshRate; + } - public void setRefreshRate(int refreshRate) { - this.refreshRate = refreshRate; - } + public void setRefreshRate(int refreshRate) { + this.refreshRate = refreshRate; + } - public String getPrivateKey() { - return privateKey; - } + public String getPrivateKey() { + return this.privateKey; + } - public void setPrivateKey(String privateKey) { - this.privateKey = privateKey; - } + public void setPrivateKey(String privateKey) { + this.privateKey = privateKey; + } - public String getHostKeyAlgorithm() { - return hostKeyAlgorithm; - } + public String getHostKeyAlgorithm() { + return this.hostKeyAlgorithm; + } - public void setHostKeyAlgorithm(String hostKeyAlgorithm) { - this.hostKeyAlgorithm = hostKeyAlgorithm; - } + public void setHostKeyAlgorithm(String hostKeyAlgorithm) { + this.hostKeyAlgorithm = hostKeyAlgorithm; + } - public String getHostKey() { - return hostKey; - } + public String getHostKey() { + return this.hostKey; + } - public void setHostKey(String hostKey) { - this.hostKey = hostKey; - } + public void setHostKey(String hostKey) { + this.hostKey = hostKey; + } - public String getKnownHostsFile() { - return knownHostsFile; - } + public String getKnownHostsFile() { + return this.knownHostsFile; + } - public void setKnownHostsFile(String knownHostsFile) { - this.knownHostsFile = knownHostsFile; - } + public void setKnownHostsFile(String knownHostsFile) { + this.knownHostsFile = knownHostsFile; + } - public String getPreferredAuthentications() { - return preferredAuthentications; - } + public String getPreferredAuthentications() { + return this.preferredAuthentications; + } - public void setPreferredAuthentications(String preferredAuthentications) { - this.preferredAuthentications = preferredAuthentications; - } + public void setPreferredAuthentications(String preferredAuthentications) { + this.preferredAuthentications = preferredAuthentications; + } - public boolean isIgnoreLocalSshSettings() { - return ignoreLocalSshSettings; - } + public boolean isIgnoreLocalSshSettings() { + return this.ignoreLocalSshSettings; + } - public void setIgnoreLocalSshSettings(boolean ignoreLocalSshSettings) { - this.ignoreLocalSshSettings = ignoreLocalSshSettings; - } + public void setIgnoreLocalSshSettings(boolean ignoreLocalSshSettings) { + this.ignoreLocalSshSettings = ignoreLocalSshSettings; + } - @Override - public boolean isStrictHostKeyChecking() { - return strictHostKeyChecking; - } + @Override + public boolean isStrictHostKeyChecking() { + return this.strictHostKeyChecking; + } - @Override - public void setStrictHostKeyChecking(boolean strictHostKeyChecking) { - this.strictHostKeyChecking = strictHostKeyChecking; - } + @Override + public void setStrictHostKeyChecking(boolean strictHostKeyChecking) { + this.strictHostKeyChecking = strictHostKeyChecking; + } - @Override - public boolean isSkipSslValidation() { - return skipSslValidation; - } + @Override + public boolean isSkipSslValidation() { + return this.skipSslValidation; + } - public void setSkipSslValidation(boolean skipSslValidation) { - this.skipSslValidation = skipSslValidation; - } + public void setSkipSslValidation(boolean skipSslValidation) { + this.skipSslValidation = skipSslValidation; + } - @Override - public Map getProxy() { - return proxy; - } + @Override + public Map getProxy() { + return this.proxy; + } + + public void setProxy( + Map proxy) { + this.proxy = proxy; + } - public void setProxy(Map proxy) { - this.proxy = proxy; - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java index e7c5ab5a..1460dcef 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.File; @@ -80,6 +81,9 @@ import static org.eclipse.jgit.transport.ReceiveCommand.Type.DELETE; public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository implements EnvironmentRepository, SearchPathLocator, InitializingBean { + /** + * Error message for URI for git repo. + */ public static final String MESSAGE = "You need to configure a uri for the git repository."; private static final String FILE_URI_PREFIX = "file:"; @@ -93,12 +97,12 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository private int timeout; /** - * Time (in seconds) between refresh of the git repository + * Time (in seconds) between refresh of the git repository. */ private int refreshRate = 0; /** - * Time of the last refresh of the git repository + * Time of the last refresh of the git repository. */ private long lastRefresh; @@ -128,10 +132,12 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository * changes and take from remote repository. */ private boolean forcePull; + private boolean initialized; /** - * Flag to indicate that the branch should be deleted locally if it's origin tracked branch was removed. + * Flag to indicate that the branch should be deleted locally if it's origin tracked + * branch was removed. */ private boolean deleteUntrackedBranches; @@ -141,7 +147,8 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository */ private boolean skipSslValidation; - public JGitEnvironmentRepository(ConfigurableEnvironment environment, JGitEnvironmentProperties properties) { + public JGitEnvironmentRepository(ConfigurableEnvironment environment, + JGitEnvironmentProperties properties) { super(environment, properties); this.cloneOnStart = properties.isCloneOnStart(); this.defaultLabel = properties.getDefaultLabel(); @@ -169,16 +176,15 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository } public int getRefreshRate() { - return refreshRate; + return this.refreshRate; } public void setRefreshRate(int refreshRate) { this.refreshRate = refreshRate; } - public TransportConfigCallback getTransportConfigCallback() { - return transportConfigCallback; + return this.transportConfigCallback; } public void setTransportConfigCallback( @@ -208,7 +214,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository } public boolean isForcePull() { - return forcePull; + return this.forcePull; } public void setForcePull(boolean forcePull) { @@ -216,7 +222,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository } public boolean isDeleteUntrackedBranches() { - return deleteUntrackedBranches; + return this.deleteUntrackedBranches; } public void setDeleteUntrackedBranches(boolean deleteUntrackedBranches) { @@ -224,7 +230,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository } public boolean isSkipSslValidation() { - return skipSslValidation; + return this.skipSslValidation; } public void setSkipSslValidation(boolean skipSslValidation) { @@ -244,8 +250,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository @Override public synchronized void afterPropertiesSet() throws Exception { - Assert.state(getUri() != null, - MESSAGE); + Assert.state(getUri() != null, MESSAGE); initialize(); if (this.cloneOnStart) { initClonedRepository(); @@ -254,6 +259,8 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository /** * Get the working directory ready. + * @param label label to refresh + * @return head id */ public String refresh(String label) { Git git = null; @@ -261,8 +268,9 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository git = createGitClient(); if (shouldPull(git)) { FetchResult fetchStatus = fetch(git, label); - if (deleteUntrackedBranches && fetchStatus != null) { - deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(), git); + if (this.deleteUntrackedBranches && fetchStatus != null) { + deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(), + git); } // checkout after fetch so we can get any new branches, tags, ect. checkout(git, label); @@ -301,19 +309,20 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository } } } - + private void tryMerge(Git git, String label) { try { if (isBranch(git, label)) { // merge results from fetch merge(git, label); if (!isClean(git, label)) { - logger.warn("The local repository is dirty or ahead of origin. Resetting" - + " it to origin/" + label + "."); + this.logger.warn( + "The local repository is dirty or ahead of origin. Resetting" + + " it to origin/" + label + "."); resetHard(git, label, LOCAL_BRANCH_REF_PREFIX + label); } } - } + } catch (GitAPIException e) { throw new NoSuchRepositoryException( "Cannot clone or checkout repository: " + getUri(), e); @@ -322,9 +331,8 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository /** * Clones the remote repository and then opens a connection to it. - * - * @throws GitAPIException - * @throws IOException + * @throws GitAPIException when cloning fails + * @throws IOException when repo opening fails */ private void initClonedRepository() throws GitAPIException, IOException { if (!getUri().startsWith(FILE_URI_PREFIX)) { @@ -343,12 +351,12 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository /** * Deletes local branches if corresponding remote branch was removed. - * * @param trackingRefUpdates list of tracking ref updates - * @param git git instance + * @param git git instance * @return list of deleted branches */ - private Collection deleteUntrackedLocalBranches(Collection trackingRefUpdates, Git git) { + private Collection deleteUntrackedLocalBranches( + Collection trackingRefUpdates, Git git) { if (CollectionUtils.isEmpty(trackingRefUpdates)) { return Collections.emptyList(); } @@ -358,8 +366,10 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository ReceiveCommand receiveCommand = trackingRefUpdate.asReceiveCommand(); if (receiveCommand.getType() == DELETE) { String localRefName = trackingRefUpdate.getLocalName(); - if (StringUtils.startsWithIgnoreCase(localRefName, LOCAL_BRANCH_REF_PREFIX)) { - String localBranchName = localRefName.substring(LOCAL_BRANCH_REF_PREFIX.length(), localRefName.length()); + if (StringUtils.startsWithIgnoreCase(localRefName, + LOCAL_BRANCH_REF_PREFIX)) { + String localBranchName = localRefName.substring( + LOCAL_BRANCH_REF_PREFIX.length(), localRefName.length()); branchesToDelete.add(localBranchName); } } @@ -370,23 +380,27 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository } try { - //make sure that deleted branch not a current one - checkout(git, defaultLabel); + // make sure that deleted branch not a current one + checkout(git, this.defaultLabel); return deleteBranches(git, branchesToDelete); - } catch (Exception ex) { + } + catch (Exception ex) { String message = format("Failed to delete %s branches.", branchesToDelete); warn(message, ex); return Collections.emptyList(); } } - private List deleteBranches(Git git, Collection branchesToDelete) throws GitAPIException { + private List deleteBranches(Git git, Collection branchesToDelete) + throws GitAPIException { DeleteBranchCommand deleteBranchCommand = git.branchDelete() .setBranchNames(branchesToDelete.toArray(new String[0])) - //local branch can contain data which is not merged to HEAD - force delete it anyway, since local copy should be R/O + // local branch can contain data which is not merged to HEAD - force + // delete it anyway, since local copy should be R/O .setForce(true); List resultList = deleteBranchCommand.call(); - logger.info(format("Deleted %s branches from %s branches to delete.", resultList, branchesToDelete)); + this.logger.info(format("Deleted %s branches from %s branches to delete.", + resultList, branchesToDelete)); return resultList; } @@ -405,7 +419,8 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository protected boolean shouldPull(Git git) throws GitAPIException { boolean shouldPull; - if (this.refreshRate > 0 && System.currentTimeMillis() - this.lastRefresh < (this.refreshRate * 1000)) { + if (this.refreshRate > 0 && System.currentTimeMillis() + - this.lastRefresh < (this.refreshRate * 1000)) { return false; } @@ -453,7 +468,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository FetchCommand fetch = git.fetch(); fetch.setRemote("origin"); fetch.setTagOpt(TagOpt.FETCH_TAGS); - fetch.setRemoveDeletedRefs(deleteUntrackedBranches); + fetch.setRemoveDeletedRefs(this.deleteUntrackedBranches); if (this.refreshRate > 0) { this.setLastRefresh(System.currentTimeMillis()); } @@ -463,7 +478,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository FetchResult result = fetch.call(); if (result.getTrackingRefUpdates() != null && result.getTrackingRefUpdates().size() > 0) { - logger.info("Fetched for remote " + label + " and found " + this.logger.info("Fetched for remote " + label + " and found " + result.getTrackingRefUpdates().size() + " updates"); } return result; @@ -522,7 +537,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository // The only way this can happen is if another JVM (e.g. one that // crashed earlier) created the lock. We can attempt to recover by // wiping the slate clean. - logger.info("Deleting stale JGit lock file at " + lock); + this.logger.info("Deleting stale JGit lock file at " + lock); lock.delete(); } if (new File(getWorkingDirectory(), ".git").exists()) { @@ -574,7 +589,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository return clone.call(); } catch (GitAPIException e) { - logger.warn("Error occured cloning to base directory.", e); + this.logger.warn("Error occured cloning to base directory.", e); deleteBaseDirIfExists(); throw e; } @@ -626,8 +641,10 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository private boolean isClean(Git git, String label) { StatusCommand status = git.status(); try { - BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(git.getRepository(), label); - boolean isBranchAhead = trackingStatus != null && trackingStatus.getAheadCount() > 0; + BranchTrackingStatus trackingStatus = BranchTrackingStatus + .of(git.getRepository(), label); + boolean isBranchAhead = trackingStatus != null + && trackingStatus.getAheadCount() > 0; return status.call().isClean() && !isBranchAhead; } catch (Exception e) { @@ -668,20 +685,20 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository } protected void warn(String message, Exception ex) { - logger.warn(message); - if (logger.isDebugEnabled()) { - logger.debug("Stacktrace for: " + message, ex); + this.logger.warn(message); + if (this.logger.isDebugEnabled()) { + this.logger.debug("Stacktrace for: " + message, ex); } } + public long getLastRefresh() { + return this.lastRefresh; + } + public void setLastRefresh(long lastRefresh) { this.lastRefresh = lastRefresh; } - public long getLastRefresh() { - return lastRefresh; - } - /** * Wraps the static method calls to {@link org.eclipse.jgit.api.Git} and * {@link org.eclipse.jgit.api.CloneCommand} allowing for easier unit testing. @@ -697,5 +714,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository CloneCommand command = Git.cloneRepository(); return command; } + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentProperties.java index 5a05b344..fe89cbd4 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -24,14 +25,17 @@ import org.springframework.core.Ordered; */ @ConfigurationProperties("spring.cloud.config.server.jdbc") public class JdbcEnvironmentProperties implements EnvironmentRepositoryProperties { - private static final String DEFAULT_SQL = "SELECT KEY, VALUE from PROPERTIES where APPLICATION=? and PROFILE=? and LABEL=?"; + + private static final String DEFAULT_SQL = "SELECT KEY, VALUE from PROPERTIES" + + " where APPLICATION=? and PROFILE=? and LABEL=?"; private int order = Ordered.LOWEST_PRECEDENCE - 10; - /** SQL used to query database for keys and values */ + + /** SQL used to query database for keys and values. */ private String sql = DEFAULT_SQL; public int getOrder() { - return order; + return this.order; } @Override @@ -40,10 +44,11 @@ public class JdbcEnvironmentProperties implements EnvironmentRepositoryPropertie } public String getSql() { - return sql; + return this.sql; } public void setSql(String sql) { this.sql = sql; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepository.java index 07e8baa0..a4eb98ab 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.sql.ResultSet; @@ -43,30 +44,35 @@ import org.springframework.util.StringUtils; * {application}-{profile}.properties, including all the encryption and * decryption, which will be applied as post-processing steps (i.e. not in this repository * directly). - * + * * @author Dave Syer * */ public class JdbcEnvironmentRepository implements EnvironmentRepository, Ordered { - private int order; + private final JdbcTemplate jdbc; - private String sql; + private final PropertiesResultSetExtractor extractor = new PropertiesResultSetExtractor(); - public JdbcEnvironmentRepository(JdbcTemplate jdbc, JdbcEnvironmentProperties properties) { + private int order; + + private String sql; + + public JdbcEnvironmentRepository(JdbcTemplate jdbc, + JdbcEnvironmentProperties properties) { this.jdbc = jdbc; this.order = properties.getOrder(); this.sql = properties.getSql(); } - public void setSql(String sql) { - this.sql = sql; - } - public String getSql() { return this.sql; } + public void setSql(String sql) { + this.sql = sql; + } + @Override public Environment findOne(String application, String profile, String label) { String config = application; @@ -87,12 +93,13 @@ public class JdbcEnvironmentRepository implements EnvironmentRepository, Ordered } List applications = new ArrayList(new LinkedHashSet<>( Arrays.asList(StringUtils.commaDelimitedListToStringArray(config)))); - List envs = new ArrayList(new LinkedHashSet<>(Arrays.asList(profiles))); + List envs = new ArrayList( + new LinkedHashSet<>(Arrays.asList(profiles))); Collections.reverse(applications); Collections.reverse(envs); for (String app : applications) { for (String env : envs) { - Map next = (Map) jdbc.query(this.sql, + Map next = (Map) this.jdbc.query(this.sql, new Object[] { app, env, label }, this.extractor); if (!next.isEmpty()) { environment.add(new PropertySource(app + "-" + env, next)); @@ -104,7 +111,7 @@ public class JdbcEnvironmentRepository implements EnvironmentRepository, Ordered @Override public int getOrder() { - return order; + return this.order; } public void setOrder(int order) { @@ -125,4 +132,4 @@ class PropertiesResultSetExtractor implements ResultSetExtractor { +public class JdbcEnvironmentRepositoryFactory implements + EnvironmentRepositoryFactory { + private JdbcTemplate jdbc; public JdbcEnvironmentRepositoryFactory(JdbcTemplate jdbc) { @@ -29,7 +31,9 @@ public class JdbcEnvironmentRepositoryFactory implements EnvironmentRepositoryFa } @Override - public JdbcEnvironmentRepository build(JdbcEnvironmentProperties environmentProperties) { - return new JdbcEnvironmentRepository(jdbc, environmentProperties); + public JdbcEnvironmentRepository build( + JdbcEnvironmentProperties environmentProperties) { + return new JdbcEnvironmentRepository(this.jdbc, environmentProperties); } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProperties.java index 72b7f3d6..e75505cc 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.LinkedHashMap; @@ -35,50 +36,59 @@ import org.springframework.validation.annotation.Validated; @HostKeyAlgoSupported @KnownHostsFileIsValid public class MultipleJGitEnvironmentProperties extends JGitEnvironmentProperties { - /** - * Map of repository identifier to location and other properties. - */ - private Map repos = new LinkedHashMap<>(); - public Map getRepos() { - return repos; - } + /** + * Map of repository identifier to location and other properties. + */ + private Map repos = new LinkedHashMap<>(); - public void setRepos(Map repos) { - this.repos = repos; - } + public Map getRepos() { + return this.repos; + } - public static class PatternMatchingJGitEnvironmentProperties extends JGitEnvironmentProperties { - /** - * Pattern to match on application name and profiles. - */ - private String[] pattern = new String[0]; - /** - * Name of repository (same as map key by default). - */ - private String name; + public void setRepos(Map repos) { + this.repos = repos; + } - public PatternMatchingJGitEnvironmentProperties() { - } + /** + * A {@link JGitEnvironmentProperties} that matches patterns. + */ + public static class PatternMatchingJGitEnvironmentProperties + extends JGitEnvironmentProperties { - public PatternMatchingJGitEnvironmentProperties(String uri) { - setUri(uri); - } + /** + * Pattern to match on application name and profiles. + */ + private String[] pattern = new String[0]; - public String[] getPattern() { - return pattern; - } + /** + * Name of repository (same as map key by default). + */ + private String name; - public void setPattern(String[] pattern) { - this.pattern = pattern; - } + public PatternMatchingJGitEnvironmentProperties() { + } - public String getName() { - return name; - } + public PatternMatchingJGitEnvironmentProperties(String uri) { + setUri(uri); + } + + public String[] getPattern() { + return this.pattern; + } + + public void setPattern(String[] pattern) { + this.pattern = pattern; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + } - public void setName(String name) { - this.name = name; - } - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepository.java index 44d4c53a..67c34d63 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.File; -import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import org.springframework.beans.BeanUtils; import org.springframework.cloud.config.environment.Environment; @@ -56,11 +55,10 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository private Map placeholders = new LinkedHashMap<>(); public MultipleJGitEnvironmentRepository(ConfigurableEnvironment environment, - MultipleJGitEnvironmentProperties properties) { + MultipleJGitEnvironmentProperties properties) { super(environment, properties); - properties.getRepos().forEach((name, props) -> - repos.put(name, new PatternMatchingJGitEnvironmentRepository(environment, props)) - ); + properties.getRepos().forEach((name, props) -> this.repos.put(name, + new PatternMatchingJGitEnvironmentRepository(environment, props))); } @Override @@ -98,10 +96,9 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository } repo.afterPropertiesSet(); } - if (!getBasedir().exists() && - !getBasedir().mkdirs()) { - throw new IllegalStateException( - "Basedir does not exist and can not be created: " + getBasedir()); + if (!getBasedir().exists() && !getBasedir().mkdirs()) { + throw new IllegalStateException( + "Basedir does not exist and can not be created: " + getBasedir()); } if (!getBasedir().getParentFile().canWrite()) { throw new IllegalStateException( @@ -110,14 +107,14 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository } } - public void setRepos(Map repos) { - this.repos.putAll(repos); - } - public Map getRepos() { return this.repos; } + public void setRepos(Map repos) { + this.repos.putAll(repos); + } + @Override public Locations getLocations(String application, String profile, String label) { for (PatternMatchingJGitEnvironmentRepository repository : this.repos.values()) { @@ -132,7 +129,7 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository } } catch (Exception e) { - if (logger.isDebugEnabled()) { + if (this.logger.isDebugEnabled()) { this.logger.debug("Cannot retrieve resource locations from " + candidate.getUri() + ", cause: (" + e.getClass().getSimpleName() + ") " @@ -168,7 +165,7 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository } } catch (Exception e) { - if (logger.isDebugEnabled()) { + if (this.logger.isDebugEnabled()) { this.logger.debug( "Cannot load configuration from " + candidate.getUri() + ", cause: (" + e.getClass().getSimpleName() @@ -242,6 +239,14 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository return repository; } + @Override + public void setOrder(int order) { + super.setOrder(order); + } + + /** + * A {@link JGitEnvironmentProperties} that matches patterns. + */ public static class PatternMatchingJGitEnvironmentRepository extends JGitEnvironmentRepository { @@ -249,6 +254,7 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository * Pattern to match on application name and profiles. */ private String[] pattern = new String[0]; + /** * Name of repository (same as map key by default). */ @@ -334,8 +340,4 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository } - @Override - public void setOrder(int order) { - super.setOrder(order); - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactory.java index 80f5e922..b28d1bc8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.Optional; @@ -28,21 +29,26 @@ import org.springframework.core.env.ConfigurableEnvironment; /** * @author Dylan Roberts */ -public class MultipleJGitEnvironmentRepositoryFactory implements EnvironmentRepositoryFactory { +public class MultipleJGitEnvironmentRepositoryFactory implements + EnvironmentRepositoryFactory { + private ConfigurableEnvironment environment; + private ConfigServerProperties server; + private Optional connectionFactory; + private Optional customTransportConfigCallback; - @Deprecated - public MultipleJGitEnvironmentRepositoryFactory(ConfigurableEnvironment environment, ConfigServerProperties server, - Optional customTransportConfigCallback) { - this(environment, server, Optional.empty(), customTransportConfigCallback); - } + @Deprecated + public MultipleJGitEnvironmentRepositoryFactory(ConfigurableEnvironment environment, + ConfigServerProperties server, + Optional customTransportConfigCallback) { + this(environment, server, Optional.empty(), customTransportConfigCallback); + } - public MultipleJGitEnvironmentRepositoryFactory( - ConfigurableEnvironment environment, ConfigServerProperties server, + public MultipleJGitEnvironmentRepositoryFactory(ConfigurableEnvironment environment, + ConfigServerProperties server, Optional connectionFactory, Optional customTransportConfigCallback) { this.environment = environment; @@ -52,28 +58,30 @@ public class MultipleJGitEnvironmentRepositoryFactory implements EnvironmentRepo } @Override - public MultipleJGitEnvironmentRepository build(MultipleJGitEnvironmentProperties environmentProperties) - throws Exception { - if (connectionFactory.isPresent()) { - HttpTransport.setConnectionFactory(connectionFactory.get()); - connectionFactory.get().addConfiguration(environmentProperties); + public MultipleJGitEnvironmentRepository build( + MultipleJGitEnvironmentProperties environmentProperties) throws Exception { + if (this.connectionFactory.isPresent()) { + HttpTransport.setConnectionFactory(this.connectionFactory.get()); + this.connectionFactory.get().addConfiguration(environmentProperties); } - MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository(environment, - environmentProperties); - repository.setTransportConfigCallback(customTransportConfigCallback + MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository( + this.environment, environmentProperties); + repository.setTransportConfigCallback(this.customTransportConfigCallback .orElse(buildTransportConfigCallback(environmentProperties))); - if (server.getDefaultLabel() != null) { - repository.setDefaultLabel(server.getDefaultLabel()); + if (this.server.getDefaultLabel() != null) { + repository.setDefaultLabel(this.server.getDefaultLabel()); } return repository; } - private TransportConfigCallback buildTransportConfigCallback(MultipleJGitEnvironmentProperties gitEnvironmentProperties) { - if (gitEnvironmentProperties.isIgnoreLocalSshSettings()) { - return new PropertiesBasedSshTransportConfigCallback(gitEnvironmentProperties); - } - return new FileBasedSshTransportConfigCallback(gitEnvironmentProperties); - } + private TransportConfigCallback buildTransportConfigCallback( + MultipleJGitEnvironmentProperties gitEnvironmentProperties) { + if (gitEnvironmentProperties.isIgnoreLocalSshSettings()) { + return new PropertiesBasedSshTransportConfigCallback( + gitEnvironmentProperties); + } + return new FileBasedSshTransportConfigCallback(gitEnvironmentProperties); + } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentProperties.java index 432b52b4..f157b0c8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -24,72 +25,79 @@ import org.springframework.core.Ordered; */ @ConfigurationProperties("spring.cloud.config.server.native") public class NativeEnvironmentProperties implements EnvironmentRepositoryProperties { - /** - * Flag to determine how to handle exceptions during decryption (default false). - */ - private Boolean failOnError = false; - /** - * Flag to determine whether label locations should be added. - */ - private Boolean addLabelLocations = true; - private String defaultLabel = "master"; - /** - * Locations to search for configuration files. Defaults to the same as a Spring Boot - * app so [classpath:/,classpath:/config/,file:./,file:./config/]. - */ - private String[] searchLocations = new String[0]; - /** - * Version string to be reported for native repository - */ - private String version; - private int order = Ordered.LOWEST_PRECEDENCE; - public Boolean getFailOnError() { - return failOnError; - } + /** + * Flag to determine how to handle exceptions during decryption (default false). + */ + private Boolean failOnError = false; - public void setFailOnError(Boolean failOnError) { - this.failOnError = failOnError; - } + /** + * Flag to determine whether label locations should be added. + */ + private Boolean addLabelLocations = true; - public Boolean getAddLabelLocations() { - return addLabelLocations; - } + private String defaultLabel = "master"; - public void setAddLabelLocations(Boolean addLabelLocations) { - this.addLabelLocations = addLabelLocations; - } + /** + * Locations to search for configuration files. Defaults to the same as a Spring Boot + * app so [classpath:/,classpath:/config/,file:./,file:./config/]. + */ + private String[] searchLocations = new String[0]; - public String getDefaultLabel() { - return defaultLabel; - } + /** + * Version string to be reported for native repository. + */ + private String version; - public void setDefaultLabel(String defaultLabel) { - this.defaultLabel = defaultLabel; - } + private int order = Ordered.LOWEST_PRECEDENCE; - public String[] getSearchLocations() { - return searchLocations; - } + public Boolean getFailOnError() { + return this.failOnError; + } - public void setSearchLocations(String[] searchLocations) { - this.searchLocations = searchLocations; - } + public void setFailOnError(Boolean failOnError) { + this.failOnError = failOnError; + } - public String getVersion() { - return version; - } + public Boolean getAddLabelLocations() { + return this.addLabelLocations; + } - public void setVersion(String version) { - this.version = version; - } + public void setAddLabelLocations(Boolean addLabelLocations) { + this.addLabelLocations = addLabelLocations; + } - public int getOrder() { - return order; - } + public String getDefaultLabel() { + return this.defaultLabel; + } + + public void setDefaultLabel(String defaultLabel) { + this.defaultLabel = defaultLabel; + } + + public String[] getSearchLocations() { + return this.searchLocations; + } + + public void setSearchLocations(String[] searchLocations) { + this.searchLocations = searchLocations; + } + + public String getVersion() { + return this.version; + } + + public void setVersion(String version) { + this.version = version; + } + + public int getOrder() { + return this.order; + } + + @Override + public void setOrder(int order) { + this.order = order; + } - @Override - public void setOrder(int order) { - this.order = order; - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepository.java index 116d8614..c5873a67 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.File; @@ -55,6 +56,9 @@ import org.springframework.util.StringUtils; public class NativeEnvironmentRepository implements EnvironmentRepository, SearchPathLocator, Ordered { + private static final String[] DEFAULT_LOCATIONS = new String[] { "classpath:/", + "classpath:/config/", "file:./", "file:./config/" }; + private static Log logger = LogFactory.getLog(NativeEnvironmentRepository.class); private String defaultLabel; @@ -76,18 +80,16 @@ public class NativeEnvironmentRepository private boolean addLabelLocations; /** - * Version string to be reported for native repository + * Version string to be reported for native repository. */ private String version; - private static final String[] DEFAULT_LOCATIONS = new String[] { "classpath:/", - "classpath:/config/", "file:./", "file:./config/" }; - private ConfigurableEnvironment environment; private int order; - public NativeEnvironmentRepository(ConfigurableEnvironment environment, NativeEnvironmentProperties properties) { + public NativeEnvironmentRepository(ConfigurableEnvironment environment, + NativeEnvironmentProperties properties) { this.environment = environment; this.addLabelLocations = properties.getAddLabelLocations(); this.defaultLabel = properties.getDefaultLabel(); @@ -97,24 +99,24 @@ public class NativeEnvironmentRepository this.version = properties.getVersion(); } - public void setFailOnError(boolean failOnError) { - this.failOnError = failOnError; - } - public boolean isFailOnError() { return this.failOnError; } - public void setAddLabelLocations(boolean addLabelLocations) { - this.addLabelLocations = addLabelLocations; + public void setFailOnError(boolean failOnError) { + this.failOnError = failOnError; } public boolean isAddLabelLocations() { return this.addLabelLocations; } + public void setAddLabelLocations(boolean addLabelLocations) { + this.addLabelLocations = addLabelLocations; + } + public String getDefaultLabel() { - return defaultLabel; + return this.defaultLabel; } public void setDefaultLabel(String defaultLabel) { @@ -157,7 +159,7 @@ public class NativeEnvironmentRepository Collection output = new LinkedHashSet(); if (label == null) { - label = defaultLabel; + label = this.defaultLabel; } for (String location : locations) { String[] profiles = new String[] { profile }; @@ -313,10 +315,11 @@ public class NativeEnvironmentRepository @Override public int getOrder() { - return order; + return this.order; } public void setOrder(int order) { this.order = order; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryFactory.java index 42ea7e8e..a8a1744d 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.cloud.config.server.config.ConfigServerProperties; @@ -21,22 +22,28 @@ import org.springframework.core.env.ConfigurableEnvironment; /** * @author Dylan Roberts */ -public class NativeEnvironmentRepositoryFactory implements EnvironmentRepositoryFactory { +public class NativeEnvironmentRepositoryFactory implements + EnvironmentRepositoryFactory { + private ConfigurableEnvironment environment; + private ConfigServerProperties properties; - public NativeEnvironmentRepositoryFactory(ConfigurableEnvironment environment, ConfigServerProperties properties) { + public NativeEnvironmentRepositoryFactory(ConfigurableEnvironment environment, + ConfigServerProperties properties) { this.environment = environment; this.properties = properties; } @Override - public NativeEnvironmentRepository build(NativeEnvironmentProperties environmentProperties) { - NativeEnvironmentRepository repository = new NativeEnvironmentRepository(environment, environmentProperties); - if(properties.getDefaultLabel() != null) { - repository.setDefaultLabel(properties.getDefaultLabel()); + public NativeEnvironmentRepository build( + NativeEnvironmentProperties environmentProperties) { + NativeEnvironmentRepository repository = new NativeEnvironmentRepository( + this.environment, environmentProperties); + if (this.properties.getDefaultLabel() != null) { + repository.setDefaultLabel(this.properties.getDefaultLabel()); } return repository; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NoSuchLabelException.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NoSuchLabelException.java index e4939307..100da1bf 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NoSuchLabelException.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NoSuchLabelException.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NoSuchRepositoryException.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NoSuchRepositoryException.java index 19aad8b3..7b80409b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NoSuchRepositoryException.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NoSuchRepositoryException.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/PassthruEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/PassthruEnvironmentRepository.java index c10ff5f5..1b8f92cb 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/PassthruEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/PassthruEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/RepositoryException.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/RepositoryException.java index 0803bc1e..c4b84395 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/RepositoryException.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/RepositoryException.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SearchPathCompositeEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SearchPathCompositeEnvironmentRepository.java index e2acdeca..15b3c228 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SearchPathCompositeEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SearchPathCompositeEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.ArrayList; @@ -21,26 +22,33 @@ import java.util.List; /** * A {@link CompositeEnvironmentRepository} which implements {@link SearchPathLocator}. + * * @author Ryan Baxter */ -public class SearchPathCompositeEnvironmentRepository extends CompositeEnvironmentRepository implements SearchPathLocator { +public class SearchPathCompositeEnvironmentRepository + extends CompositeEnvironmentRepository implements SearchPathLocator { /** * Creates a new {@link SearchPathCompositeEnvironmentRepository}. - * @param environmentRepositories The {@link EnvironmentRepository}s to create this composite from. + * @param environmentRepositories The {@link EnvironmentRepository}s to create this + * composite from. */ - public SearchPathCompositeEnvironmentRepository(List environmentRepositories) { + public SearchPathCompositeEnvironmentRepository( + List environmentRepositories) { super(environmentRepositories); } @Override public Locations getLocations(String application, String profile, String label) { List locations = new ArrayList<>(); - for(EnvironmentRepository repo : this.environmentRepositories) { - if(repo instanceof SearchPathLocator) { - locations.addAll(Arrays.asList(((SearchPathLocator) repo).getLocations(application, profile, label).getLocations())); + for (EnvironmentRepository repo : this.environmentRepositories) { + if (repo instanceof SearchPathLocator) { + locations.addAll(Arrays.asList(((SearchPathLocator) repo) + .getLocations(application, profile, label).getLocations())); } } - return new Locations(application, profile, label, null, locations.toArray(new String[locations.size()])); + return new Locations(application, profile, label, null, + locations.toArray(new String[locations.size()])); } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SearchPathLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SearchPathLocator.java index 39331ab1..e692990e 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SearchPathLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SearchPathLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,14 +29,23 @@ public interface SearchPathLocator { Locations getLocations(String application, String profile, String label); + /** + * Locations POJO. + */ class Locations { + private final String application; + private final String profile; + private final String label; + private final String[] locations; + private final String version; - public Locations(String application, String profile, String label, String version, String[] locations) { + public Locations(String application, String profile, String label, String version, + String[] locations) { this.application = application; this.profile = profile; this.label = label; @@ -45,31 +54,32 @@ public interface SearchPathLocator { } public String[] getLocations() { - return locations; + return this.locations; } public String getVersion() { - return version; + return this.version; } public String getApplication() { - return application; + return this.application; } public String getProfile() { - return profile; + return this.profile; } public String getLabel() { - return label; + return this.label; } @Override public String toString() { - return "Locations [application=" + application + ", profile=" + profile - + ", label=" + label + ", locations=" + Arrays.toString(locations) - + ", version=" + version + "]"; + return "Locations [application=" + this.application + ", profile=" + + this.profile + ", label=" + this.label + ", locations=" + + Arrays.toString(this.locations) + ", version=" + this.version + "]"; } } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SerializableMapPropertySource.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SerializableMapPropertySource.java index c4b2b614..04e28fd8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SerializableMapPropertySource.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SerializableMapPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.Map; @@ -20,19 +21,20 @@ import java.util.Map; class SerializableMapPropertySource { private String name; + private Map source; - public SerializableMapPropertySource(String name, Map source) { + SerializableMapPropertySource(String name, Map source) { this.name = name; this.source = source; } - + public String getName() { - return name; + return this.name; } public Map getSource() { - return source; + return this.source; } - -} \ No newline at end of file + +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnEnvironmentRepositoryFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnEnvironmentRepositoryFactory.java index cd67b4bd..19477f15 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnEnvironmentRepositoryFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnEnvironmentRepositoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.cloud.config.server.config.ConfigServerProperties; @@ -21,22 +22,28 @@ import org.springframework.core.env.ConfigurableEnvironment; /** * @author Dylan Roberts */ -public class SvnEnvironmentRepositoryFactory implements EnvironmentRepositoryFactory { +public class SvnEnvironmentRepositoryFactory implements + EnvironmentRepositoryFactory { + private ConfigurableEnvironment environment; + private ConfigServerProperties server; - public SvnEnvironmentRepositoryFactory(ConfigurableEnvironment environment, ConfigServerProperties server) { + public SvnEnvironmentRepositoryFactory(ConfigurableEnvironment environment, + ConfigServerProperties server) { this.environment = environment; this.server = server; } @Override - public SvnKitEnvironmentRepository build(SvnKitEnvironmentProperties environmentProperties) { - SvnKitEnvironmentRepository repository = new SvnKitEnvironmentRepository(environment, environmentProperties); + public SvnKitEnvironmentRepository build( + SvnKitEnvironmentProperties environmentProperties) { + SvnKitEnvironmentRepository repository = new SvnKitEnvironmentRepository( + this.environment, environmentProperties); if (this.server.getDefaultLabel() != null) { repository.setDefaultLabel(this.server.getDefaultLabel()); } return repository; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentProperties.java index fed7c634..f30cfba5 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -23,10 +24,12 @@ import org.springframework.cloud.config.server.support.AbstractScmAccessorProper */ @ConfigurationProperties("spring.cloud.config.server.svn") public class SvnKitEnvironmentProperties extends AbstractScmAccessorProperties { - private static final String DEFAULT_LABEL = "trunk"; - public SvnKitEnvironmentProperties() { - super(); - setDefaultLabel(DEFAULT_LABEL); - } + private static final String DEFAULT_LABEL = "trunk"; + + public SvnKitEnvironmentProperties() { + super(); + setDefaultLabel(DEFAULT_LABEL); + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentRepository.java index 2d0458f0..ad3db4ab 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.File; @@ -53,6 +54,12 @@ public class SvnKitEnvironmentRepository extends AbstractScmEnvironmentRepositor */ private String defaultLabel; + public SvnKitEnvironmentRepository(ConfigurableEnvironment environment, + SvnKitEnvironmentProperties properties) { + super(environment, properties); + this.defaultLabel = properties.getDefaultLabel(); + } + public String getDefaultLabel() { return this.defaultLabel; } @@ -61,11 +68,6 @@ public class SvnKitEnvironmentRepository extends AbstractScmEnvironmentRepositor this.defaultLabel = defaultLabel; } - public SvnKitEnvironmentRepository(ConfigurableEnvironment environment, SvnKitEnvironmentProperties properties) { - super(environment, properties); - this.defaultLabel = properties.getDefaultLabel(); - } - @Override public synchronized Locations getLocations(String application, String profile, String label) { @@ -98,7 +100,8 @@ public class SvnKitEnvironmentRepository extends AbstractScmEnvironmentRepositor } private String[] getPaths(String application, String profile, String label) { - String[] locations = getSearchLocations(getSvnPath(getWorkingDirectory(), label), application, profile, label); + String[] locations = getSearchLocations(getSvnPath(getWorkingDirectory(), label), + application, profile, label); boolean exists = false; for (String location : locations) { location = StringUtils.cleanPath(location); @@ -127,7 +130,8 @@ public class SvnKitEnvironmentRepository extends AbstractScmEnvironmentRepositor return id.toString(); } - private String update(SvnOperationFactory svnOperationFactory, String label) throws SVNException { + private String update(SvnOperationFactory svnOperationFactory, String label) + throws SVNException { logger.debug("Repo already checked out - updating instead."); try { @@ -145,10 +149,12 @@ public class SvnKitEnvironmentRepository extends AbstractScmEnvironmentRepositor } catch (Exception e) { String message = "Could not update remote for " + label + " (current local=" - + getWorkingDirectory().getPath() + "), remote: " + this.getUri() + ")"; + + getWorkingDirectory().getPath() + "), remote: " + this.getUri() + + ")"; if (logger.isDebugEnabled()) { logger.debug(message, e); - } else if (logger.isWarnEnabled()) { + } + else if (logger.isWarnEnabled()) { logger.warn(message); } } @@ -183,16 +189,16 @@ public class SvnKitEnvironmentRepository extends AbstractScmEnvironmentRepositor // use label as path relative to repository root // if it doesn't exists check branches and then tags folders File svnPath = new File(workingDirectory, label); - if(!svnPath.exists()) { + if (!svnPath.exists()) { svnPath = new File(workingDirectory, "branches" + File.separator + label); - if(!svnPath.exists()) { + if (!svnPath.exists()) { svnPath = new File(workingDirectory, "tags" + File.separator + label); - if(!svnPath.exists()) { + if (!svnPath.exists()) { throw new NoSuchLabelException("No label found for: " + label); } } } - return svnPath; + return svnPath; } @Override diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentProperties.java index 36d9ea11..cee11091 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.HashMap; @@ -29,125 +30,140 @@ import org.springframework.core.Ordered; */ @ConfigurationProperties("spring.cloud.config.server.vault") public class VaultEnvironmentProperties implements HttpEnvironmentRepositoryProperties { - /** Vault host. Defaults to 127.0.0.1. */ - private String host = "127.0.0.1"; - /** Vault port. Defaults to 8200. */ - private Integer port = 8200; - /** Vault scheme. Defaults to http. */ - private String scheme = "http"; - /** Timeout (in seconds) for obtaining HTTP connection, defaults to 5 seconds. */ - private int timeout = 5; - /** Vault backend. Defaults to secret. */ - private String backend = "secret"; - /** The key in vault shared by all applications. Defaults to application. Set to empty to disable. */ - private String defaultKey = "application"; - /** Vault profile separator. Defaults to comma. */ - private String profileSeparator = ","; - /** - * Flag to indicate that SSL certificate validation should be bypassed when communicating with a repository served - * over an HTTPS connection. - */ - private boolean skipSslValidation = false; - /** - * HTTP proxy configuration. - */ - private Map proxy = new HashMap<>(); - private int order = Ordered.LOWEST_PRECEDENCE; - /** - * Value to indicate which version of Vault kv backend is used. Defaults to 1. - */ - private int kvVersion = 1; + /** Vault host. Defaults to 127.0.0.1. */ + private String host = "127.0.0.1"; - public String getHost() { - return host; - } + /** Vault port. Defaults to 8200. */ + private Integer port = 8200; - public void setHost(String host) { - this.host = host; - } + /** Vault scheme. Defaults to http. */ + private String scheme = "http"; - public Integer getPort() { - return port; - } + /** Timeout (in seconds) for obtaining HTTP connection, defaults to 5 seconds. */ + private int timeout = 5; - public void setPort(Integer port) { - this.port = port; - } + /** Vault backend. Defaults to secret. */ + private String backend = "secret"; - public String getScheme() { - return scheme; - } + /** + * The key in vault shared by all applications. Defaults to application. Set to empty + * to disable. + */ + private String defaultKey = "application"; - public void setScheme(String scheme) { - this.scheme = scheme; - } + /** Vault profile separator. Defaults to comma. */ + private String profileSeparator = ","; - public String getBackend() { - return backend; - } + /** + * Flag to indicate that SSL certificate validation should be bypassed when + * communicating with a repository served over an HTTPS connection. + */ + private boolean skipSslValidation = false; - public void setBackend(String backend) { - this.backend = backend; - } + /** + * HTTP proxy configuration. + */ + private Map proxy = new HashMap<>(); - public String getDefaultKey() { - return defaultKey; - } + private int order = Ordered.LOWEST_PRECEDENCE; - public void setDefaultKey(String defaultKey) { - this.defaultKey = defaultKey; - } + /** + * Value to indicate which version of Vault kv backend is used. Defaults to 1. + */ + private int kvVersion = 1; - public String getProfileSeparator() { - return profileSeparator; - } + public String getHost() { + return this.host; + } - public void setProfileSeparator(String profileSeparator) { - this.profileSeparator = profileSeparator; - } + public void setHost(String host) { + this.host = host; + } - @Override - public boolean isSkipSslValidation() { - return skipSslValidation; - } + public Integer getPort() { + return this.port; + } - public void setSkipSslValidation(boolean skipSslValidation) { - this.skipSslValidation = skipSslValidation; - } + public void setPort(Integer port) { + this.port = port; + } - @Override - public Map getProxy() { - return proxy; - } + public String getScheme() { + return this.scheme; + } - public void setProxy(Map proxy) { - this.proxy = proxy; - } + public void setScheme(String scheme) { + this.scheme = scheme; + } - public int getOrder() { - return order; - } + public String getBackend() { + return this.backend; + } - @Override - public void setOrder(int order) { - this.order = order; - } + public void setBackend(String backend) { + this.backend = backend; + } - @Override - public int getTimeout() { - return timeout; - } + public String getDefaultKey() { + return this.defaultKey; + } + + public void setDefaultKey(String defaultKey) { + this.defaultKey = defaultKey; + } + + public String getProfileSeparator() { + return this.profileSeparator; + } + + public void setProfileSeparator(String profileSeparator) { + this.profileSeparator = profileSeparator; + } + + @Override + public boolean isSkipSslValidation() { + return this.skipSslValidation; + } + + public void setSkipSslValidation(boolean skipSslValidation) { + this.skipSslValidation = skipSslValidation; + } + + @Override + public Map getProxy() { + return this.proxy; + } + + public void setProxy( + Map proxy) { + this.proxy = proxy; + } + + public int getOrder() { + return this.order; + } + + @Override + public void setOrder(int order) { + this.order = order; + } + + @Override + public int getTimeout() { + return this.timeout; + } + + public void setTimeout(int timeout) { + this.timeout = timeout; + } - public void setTimeout(int timeout) { - this.timeout = timeout; - } - public int getKvVersion() { - return kvVersion; - } + return this.kvVersion; + } + + public void setKvVersion(int kvVersion) { + this.kvVersion = kvVersion; + } - public void setKvVersion(int kvVersion) { - this.kvVersion = kvVersion; - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepository.java index 3ebe01dd..f85593f8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.ArrayList; @@ -48,6 +49,9 @@ import static org.springframework.cloud.config.client.ConfigClientProperties.TOK @Validated public class VaultEnvironmentRepository implements EnvironmentRepository, Ordered { + /** + * Vault token header name. + */ public static final String VAULT_TOKEN = "X-Vault-Token"; /** Vault host. Defaults to 127.0.0.1. */ @@ -66,7 +70,10 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere @NotEmpty private String backend; - /** The key in vault shared by all applications. Defaults to application. Set to empty to disable. */ + /** + * The key in vault shared by all applications. Defaults to application. Set to empty + * to disable. + */ private String defaultKey; /** Vault profile separator. Defaults to comma. */ @@ -104,7 +111,7 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere @Override public Environment findOne(String application, String profile, String label) { - HttpServletRequest servletRequest = request.getIfAvailable(); + HttpServletRequest servletRequest = this.request.getIfAvailable(); if (servletRequest == null) { throw new IllegalStateException("No HttpServletRequest available"); } @@ -117,7 +124,8 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere List keys = findKeys(application, scrubbedProfiles); - Environment environment = new Environment(application, profiles, label, null, newState); + Environment environment = new Environment(application, profiles, label, null, + newState); for (String key : keys) { // read raw 'data' key from vault @@ -140,7 +148,8 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere private List findKeys(String application, List profiles) { List keys = new ArrayList<>(); - if (StringUtils.hasText(this.defaultKey) && !this.defaultKey.equals(application)) { + if (StringUtils.hasText(this.defaultKey) + && !this.defaultKey.equals(application)) { keys.add(this.defaultKey); addProfiles(keys, this.defaultKey, profiles); } @@ -173,10 +182,11 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere String token = servletRequest.getHeader(TOKEN_HEADER); if (!StringUtils.hasLength(token)) { - throw new IllegalArgumentException("Missing required header: " + TOKEN_HEADER); + throw new IllegalArgumentException( + "Missing required header: " + TOKEN_HEADER); } headers.add(VAULT_TOKEN, token); - return accessStrategy.getData(headers, backend, key); + return this.accessStrategy.getData(headers, this.backend, key); } public void setHost(String host) { @@ -203,12 +213,13 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere this.profileSeparator = profileSeparator; } + @Override + public int getOrder() { + return this.order; + } + public void setOrder(int order) { this.order = order; } - @Override - public int getOrder() { - return order; - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryFactory.java index 90659fb5..f95768cf 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.Optional; + import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.ObjectProvider; @@ -24,30 +26,44 @@ import org.springframework.web.client.RestTemplate; /** * @author Dylan Roberts */ -public class VaultEnvironmentRepositoryFactory implements EnvironmentRepositoryFactory { +public class VaultEnvironmentRepositoryFactory implements + EnvironmentRepositoryFactory { + private ObjectProvider request; + private EnvironmentWatch watch; + private Optional vaultRestTemplateFactory; - public VaultEnvironmentRepositoryFactory(ObjectProvider request, EnvironmentWatch watch, - Optional vaultRestTemplateFactory) { + public VaultEnvironmentRepositoryFactory(ObjectProvider request, + EnvironmentWatch watch, + Optional vaultRestTemplateFactory) { this.request = request; this.watch = watch; this.vaultRestTemplateFactory = vaultRestTemplateFactory; } @Override - public VaultEnvironmentRepository build(VaultEnvironmentProperties environmentProperties) throws Exception { - if (vaultRestTemplateFactory.isPresent()) { - RestTemplate restTemplate = vaultRestTemplateFactory.get().build(environmentProperties); - return new VaultEnvironmentRepository(request, watch, restTemplate, environmentProperties); + public VaultEnvironmentRepository build( + VaultEnvironmentProperties environmentProperties) throws Exception { + if (this.vaultRestTemplateFactory.isPresent()) { + RestTemplate restTemplate = this.vaultRestTemplateFactory.get() + .build(environmentProperties); + return new VaultEnvironmentRepository(this.request, this.watch, restTemplate, + environmentProperties); } - return new VaultEnvironmentRepository(request, watch, new RestTemplate(), environmentProperties); + return new VaultEnvironmentRepository(this.request, this.watch, + new RestTemplate(), environmentProperties); } + /** + * Rest template factory for Vault. + */ public interface VaultRestTemplateFactory { - RestTemplate build(VaultEnvironmentProperties environmentProperties) throws Exception; + RestTemplate build(VaultEnvironmentProperties environmentProperties) + throws Exception; + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategy.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategy.java index 177aaaf6..8b2b08f6 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategy.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategy.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.environment; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -9,6 +25,7 @@ import org.springframework.web.client.RestClientException; /** * Strategy interface to obtain secrets from Vault's key-value secret backend. + * * @author Haroun Pacquee * @author Mark Paluch * @since 2.0 @@ -29,6 +46,9 @@ public interface VaultKvAccessStrategy { String getData(HttpHeaders headers, String backend, String key) throws RestClientException; + /** + * Vault response POJO. + */ @JsonIgnoreProperties(ignoreUnknown = true) class VaultResponse { @@ -48,7 +68,7 @@ public interface VaultKvAccessStrategy { } public String getAuth() { - return auth; + return this.auth; } public void setAuth(String auth) { @@ -56,7 +76,7 @@ public interface VaultKvAccessStrategy { } public Object getData() { - return data; + return this.data; } public void setData(JsonNode data) { @@ -64,7 +84,7 @@ public interface VaultKvAccessStrategy { } public long getLeaseDuration() { - return leaseDuration; + return this.leaseDuration; } public void setLeaseDuration(long leaseDuration) { @@ -72,7 +92,7 @@ public interface VaultKvAccessStrategy { } public String getLeaseId() { - return leaseId; + return this.leaseId; } public void setLeaseId(String leaseId) { @@ -80,11 +100,13 @@ public interface VaultKvAccessStrategy { } public boolean isRenewable() { - return renewable; + return this.renewable; } public void setRenewable(boolean renewable) { this.renewable = renewable; } + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactory.java index f4f36ce5..3e95a1c9 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import com.fasterxml.jackson.databind.JsonNode; @@ -21,11 +22,16 @@ import org.springframework.web.client.RestOperations; /** * Factory for {@link VaultKvAccessStrategy}. + * * @author Haroun Pacquee * @author Mark Paluch * @since 2.0 */ -public class VaultKvAccessStrategyFactory { +public final class VaultKvAccessStrategyFactory { + + private VaultKvAccessStrategyFactory() { + throw new IllegalStateException("Can't instantiate an utility class"); + } /** * Create a new {@link VaultKvAccessStrategy} given {@link RestOperations}, @@ -67,6 +73,7 @@ public class VaultKvAccessStrategyFactory { public String extractDataFromBody(VaultResponse body) { return body.getData() == null ? null : body.getData().toString(); } + } /** @@ -89,5 +96,7 @@ public class VaultKvAccessStrategyFactory { : ((JsonNode) body.getData()).get("data"); return nestedDataNode == null ? null : nestedDataNode.toString(); } + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategySupport.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategySupport.java index 2841ebab..9144e960 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategySupport.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategySupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.springframework.http.HttpEntity; @@ -25,12 +26,14 @@ import org.springframework.web.client.RestOperations; /** * Base class for {@link VaultKvAccessStrategy} implementors. + * * @author Mark Paluch * @since 2.0 */ abstract class VaultKvAccessStrategySupport implements VaultKvAccessStrategy { private final String baseUrl; + private final RestOperations rest; VaultKvAccessStrategySupport(String baseUrl, RestOperations rest) { @@ -48,8 +51,8 @@ abstract class VaultKvAccessStrategySupport implements VaultKvAccessStrategy { /** * Extract the raw JSON from the * {@link org.springframework.cloud.config.server.environment.VaultKvAccessStrategy.VaultResponse}. - * @param body - * @return + * @param body vault response + * @return raw JSON */ abstract String extractDataFromBody(VaultResponse body); @@ -63,10 +66,11 @@ abstract class VaultKvAccessStrategySupport implements VaultKvAccessStrategy { public String getData(HttpHeaders headers, String backend, String key) { try { - String urlTemplate = String.format("%s/v1/%s/%s", baseUrl, backend, getPath()); + String urlTemplate = String.format("%s/v1/%s/%s", this.baseUrl, backend, + getPath()); - ResponseEntity response = rest.exchange(urlTemplate, HttpMethod.GET, - new HttpEntity<>(headers), VaultResponse.class, key); + ResponseEntity response = this.rest.exchange(urlTemplate, + HttpMethod.GET, new HttpEntity<>(headers), VaultResponse.class, key); HttpStatus status = response.getStatusCode(); if (status == HttpStatus.OK) { return extractDataFromBody(response.getBody()); @@ -80,4 +84,5 @@ abstract class VaultKvAccessStrategySupport implements VaultKvAccessStrategy { } return null; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/ProxyHostCredentialsProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/ProxyHostCredentialsProvider.java index a6cfb140..0831e984 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/ProxyHostCredentialsProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/ProxyHostCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.proxy; import org.apache.http.auth.AuthScope; @@ -24,16 +25,18 @@ import org.apache.http.impl.client.BasicCredentialsProvider; */ public class ProxyHostCredentialsProvider extends BasicCredentialsProvider { - public ProxyHostCredentialsProvider(ProxyHostProperties... proxyHostProperties) { + public ProxyHostCredentialsProvider(ProxyHostProperties... proxyHostProperties) { - for (ProxyHostProperties proxy : proxyHostProperties) { + for (ProxyHostProperties proxy : proxyHostProperties) { + + if (proxy != null && proxy.getUsername() != null + && proxy.getPassword() != null) { + AuthScope authscope = new AuthScope(proxy.getHost(), proxy.getPort()); + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( + proxy.getUsername(), proxy.getPassword()); + setCredentials(authscope, credentials); + } + } + } - if (proxy != null && proxy.getUsername() != null && proxy.getPassword() != null) { - AuthScope authscope = new AuthScope(proxy.getHost(), proxy.getPort()); - UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), - proxy.getPassword()); - setCredentials(authscope, credentials); - } - } - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/ProxyHostProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/ProxyHostProperties.java index 67bdee27..c66df11d 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/ProxyHostProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/ProxyHostProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,20 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.proxy; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +/** + * Properties for a proxy host. + * + * @author Dylan Roberts + */ public class ProxyHostProperties { + private String host; + private int port; + private String nonProxyHosts; + private String username; + private String password; public String getHost() { - return host; + return this.host; } public void setHost(String host) { @@ -34,7 +45,7 @@ public class ProxyHostProperties { } public int getPort() { - return port; + return this.port; } public void setPort(int port) { @@ -42,7 +53,7 @@ public class ProxyHostProperties { } public String getNonProxyHosts() { - return nonProxyHosts; + return this.nonProxyHosts; } public void setNonProxyHosts(String nonProxyHosts) { @@ -50,7 +61,7 @@ public class ProxyHostProperties { } public String getUsername() { - return username; + return this.username; } public void setUsername(String username) { @@ -58,15 +69,25 @@ public class ProxyHostProperties { } public String getPassword() { - return password; + return this.password; } public void setPassword(String password) { this.password = password; } + /** + * Proxy for a given scheme. + */ public enum ProxyForScheme { + + /** + * HTTP scheme. + */ HTTP, + /** + * HTTPS scheme. + */ HTTPS; @JsonCreator @@ -78,5 +99,7 @@ public class ProxyHostProperties { public String lowercaseName() { return this.name().toLowerCase(); } + } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/SchemeBasedRoutePlanner.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/SchemeBasedRoutePlanner.java index e1d3510e..546b024e 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/SchemeBasedRoutePlanner.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/proxy/SchemeBasedRoutePlanner.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.proxy; import org.apache.http.HttpHost; @@ -25,26 +26,29 @@ import org.apache.http.protocol.HttpContext; */ public class SchemeBasedRoutePlanner extends DefaultRoutePlanner { - private final ProxyHostProperties httpsProxy; - private final ProxyHostProperties httpProxy; + private final ProxyHostProperties httpsProxy; - public SchemeBasedRoutePlanner(ProxyHostProperties httpsProxy, ProxyHostProperties httpProxy) { - super(null); - this.httpsProxy = httpsProxy; - this.httpProxy = httpProxy; - } + private final ProxyHostProperties httpProxy; - @Override - protected HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) { - return "https".equals(target.getSchemeName()) ? - determineProxy(httpsProxy) : - determineProxy(httpProxy); - } + public SchemeBasedRoutePlanner(ProxyHostProperties httpsProxy, + ProxyHostProperties httpProxy) { + super(null); + this.httpsProxy = httpsProxy; + this.httpProxy = httpProxy; + } + + @Override + protected HttpHost determineProxy(HttpHost target, HttpRequest request, + HttpContext context) { + return "https".equals(target.getSchemeName()) ? determineProxy(this.httpsProxy) + : determineProxy(this.httpProxy); + } + + private HttpHost determineProxy(ProxyHostProperties properties) { + if (properties == null) { + return null; + } + return new HttpHost(properties.getHost(), properties.getPort()); + } - private HttpHost determineProxy(ProxyHostProperties properties) { - if (properties == null) { - return null; - } - return new HttpHost(properties.getHost(), properties.getPort()); - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/GenericResourceRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/GenericResourceRepository.java index bbac9731..5ef26911 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/GenericResourceRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/GenericResourceRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,8 @@ public class GenericResourceRepository @Override public synchronized Resource findOne(String application, String profile, String label, String path) { - String[] locations = this.service.getLocations(application, profile, label).getLocations(); + String[] locations = this.service.getLocations(application, profile, label) + .getLocations(); try { for (int i = locations.length; i-- > 0;) { String location = locations[i]; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/NoSuchResourceException.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/NoSuchResourceException.java index 5cfcdaf6..98530920 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/NoSuchResourceException.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/NoSuchResourceException.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceController.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceController.java index f455ac35..6bd904a8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceController.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceController.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.cloud.config.server.resource; -import static org.springframework.cloud.config.server.support.EnvironmentPropertySource.prepareEnvironment; -import static org.springframework.cloud.config.server.support.EnvironmentPropertySource.resolvePlaceholders; - import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; @@ -40,6 +37,9 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UrlPathHelper; +import static org.springframework.cloud.config.server.support.EnvironmentPropertySource.prepareEnvironment; +import static org.springframework.cloud.config.server.support.EnvironmentPropertySource.resolvePlaceholders; + /** * An HTTP endpoint for serving up templated plain text resources from an underlying * repository. Can be used to supply config files for consumption by a wide variety of @@ -90,9 +90,10 @@ public class ResourceController { private String getFilePath(HttpServletRequest request, String name, String profile, String label) { String stem; - if(label != null ) { + if (label != null) { stem = String.format("/%s/%s/%s/", name, profile, label); - }else { + } + else { stem = String.format("/%s/%s/", name, profile); } String path = this.helper.getPathWithinApplication(request); @@ -127,9 +128,8 @@ public class ResourceController { } @RequestMapping(value = "/{name}/{profile}/{label}/**", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) - public byte[] binary(@PathVariable String name, - @PathVariable String profile, @PathVariable String label, - HttpServletRequest request) throws IOException { + public byte[] binary(@PathVariable String name, @PathVariable String profile, + @PathVariable String label, HttpServletRequest request) throws IOException { String path = getFilePath(request, name, profile, label); return binary(name, profile, label, path); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceRepository.java index 77abdd0f..5f563c50 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/FileBasedSshTransportConfigCallback.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/FileBasedSshTransportConfigCallback.java index b4541ac7..56b551a8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/FileBasedSshTransportConfigCallback.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/FileBasedSshTransportConfigCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.ssh; import com.jcraft.jsch.Session; @@ -25,29 +26,34 @@ import org.eclipse.jgit.transport.Transport; import org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentProperties; /** - * Configure JGit transport command to use a default SSH session factory based on local machines SSH config. - * Allow strict host key checking to be set. + * Configure JGit transport command to use a default SSH session factory based on local + * machines SSH config. Allow strict host key checking to be set. + * + * @author Dylan Roberts */ public class FileBasedSshTransportConfigCallback implements TransportConfigCallback { - private MultipleJGitEnvironmentProperties sshUriProperties; + private MultipleJGitEnvironmentProperties sshUriProperties; - public FileBasedSshTransportConfigCallback(MultipleJGitEnvironmentProperties sshUriProperties) { - this.sshUriProperties = sshUriProperties; - } + public FileBasedSshTransportConfigCallback( + MultipleJGitEnvironmentProperties sshUriProperties) { + this.sshUriProperties = sshUriProperties; + } - public MultipleJGitEnvironmentProperties getSshUriProperties() { - return sshUriProperties; - } + public MultipleJGitEnvironmentProperties getSshUriProperties() { + return this.sshUriProperties; + } + + @Override + public void configure(Transport transport) { + SshSessionFactory.setInstance(new JschConfigSessionFactory() { + @Override + protected void configure(OpenSshConfig.Host hc, Session session) { + session.setConfig("StrictHostKeyChecking", + FileBasedSshTransportConfigCallback.this.sshUriProperties + .isStrictHostKeyChecking() ? "yes" : "no"); + } + }); + } - @Override - public void configure(Transport transport) { - SshSessionFactory.setInstance(new JschConfigSessionFactory() { - @Override - protected void configure(OpenSshConfig.Host hc, Session session) { - session.setConfig("StrictHostKeyChecking", - sshUriProperties.isStrictHostKeyChecking() ? "yes" : "no"); - } - }); - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupported.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupported.java index 68fae7d0..1f7b1918 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupported.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupported.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,19 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.ssh; -import org.springframework.validation.annotation.Validated; - -import javax.validation.Constraint; -import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.validation.Constraint; +import javax.validation.Payload; + +import org.springframework.validation.annotation.Validated; + /** - * Beans annotated with {@link HostKeyAlgoSupported} and {@link Validated} will have the constraints applied. + * Beans annotated with {@link HostKeyAlgoSupported} and {@link Validated} will have the + * constraints applied. * * @author Ollie Hughes **/ @@ -33,7 +36,11 @@ import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface HostKeyAlgoSupported { + String message() default "{HostKeyAlgoSupported.message}"; + Class[] groups() default {}; + Class[] payload() default {}; + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupportedValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupportedValidator.java index e3652592..29a77503 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupportedValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupportedValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.ssh; import java.util.Arrays; @@ -20,6 +21,7 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; + import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; @@ -32,44 +34,58 @@ import static org.springframework.cloud.config.server.ssh.SshPropertyValidator.i import static org.springframework.util.StringUtils.hasText; /** - * JSR-303 Cross Field validator that ensures that a {@link MultipleJGitEnvironmentProperties} bean for the constraints: - * - If host key algo is supported + * JSR-303 Cross Field validator that ensures that a + * {@link MultipleJGitEnvironmentProperties} bean for the constraints: - If host key algo + * is supported * - * Beans annotated with {@link HostKeyAlgoSupported} and {@link Validated} will have the constraints applied. + * Beans annotated with {@link HostKeyAlgoSupported} and {@link Validated} will have the + * constraints applied. * * @author Ollie Hughes */ -public class HostKeyAlgoSupportedValidator implements ConstraintValidator { +public class HostKeyAlgoSupportedValidator implements + ConstraintValidator { + private static final String GIT_PROPERTY_PREFIX = "spring.cloud.config.server.git."; + + private static final Set VALID_HOST_KEY_ALGORITHMS = new LinkedHashSet<>( + Arrays.asList("ssh-dss", "ssh-rsa", "ecdsa-sha2-nistp256", + "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521")); + private final SshPropertyValidator sshPropertyValidator = new SshPropertyValidator(); - private static final Set VALID_HOST_KEY_ALGORITHMS = new LinkedHashSet<>(Arrays.asList( - "ssh-dss","ssh-rsa","ecdsa-sha2-nistp256","ecdsa-sha2-nistp384","ecdsa-sha2-nistp521")); @Override public void initialize(HostKeyAlgoSupported constrainAnnotation) { - //No special initialization of validator required + // No special initialization of validator required } @Override - public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) { + public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, + ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); Set validationResults = new HashSet<>(); - List extractedProperties = sshPropertyValidator.extractRepoProperties(sshUriProperties); + List extractedProperties = this.sshPropertyValidator + .extractRepoProperties(sshUriProperties); for (JGitEnvironmentProperties extractedProperty : extractedProperties) { - if (sshUriProperties.isIgnoreLocalSshSettings() && isSshUri(extractedProperty.getUri())) { - validationResults.add(isHostKeySpecifiedWhenAlgorithmSet(extractedProperty, context)); + if (sshUriProperties.isIgnoreLocalSshSettings() + && isSshUri(extractedProperty.getUri())) { + validationResults.add( + isHostKeySpecifiedWhenAlgorithmSet(extractedProperty, context)); } } return !validationResults.contains(false); } - private boolean isHostKeySpecifiedWhenAlgorithmSet(JGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) { - if (hasText(sshUriProperties.getHostKeyAlgorithm()) - && !VALID_HOST_KEY_ALGORITHMS.contains(sshUriProperties.getHostKeyAlgorithm())) { + private boolean isHostKeySpecifiedWhenAlgorithmSet( + JGitEnvironmentProperties sshUriProperties, + ConstraintValidatorContext context) { + if (hasText(sshUriProperties.getHostKeyAlgorithm()) && !VALID_HOST_KEY_ALGORITHMS + .contains(sshUriProperties.getHostKeyAlgorithm())) { context.buildConstraintViolationWithTemplate( - format("Property '%shostKeyAlgorithm' must be one of %s", GIT_PROPERTY_PREFIX, VALID_HOST_KEY_ALGORITHMS)) + format("Property '%shostKeyAlgorithm' must be one of %s", + GIT_PROPERTY_PREFIX, VALID_HOST_KEY_ALGORITHMS)) .addConstraintViolation(); return false; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExist.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExist.java index b0464526..0cfd2814 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExist.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExist.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,26 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.ssh; -import org.springframework.validation.annotation.Validated; - -import javax.validation.Constraint; -import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.validation.Constraint; +import javax.validation.Payload; + +import org.springframework.validation.annotation.Validated; + /** - * Beans annotated with {@link HostKeyAndAlgoBothExist} and {@link Validated} will have the constraints applied. + * Beans annotated with {@link HostKeyAndAlgoBothExist} and {@link Validated} will have + * the constraints applied. * @author Ollie Hughes */ @Constraint(validatedBy = HostKeyAndAlgoBothExistValidator.class) @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface HostKeyAndAlgoBothExist { + String message() default "{HostKeyAndAlgoBothExist.message}"; + Class[] groups() default {}; + Class[] payload() default {}; + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExistValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExistValidator.java index 3d376cfd..f99b78b4 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExistValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExistValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.ssh; import java.util.HashSet; import java.util.List; import java.util.Set; + import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; @@ -30,57 +32,73 @@ import static org.springframework.cloud.config.server.ssh.SshPropertyValidator.i import static org.springframework.util.StringUtils.hasText; /** - * JSR-303 Cross Field validator that ensures that a {@link MultipleJGitEnvironmentProperties} bean for the constraints: - * - If host key is set then host key algo must also be set - * - If host key algo is set then host key must also be set + * JSR-303 Cross Field validator that ensures that a + * {@link MultipleJGitEnvironmentProperties} bean for the constraints: - If host key is + * set then host key algo must also be set - If host key algo is set then host key must + * also be set * - * Beans annotated with {@link HostKeyAndAlgoBothExist} and {@link Validated} will have the constraints applied. + * Beans annotated with {@link HostKeyAndAlgoBothExist} and {@link Validated} will have + * the constraints applied. * * @author Ollie Hughes */ -public class HostKeyAndAlgoBothExistValidator implements ConstraintValidator { +public class HostKeyAndAlgoBothExistValidator implements + ConstraintValidator { + private static final String GIT_PROPERTY_PREFIX = "spring.cloud.config.server.git."; + private final SshPropertyValidator sshPropertyValidator = new SshPropertyValidator(); @Override public void initialize(HostKeyAndAlgoBothExist constrainAnnotation) { - //No special initialization of validator required + // No special initialization of validator required } @Override - public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) { + public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, + ConstraintValidatorContext context) { Set validationResults = new HashSet<>(); - List extractedProperties = sshPropertyValidator.extractRepoProperties(sshUriProperties); + List extractedProperties = this.sshPropertyValidator + .extractRepoProperties(sshUriProperties); for (JGitEnvironmentProperties extractedProperty : extractedProperties) { - if (sshUriProperties.isIgnoreLocalSshSettings() && isSshUri(extractedProperty.getUri())) { + if (sshUriProperties.isIgnoreLocalSshSettings() + && isSshUri(extractedProperty.getUri())) { validationResults.add( isAlgorithmSpecifiedWhenHostKeySet(extractedProperty, context) - && isHostKeySpecifiedWhenAlgorithmSet(extractedProperty, context)); + && isHostKeySpecifiedWhenAlgorithmSet(extractedProperty, + context)); } } return !validationResults.contains(false); } - private boolean isHostKeySpecifiedWhenAlgorithmSet(JGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) { - if (hasText(sshUriProperties.getHostKeyAlgorithm()) && !hasText(sshUriProperties.getHostKey())) { - context.disableDefaultConstraintViolation(); - context.buildConstraintViolationWithTemplate( - format("Property '%shostKey' must be set when '%shostKeyAlgorithm' is specified", GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX)) - .addConstraintViolation(); + private boolean isHostKeySpecifiedWhenAlgorithmSet( + JGitEnvironmentProperties sshUriProperties, + ConstraintValidatorContext context) { + if (hasText(sshUriProperties.getHostKeyAlgorithm()) + && !hasText(sshUriProperties.getHostKey())) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(format( + "Property '%shostKey' must be set when '%shostKeyAlgorithm' is specified", + GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX)).addConstraintViolation(); return false; } return true; } - private boolean isAlgorithmSpecifiedWhenHostKeySet(JGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) { - if (hasText(sshUriProperties.getHostKey()) && !hasText(sshUriProperties.getHostKeyAlgorithm())) { + private boolean isAlgorithmSpecifiedWhenHostKeySet( + JGitEnvironmentProperties sshUriProperties, + ConstraintValidatorContext context) { + if (hasText(sshUriProperties.getHostKey()) + && !hasText(sshUriProperties.getHostKeyAlgorithm())) { context.disableDefaultConstraintViolation(); - context.buildConstraintViolationWithTemplate( - format("Property '%shostKeyAlgorithm' must be set when '%shostKey' is specified", GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX)) - .addConstraintViolation(); + context.buildConstraintViolationWithTemplate(format( + "Property '%shostKeyAlgorithm' must be set when '%shostKey' is specified", + GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX)).addConstraintViolation(); return false; } return true; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileIsValid.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileIsValid.java index f11af222..d2d643e1 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileIsValid.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileIsValid.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,19 @@ package org.springframework.cloud.config.server.ssh; -import org.springframework.validation.annotation.Validated; - -import javax.validation.Constraint; -import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.validation.Constraint; +import javax.validation.Payload; + +import org.springframework.validation.annotation.Validated; + /** - * Beans annotated with {@link KnownHostsFileIsValid} and {@link Validated} will have the constraints applied. + * Beans annotated with {@link KnownHostsFileIsValid} and {@link Validated} will have the + * constraints applied. * * @author Edgars Jasmans **/ @@ -34,7 +36,11 @@ import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface KnownHostsFileIsValid { - String message() default "{KnownHostsFileIsValid.message}"; - Class[] groups() default {}; - Class[] payload() default {}; + + String message() default "{KnownHostsFileIsValid.message}"; + + Class[] groups() default {}; + + Class[] payload() default {}; + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileValidator.java index e3cb4262..9ea626a6 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.config.server.ssh; import java.io.File; + import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; @@ -26,30 +27,35 @@ import org.springframework.validation.annotation.Validated; import static java.lang.String.format; /** - * JSR-303 Cross Field validator that ensures that a {@link MultipleJGitEnvironmentProperties} bean for the constraints: - * - Verifies that known hosts file exists + * JSR-303 Cross Field validator that ensures that a + * {@link MultipleJGitEnvironmentProperties} bean for the constraints: - Verifies that + * known hosts file exists *

- * Beans annotated with {@link KnownHostsFileIsValid} and {@link Validated} will have the constraints applied. + * Beans annotated with {@link KnownHostsFileIsValid} and {@link Validated} will have the + * constraints applied. * * @author Edgars Jasmans */ -public class KnownHostsFileValidator implements ConstraintValidator { +public class KnownHostsFileValidator implements + ConstraintValidator { - @Override - public void initialize(KnownHostsFileIsValid knownHostsFileIsValid) { - // No initialization required - } + @Override + public void initialize(KnownHostsFileIsValid knownHostsFileIsValid) { + // No initialization required + } + + @Override + public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, + ConstraintValidatorContext context) { + String knownHostsFile = sshUriProperties.getKnownHostsFile(); + if (knownHostsFile != null && !new File(knownHostsFile).exists()) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(format( + "File '%s' specified in property 'spring.cloud.config.server.git.knownHostsFile' could not be located", + knownHostsFile)).addConstraintViolation(); + return false; + } + return true; + } - @Override - public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) { - String knownHostsFile = sshUriProperties.getKnownHostsFile(); - if (knownHostsFile != null && !new File(knownHostsFile).exists()) { - context.disableDefaultConstraintViolation(); - context.buildConstraintViolationWithTemplate( - format("File '%s' specified in property 'spring.cloud.config.server.git.knownHostsFile' could not be located", knownHostsFile)) - .addConstraintViolation(); - return false; - } - return true; - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyIsValid.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyIsValid.java index 6a0a831b..c34ca5db 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyIsValid.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyIsValid.java @@ -1,24 +1,46 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.ssh; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; + import javax.validation.Constraint; import javax.validation.Payload; import org.springframework.validation.annotation.Validated; /** -* Beans annotated with {@link PrivateKeyValidator} and {@link Validated} will have the constraints applied. -* -* @author Ollie Hughes -*/ + * Beans annotated with {@link PrivateKeyValidator} and {@link Validated} will have the + * constraints applied. + * + * @author Ollie Hughes + */ @Constraint(validatedBy = PrivateKeyValidator.class) @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface PrivateKeyIsValid { + String message() default "{PrivateKeyIsValid.message}"; + Class[] groups() default {}; + Class[] payload() default {}; + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyValidator.java index 51be05a2..a24ffe0a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.ssh; import java.util.HashSet; import java.util.List; import java.util.Set; + import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; @@ -34,32 +36,39 @@ import static org.springframework.cloud.config.server.ssh.SshPropertyValidator.i import static org.springframework.util.StringUtils.hasText; /** - * JSR-303 Cross Field validator that ensures that an {@link MultipleJGitEnvironmentProperties} bean for the constraints: - * - Private key is present and can be correctly parsed using {@link com.jcraft.jsch.KeyPair} + * JSR-303 Cross Field validator that ensures that an + * {@link MultipleJGitEnvironmentProperties} bean for the constraints: - Private key is + * present and can be correctly parsed using {@link com.jcraft.jsch.KeyPair} * - * Beans annotated with {@link PrivateKeyValidator} and {@link Validated} will have the constraints applied. + * Beans annotated with {@link PrivateKeyValidator} and {@link Validated} will have the + * constraints applied. * * @author Ollie Hughes */ -public class PrivateKeyValidator implements ConstraintValidator { +public class PrivateKeyValidator implements + ConstraintValidator { + private static final String GIT_PROPERTY_PREFIX = "spring.cloud.config.server.git."; + private final SshPropertyValidator sshPropertyValidator = new SshPropertyValidator(); @Override public void initialize(PrivateKeyIsValid constrainAnnotation) { - //No special initialization of validator required + // No special initialization of validator required } @Override - public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) { + public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, + ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); Set validationResults = new HashSet<>(); - List extractedProperties = sshPropertyValidator.extractRepoProperties(sshUriProperties); + List extractedProperties = this.sshPropertyValidator + .extractRepoProperties(sshUriProperties); for (JGitEnvironmentProperties extractedProperty : extractedProperties) { - if (extractedProperty.isIgnoreLocalSshSettings() && isSshUri(extractedProperty.getUri())) { - validationResults.add( - isPrivateKeyPresent(extractedProperty, context) + if (extractedProperty.isIgnoreLocalSshSettings() + && isSshUri(extractedProperty.getUri())) { + validationResults.add(isPrivateKeyPresent(extractedProperty, context) && isPrivateKeyFormatCorrect(extractedProperty, context)); } } @@ -67,25 +76,30 @@ public class PrivateKeyValidator implements ConstraintValidator sshKeysByHostname; + private final JSch jSch; - public PropertyBasedSshSessionFactory(Map sshKeysByHostname, JSch jSch) { + public PropertyBasedSshSessionFactory( + Map sshKeysByHostname, JSch jSch) { this.sshKeysByHostname = sshKeysByHostname; this.jSch = jSch; } @Override protected void configure(Host hc, Session session) { - JGitEnvironmentProperties sshProperties = sshKeysByHostname.get(hc.getHostName()); + JGitEnvironmentProperties sshProperties = this.sshKeysByHostname + .get(hc.getHostName()); String hostKeyAlgorithm = sshProperties.getHostKeyAlgorithm(); if (hostKeyAlgorithm != null) { session.setConfig(SERVER_HOST_KEY, hostKeyAlgorithm); } - if (sshProperties.getHostKey() == null || !sshProperties.isStrictHostKeyChecking()) { + if (sshProperties.getHostKey() == null + || !sshProperties.isStrictHostKeyChecking()) { session.setConfig(STRICT_HOST_KEY_CHECKING, NO_OPTION); - } else { + } + else { session.setConfig(STRICT_HOST_KEY_CHECKING, YES_OPTION); } String preferredAuthentications = sshProperties.getPreferredAuthentications(); @@ -69,18 +81,21 @@ public class PropertyBasedSshSessionFactory extends JschConfigSessionFactory { } @Override - protected Session createSession(Host hc, String user, String host, int port, FS fs) throws JSchException { - if (sshKeysByHostname.containsKey(host)) { - JGitEnvironmentProperties sshUriProperties = sshKeysByHostname.get(host); - jSch.addIdentity(host, sshUriProperties.getPrivateKey().getBytes(), null, null); + protected Session createSession(Host hc, String user, String host, int port, FS fs) + throws JSchException { + if (this.sshKeysByHostname.containsKey(host)) { + JGitEnvironmentProperties sshUriProperties = this.sshKeysByHostname.get(host); + this.jSch.addIdentity(host, sshUriProperties.getPrivateKey().getBytes(), null, + null); if (sshUriProperties.getKnownHostsFile() != null) { - jSch.setKnownHosts(sshUriProperties.getKnownHostsFile()); + this.jSch.setKnownHosts(sshUriProperties.getKnownHostsFile()); } if (sshUriProperties.getHostKey() != null) { - HostKey hostkey = new HostKey(host, Base64.decode(sshUriProperties.getHostKey())); - jSch.getHostKeyRepository().add(hostkey, null); + HostKey hostkey = new HostKey(host, + Base64.decode(sshUriProperties.getHostKey())); + this.jSch.getHostKeyRepository().add(hostkey, null); } - return jSch.getSession(user, host, port); + return this.jSch.getSession(user, host, port); } throw new JSchException("no keys configured for hostname " + host); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshPropertyValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshPropertyValidator.java index 75b1fc4a..58543ae3 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshPropertyValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshPropertyValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.springframework.stereotype.Component; import static org.springframework.util.StringUtils.hasText; /** - * Validate SSH related properties + * Validate SSH related properties. * * @author Ollie Hughes */ @@ -40,30 +40,36 @@ import static org.springframework.util.StringUtils.hasText; public class SshPropertyValidator { protected static boolean isSshUri(Object uri) { - if(uri != null) { + if (uri != null) { try { URIish urIish = new URIish(uri.toString()); String scheme = urIish.getScheme(); - if(scheme == null && hasText(urIish.getHost()) && hasText(urIish.getUser())) { - //JGit returns null if using SCP URI but user and host will be populated + if (scheme == null && hasText(urIish.getHost()) + && hasText(urIish.getUser())) { + // JGit returns null if using SCP URI but user and host will be + // populated return true; } return scheme != null && !scheme.matches("^(http|https)$"); - } catch (URISyntaxException e) { + } + catch (URISyntaxException e) { return false; } } return false; } - protected List extractRepoProperties(MultipleJGitEnvironmentProperties sshUriProperties) { + protected List extractRepoProperties( + MultipleJGitEnvironmentProperties sshUriProperties) { List allRepoProperties = new ArrayList<>(); allRepoProperties.add(sshUriProperties); - Map repos = sshUriProperties.getRepos(); + Map repos = sshUriProperties + .getRepos(); if (repos != null) { allRepoProperties.addAll(repos.values()); } return allRepoProperties; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessor.java index c5465fb1..d31fc955 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.config.server.ssh; +package org.springframework.cloud.config.server.ssh; import java.net.URISyntaxException; import java.util.HashMap; @@ -28,7 +28,9 @@ import org.springframework.cloud.config.server.environment.MultipleJGitEnvironme import static org.springframework.cloud.config.server.ssh.SshPropertyValidator.isSshUri; /** - * Check if Git repo properties refer to an SSH based transport then filter and extract the properties + * Check if Git repo properties refer to an SSH based transport then filter and extract + * the properties. + * * @author William Tran * @author Ollie Hughes */ @@ -40,19 +42,32 @@ public class SshUriPropertyProcessor { this.sshUriProperties = sshUriProperties; } - public Map getSshKeysByHostname() { - return extractNestedProperties(sshUriProperties); + protected static String getHostname(String uri) { + try { + URIish urIish = new URIish(uri); + return urIish.getHost(); + } + catch (URISyntaxException e) { + return null; + } } - private Map extractNestedProperties(MultipleJGitEnvironmentProperties uriProperties) { + public Map getSshKeysByHostname() { + return extractNestedProperties(this.sshUriProperties); + } + + private Map extractNestedProperties( + MultipleJGitEnvironmentProperties uriProperties) { Map sshUriPropertyMap = new HashMap<>(); String parentUri = uriProperties.getUri(); if (isSshUri(parentUri) && getHostname(parentUri) != null) { sshUriPropertyMap.put(getHostname(parentUri), uriProperties); } - Map repos = uriProperties.getRepos(); - if(repos != null) { - for (MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties repoProperties : repos.values()) { + Map repos = uriProperties + .getRepos(); + if (repos != null) { + for (MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties repoProperties : repos + .values()) { String repoUri = repoProperties.getUri(); if (isSshUri(repoUri) && getHostname(repoUri) != null) { sshUriPropertyMap.put(getHostname(repoUri), repoProperties); @@ -62,12 +77,4 @@ public class SshUriPropertyProcessor { return sshUriPropertyMap; } - protected static String getHostname(String uri) { - try { - URIish urIish = new URIish(uri); - return urIish.getHost(); - } catch (URISyntaxException e) { - return null; - } - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AbstractScmAccessor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AbstractScmAccessor.java index 018500ff..c568ea77 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AbstractScmAccessor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AbstractScmAccessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,36 +42,43 @@ import org.springframework.util.StringUtils; * Base class for components that want to access a source control management system. * * @author Dave Syer - * */ public abstract class AbstractScmAccessor implements ResourceLoaderAware { protected Log logger = LogFactory.getLog(getClass()); + /** * Base directory for local working copy of repository. */ private File basedir; + /** * URI of remote repository. */ private String uri; + private ConfigurableEnvironment environment; + /** * Username for authentication with remote repository. */ private String username; + /** * Password for authentication with remote repository. */ private String password; + /** * Passphrase for unlocking your ssh private key. */ private String passphrase; + /** * Reject incoming SSH host keys from remote servers not in the known host list. */ private boolean strictHostKeyChecking; + /** * Search paths to use within local working copy. By default searches only the root. */ @@ -132,6 +139,10 @@ public abstract class AbstractScmAccessor implements ResourceLoaderAware { this.environment = environment; } + public String getUri() { + return this.uri; + } + public void setUri(String uri) { while (uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); @@ -144,26 +155,22 @@ public abstract class AbstractScmAccessor implements ResourceLoaderAware { this.uri = uri; } - public String getUri() { - return this.uri; + public File getBasedir() { + return this.basedir; } public void setBasedir(File basedir) { this.basedir = basedir.getAbsoluteFile(); } - public File getBasedir() { - return this.basedir; + public String[] getSearchPaths() { + return this.searchPaths; } public void setSearchPaths(String... searchPaths) { this.searchPaths = searchPaths; } - public String[] getSearchPaths() { - return this.searchPaths; - } - public String getUsername() { return this.username; } @@ -181,7 +188,7 @@ public abstract class AbstractScmAccessor implements ResourceLoaderAware { } public String getPassphrase() { - return passphrase; + return this.passphrase; } public void setPassphrase(String passphrase) { @@ -189,7 +196,7 @@ public abstract class AbstractScmAccessor implements ResourceLoaderAware { } public boolean isStrictHostKeyChecking() { - return strictHostKeyChecking; + return this.strictHostKeyChecking; } public void setStrictHostKeyChecking(boolean strictHostKeyChecking) { @@ -216,7 +223,8 @@ public abstract class AbstractScmAccessor implements ResourceLoaderAware { locations = AbstractScmAccessorProperties.DEFAULT_LOCATIONS; } else if (locations != AbstractScmAccessorProperties.DEFAULT_LOCATIONS) { - locations = StringUtils.concatenateStringArrays(AbstractScmAccessorProperties.DEFAULT_LOCATIONS, locations); + locations = StringUtils.concatenateStringArrays( + AbstractScmAccessorProperties.DEFAULT_LOCATIONS, locations); } Collection output = new LinkedHashSet(); for (String location : locations) { diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AbstractScmAccessorProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AbstractScmAccessorProperties.java index 9b80c155..a240c8f8 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AbstractScmAccessorProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AbstractScmAccessorProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.support; import java.io.File; @@ -23,113 +24,121 @@ import org.springframework.core.Ordered; * @author Dylan Roberts */ public class AbstractScmAccessorProperties implements EnvironmentRepositoryProperties { - static final String[] DEFAULT_LOCATIONS = new String[] { "/" }; - /** - * URI of remote repository. - */ - private String uri; - /** - * Base directory for local working copy of repository. - */ - private File basedir; - /** - * Search paths to use within local working copy. By default searches only the root. - */ - private String[] searchPaths = DEFAULT_LOCATIONS.clone();; - /** - * Username for authentication with remote repository. - */ - private String username; - /** - * Password for authentication with remote repository. - */ - private String password; - /** - * Passphrase for unlocking your ssh private key. - */ - private String passphrase; - /** - * Reject incoming SSH host keys from remote servers not in the known host list. - */ - private boolean strictHostKeyChecking = true; + static final String[] DEFAULT_LOCATIONS = new String[] { "/" }; - /** The order of the environment repository. */ - private int order = Ordered.LOWEST_PRECEDENCE; + /** + * URI of remote repository. + */ + private String uri; - /** The default label to be used with the remote repository */ - private String defaultLabel; + /** + * Base directory for local working copy of repository. + */ + private File basedir; - public String getUri() { - return uri; - } + /** + * Search paths to use within local working copy. By default searches only the root. + */ + private String[] searchPaths = DEFAULT_LOCATIONS.clone(); - public void setUri(String uri) { - this.uri = uri; - } + /** + * Username for authentication with remote repository. + */ + private String username; - public File getBasedir() { - return basedir; - } + /** + * Password for authentication with remote repository. + */ + private String password; - public void setBasedir(File basedir) { - this.basedir = basedir; - } + /** + * Passphrase for unlocking your ssh private key. + */ + private String passphrase; - public String[] getSearchPaths() { - return searchPaths; - } + /** + * Reject incoming SSH host keys from remote servers not in the known host list. + */ + private boolean strictHostKeyChecking = true; - public void setSearchPaths(String... searchPaths) { - this.searchPaths = searchPaths; - } + /** The order of the environment repository. */ + private int order = Ordered.LOWEST_PRECEDENCE; - public String getUsername() { - return username; - } + /** The default label to be used with the remote repository. */ + private String defaultLabel; - public void setUsername(String username) { - this.username = username; - } + public String getUri() { + return this.uri; + } - public String getPassword() { - return password; - } + public void setUri(String uri) { + this.uri = uri; + } - public void setPassword(String password) { - this.password = password; - } + public File getBasedir() { + return this.basedir; + } - public String getPassphrase() { - return passphrase; - } + public void setBasedir(File basedir) { + this.basedir = basedir; + } - public void setPassphrase(String passphrase) { - this.passphrase = passphrase; - } + public String[] getSearchPaths() { + return this.searchPaths; + } - public boolean isStrictHostKeyChecking() { - return strictHostKeyChecking; - } + public void setSearchPaths(String... searchPaths) { + this.searchPaths = searchPaths; + } - public void setStrictHostKeyChecking(boolean strictHostKeyChecking) { - this.strictHostKeyChecking = strictHostKeyChecking; - } + public String getUsername() { + return this.username; + } - public int getOrder() { - return order; - } + public void setUsername(String username) { + this.username = username; + } - @Override - public void setOrder(int order) { - this.order = order; - } + public String getPassword() { + return this.password; + } - public String getDefaultLabel() { - return defaultLabel; - } + public void setPassword(String password) { + this.password = password; + } + + public String getPassphrase() { + return this.passphrase; + } + + public void setPassphrase(String passphrase) { + this.passphrase = passphrase; + } + + public boolean isStrictHostKeyChecking() { + return this.strictHostKeyChecking; + } + + public void setStrictHostKeyChecking(boolean strictHostKeyChecking) { + this.strictHostKeyChecking = strictHostKeyChecking; + } + + public int getOrder() { + return this.order; + } + + @Override + public void setOrder(int order) { + this.order = order; + } + + public String getDefaultLabel() { + return this.defaultLabel; + } + + public void setDefaultLabel(String defaultLabel) { + this.defaultLabel = defaultLabel; + } - public void setDefaultLabel(String defaultLabel) { - this.defaultLabel = defaultLabel; - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java index 1653d72f..34043a4c 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,6 @@ package org.springframework.cloud.config.server.support; -import static org.springframework.util.StringUtils.hasText; - import java.net.URI; import java.net.URL; import java.security.MessageDigest; @@ -29,6 +27,12 @@ import java.util.TimeZone; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSSessionCredentials; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; +import com.amazonaws.util.ValidationUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jgit.errors.UnsupportedCredentialItem; @@ -36,59 +40,185 @@ import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.URIish; -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.AWSCredentialsProvider; -import com.amazonaws.auth.AWSSessionCredentials; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; -import com.amazonaws.util.ValidationUtils; +import static org.springframework.util.StringUtils.hasText; /** - * Provides a jgit {@link CredentialsProvider} implementation that can provide - * the appropriate credentials to connect to an AWS CodeCommit repository. + * Provides a jgit {@link CredentialsProvider} implementation that can provide the + * appropriate credentials to connect to an AWS CodeCommit repository. *

- * From the command line, you can configure git to use AWS code commit with a - * credential helper. However, jgit does not support credential helper commands, - * but it does provider a CredentialsProvider abstract class we can extend. + * From the command line, you can configure git to use AWS code commit with a credential + * helper. However, jgit does not support credential helper commands, but it does provider + * a CredentialsProvider abstract class we can extend. *

- * Connecting to an AWS CodeCommit (codecommit) repository requires an AWS access key - * and secret key. These are used to calculate a signature for the git request. The - * AWS access key is used as the codecommit username, and the calculated signature - * is used as the password. The process for calculating this signature is documented - * very well at http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html. - *

- * - * @author Don Laidlaw + * Connecting to an AWS CodeCommit (codecommit) repository requires an AWS access key and + * secret key. These are used to calculate a signature for the git request. The AWS access + * key is used as the codecommit username, and the calculated signature is used as the + * password. The process for calculating this signature is documented very well at + * http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html. * + * @author Don Laidlaw */ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { private static final String SHA_256 = "SHA-256"; //$NON-NLS-1$ + private static final String UTF8 = "UTF8"; //$NON-NLS-1$ + private static final String HMAC_SHA256 = "HmacSHA256"; //$NON-NLS-1$ + private static final char[] hexArray = "0123456789abcdef".toCharArray(); //$NON-NLS-1$ protected Log logger = LogFactory.getLog(getClass()); /** - * The AWSCredentialsProvider will be used to provide the access key and - * secret key if they are not specified. + * The AWSCredentialsProvider will be used to provide the access key and secret key if + * they are not specified. */ private AWSCredentialsProvider awsCredentialProvider; /** - * If the access and secret keys are provided, then the - * AWSCredentialsProvider will not be used. The username is the - * awsAccessKeyId. + * If the access and secret keys are provided, then the AWSCredentialsProvider will + * not be used. The username is the awsAccessKeyId. */ private String username; - + /** - * If the access and secret keys are provided, then the AWSCredentialsProvider will + * If the access and secret keys are provided, then the AWSCredentialsProvider will * not be used. The password is the awsSecretKey. */ private String password; + /** + * Calculate the AWS CodeCommit password for the provided URI and AWS secret key. This + * uses the algorithm published by AWS at + * http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html + * @param uri the codecommit repository uri + * @param awsSecretKey the aws secret key + * @return the password to use in the git request + */ + protected static String calculateCodeCommitPassword(URIish uri, String awsSecretKey) { + String[] split = uri.getHost().split("\\."); + if (split.length < 4) { + throw new CredentialException("Cannot detect AWS region from URI", null); + } + String region = split[1]; + + Date now = new Date(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + String dateStamp = dateFormat.format(now); + String shortDateStamp = dateStamp.substring(0, 8); + + String codeCommitPassword; + try { + StringBuilder stringToSign = new StringBuilder(); + stringToSign.append("AWS4-HMAC-SHA256\n").append(dateStamp).append("\n") + .append(shortDateStamp).append("/").append(region) + .append("/codecommit/aws4_request\n") + .append(bytesToHexString(canonicalRequestDigest(uri))); + + byte[] signedRequest = sign(awsSecretKey, shortDateStamp, region, + stringToSign.toString()); + codeCommitPassword = dateStamp + "Z" + bytesToHexString(signedRequest); + } + catch (Exception e) { + throw new CredentialException("Error calculating AWS CodeCommit password", e); + } + + return codeCommitPassword; + } + + private static byte[] hmacSha256(String data, byte[] key) throws Exception { + String algorithm = HMAC_SHA256; + Mac mac = Mac.getInstance(algorithm); + mac.init(new SecretKeySpec(key, algorithm)); + return mac.doFinal(data.getBytes(UTF8)); + } + + private static byte[] sign(String secret, String shortDateStamp, String region, + String toSign) throws Exception { + byte[] kSecret = ("AWS4" + secret).getBytes(UTF8); + byte[] kDate = hmacSha256(shortDateStamp, kSecret); + byte[] kRegion = hmacSha256(region, kDate); + byte[] kService = hmacSha256("codecommit", kRegion); + byte[] kSigning = hmacSha256("aws4_request", kService); + return hmacSha256(toSign, kSigning); + } + + /** + * Creates a message digest. + * @param uri uri to process + * @return a message digest + * @throws NoSuchAlgorithmException when the SHA 256 algorithm is not found + */ + private static byte[] canonicalRequestDigest(URIish uri) + throws NoSuchAlgorithmException { + StringBuilder canonicalRequest = new StringBuilder(); + canonicalRequest.append("GIT\n") // codecommit uses GIT as the request method + .append(uri.getPath()).append("\n") // URI request path + .append("\n") // Query string, always empty for codecommit + // Next is canonical headers, codecommit only requires the host header + .append("host:").append(uri.getHost()).append("\n").append("\n") // canonical + // headers + // are + // always + // terminated + // by + // newline + .append("host\n"); // The list of canonical headers, only one for + // codecommit + + MessageDigest digest = MessageDigest.getInstance(SHA_256); + + return digest.digest(canonicalRequest.toString().getBytes()); + } + + /** + * Convert bytes to a hex string. + * @param bytes the bytes + * @return a string of hex characters encoding the bytes. + */ + private static String bytesToHexString(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); + } + + /** + * This provider can handle uris like + * https://git-codecommit.$AWS_REGION.amazonaws.com/v1/repos/$REPO . + * @param uri uri to parse + * @return {@code true} if the URI can be handled + */ + public static boolean canHandle(String uri) { + if (!hasText(uri)) { + return false; + } + + try { + URL url = new URL(uri); + URI u = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), + url.getPort(), url.getPath(), url.getQuery(), url.getRef()); + if (u.getScheme().equals("https")) { + String host = u.getHost(); + if (host.endsWith(".amazonaws.com") + && host.startsWith("git-codecommit.")) { + return true; + } + } + } + catch (Throwable t) { + // ignore all, we can't handle it + } + + return false; + } + /** * This credentials provider cannot run interactively. * @return false @@ -99,7 +229,6 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { return false; } - /** * We support username and password credential items only. * @see org.eclipse.jgit.transport.CredentialsProvider#supports(org.eclipse.jgit.transport.CredentialItem[]) @@ -119,34 +248,37 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { } return true; } - + /** - * Get the AWSCredentials. If an AWSCredentialProvider was specified, use that, otherwise, - * create a new AWSCredentialsProvider. If the username and password are provided, then - * use those directly as AWSCredentials. Otherwise us the {@link DefaultAWSCredentialsProviderChain} - * as is standard with AWS applications. + * Get the AWSCredentials. If an AWSCredentialProvider was specified, use that, + * otherwise, create a new AWSCredentialsProvider. If the username and password are + * provided, then use those directly as AWSCredentials. Otherwise us the + * {@link DefaultAWSCredentialsProviderChain} as is standard with AWS applications. * @return the AWS credentials. */ private AWSCredentials retrieveAwsCredentials() { - if (awsCredentialProvider == null) { - if (username != null && password != null) { - logger.debug("Creating a static AWSCredentialsProvider"); - awsCredentialProvider = new AWSStaticCredentialsProvider(new BasicAWSCredentials(username, password)); - } else { - logger.debug("Creating a default AWSCredentialsProvider"); - awsCredentialProvider = new DefaultAWSCredentialsProviderChain(); + if (this.awsCredentialProvider == null) { + if (this.username != null && this.password != null) { + this.logger.debug("Creating a static AWSCredentialsProvider"); + this.awsCredentialProvider = new AWSStaticCredentialsProvider( + new BasicAWSCredentials(this.username, this.password)); + } + else { + this.logger.debug("Creating a default AWSCredentialsProvider"); + this.awsCredentialProvider = new DefaultAWSCredentialsProviderChain(); } } - return awsCredentialProvider.getCredentials(); + return this.awsCredentialProvider.getCredentials(); } - /** * Get the username and password to use for the given uri. - * @see org.eclipse.jgit.transport.CredentialsProvider#get(org.eclipse.jgit.transport.URIish, org.eclipse.jgit.transport.CredentialItem[]) + * @see org.eclipse.jgit.transport.CredentialsProvider#get(org.eclipse.jgit.transport.URIish, + * org.eclipse.jgit.transport.CredentialItem[]) */ @Override - public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem { + public boolean get(URIish uri, CredentialItem... items) + throws UnsupportedCredentialItem { String codeCommitPassword; String awsAccessKey; String awsSecretKey; @@ -156,87 +288,49 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { awsKey.append(awsCredentials.getAWSAccessKeyId()); awsSecretKey = awsCredentials.getAWSSecretKey(); if (awsCredentials instanceof AWSSessionCredentials) { - AWSSessionCredentials sessionCreds = (AWSSessionCredentials) awsCredentials; + AWSSessionCredentials sessionCreds = (AWSSessionCredentials) awsCredentials; if (sessionCreds.getSessionToken() != null) { - awsKey.append('%') - .append(sessionCreds.getSessionToken()); + awsKey.append('%').append(sessionCreds.getSessionToken()); } } awsAccessKey = awsKey.toString(); - } catch (Throwable t) { - logger.warn("Unable to retrieve AWS Credentials", t); + } + catch (Throwable t) { + this.logger.warn("Unable to retrieve AWS Credentials", t); return false; } try { codeCommitPassword = calculateCodeCommitPassword(uri, awsSecretKey); - } catch (Throwable t) { - logger.warn("Error calculating the AWS CodeCommit password", t); + } + catch (Throwable t) { + this.logger.warn("Error calculating the AWS CodeCommit password", t); return false; } - + for (CredentialItem i : items) { if (i instanceof CredentialItem.Username) { ((CredentialItem.Username) i).setValue(awsAccessKey); - logger.trace("Returning username " + awsAccessKey); + this.logger.trace("Returning username " + awsAccessKey); continue; } if (i instanceof CredentialItem.Password) { ((CredentialItem.Password) i).setValue(codeCommitPassword.toCharArray()); - logger.trace("Returning password " + codeCommitPassword); + this.logger.trace("Returning password " + codeCommitPassword); continue; } - if (i instanceof CredentialItem.StringType && i.getPromptText().equals("Password: ")) { //$NON-NLS-1$ + if (i instanceof CredentialItem.StringType + && i.getPromptText().equals("Password: ")) { //$NON-NLS-1$ ((CredentialItem.StringType) i).setValue(codeCommitPassword); - logger.trace("Returning password string " + codeCommitPassword); + this.logger.trace("Returning password string " + codeCommitPassword); continue; } - throw new UnsupportedCredentialItem(uri, i.getClass().getName() + ":" + i.getPromptText()); //$NON-NLS-1$ + throw new UnsupportedCredentialItem(uri, + i.getClass().getName() + ":" + i.getPromptText()); //$NON-NLS-1$ } return true; } - - /** - * Calculate the AWS CodeCommit password for the provided URI and AWS secret key. - * This uses the algorithm published by AWS at - * http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html - * @param uri the codecommit repository uri - * @param awsSecretKey the aws secret key - * @return the password to use in the git request - */ - protected static String calculateCodeCommitPassword(URIish uri, String awsSecretKey) { - String[] split = uri.getHost().split("\\."); - if (split.length < 4) { - throw new CredentialException("Cannot detect AWS region from URI", null); - } - String region = split[1]; - Date now = new Date(); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - String dateStamp = dateFormat.format(now); - String shortDateStamp = dateStamp.substring(0, 8); - - String codeCommitPassword; - try { - StringBuilder stringToSign = new StringBuilder(); - stringToSign.append("AWS4-HMAC-SHA256\n") - .append(dateStamp).append("\n") - .append(shortDateStamp) - .append("/").append(region) - .append("/codecommit/aws4_request\n") - .append(bytesToHexString(canonicalRequestDigest(uri))); - - byte[] signedRequest = sign(awsSecretKey, shortDateStamp, region, stringToSign.toString()); - codeCommitPassword = dateStamp + "Z" + bytesToHexString(signedRequest); - } catch (Exception e) { - throw new CredentialException("Error calculating AWS CodeCommit password", e); - } - - return codeCommitPassword; - } - /** * Throw out cached data and force retrieval of AWS credentials. * @param uri This parameter is not used in this implementation. @@ -250,64 +344,11 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { // its AWSCredentials object. } - private static byte[] hmacSha256(String data, byte[] key) throws Exception { - String algorithm = HMAC_SHA256; - Mac mac = Mac.getInstance(algorithm); - mac.init(new SecretKeySpec(key, algorithm)); - return mac.doFinal(data.getBytes(UTF8)); - } - - private static byte[] sign(String secret, String shortDateStamp, String region, String toSign) throws Exception { - byte[] kSecret = ("AWS4" + secret).getBytes(UTF8); - byte[] kDate = hmacSha256(shortDateStamp, kSecret); - byte[] kRegion = hmacSha256(region, kDate); - byte[] kService = hmacSha256("codecommit", kRegion); - byte[] kSigning = hmacSha256("aws4_request", kService); - return hmacSha256(toSign, kSigning); - } - - /** - * Creates a message digest - * @param uri - * @return - * @throws NoSuchAlgorithmException - */ - private static byte[] canonicalRequestDigest(URIish uri) throws NoSuchAlgorithmException { - StringBuilder canonicalRequest = new StringBuilder(); - canonicalRequest.append("GIT\n") // codecommit uses GIT as the request method - .append(uri.getPath()).append("\n") // URI request path - .append("\n") // Query string, always empty for codecommit - // Next is canonical headers, codecommit only requires the host header - .append("host:").append(uri.getHost()).append("\n") - .append("\n") // canonical headers are always terminated by newline - .append("host\n"); // The list of canonical headers, only one for codecommit - - MessageDigest digest = MessageDigest.getInstance(SHA_256); - - return digest.digest(canonicalRequest.toString().getBytes()); - } - - /** - * Convert bytes to a hex string - * @param bytes the bytes - * @return a string of hex characters encoding the bytes. - */ - private static String bytesToHexString(byte[] bytes) { - char[] hexChars = new char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) { - int v = bytes[j] & 0xFF; - hexChars[j * 2] = hexArray[v >>> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; - } - return new String(hexChars); - } - - /** * @return the awsCredentialProvider */ public AWSCredentialsProvider getAwsCredentialProvider() { - return awsCredentialProvider; + return this.awsCredentialProvider; } /** @@ -317,36 +358,11 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { this.awsCredentialProvider = awsCredentialProvider; } - /** - * This provider can handle uris like https://git-codecommit.$AWS_REGION.amazonaws.com/v1/repos/$REPO - * @see org.springframework.cloud.config.server.credentials.GitCredentialsProvider#canHandleUri(java.lang.String) - */ - public static boolean canHandle(String uri) { - if (!hasText(uri)) { - return false; - } - - try { - URL url = new URL(uri); - URI u = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); - if (u.getScheme().equals("https")) { - String host = u.getHost(); - if (host.endsWith(".amazonaws.com") && host.startsWith("git-codecommit.")) { - return true; - } - } - } catch (Throwable t) { - // ignore all, we can't handle it - } - - return false; - } - /** * @return the username */ public String getUsername() { - return username; + return this.username; } /** @@ -360,7 +376,7 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { * @return the password */ public String getPassword() { - return password; + return this.password; } /** @@ -371,8 +387,8 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { } /** - * Simple implementation of AWSCredentialsProvider that just wraps static AWSCredentials. - * AWS Actually provides this class in newer versions of the AWS API. + * Simple implementation of AWSCredentialsProvider that just wraps static + * AWSCredentials. AWS Actually provides this class in newer versions of the AWS API. */ public class AWSStaticCredentialsProvider implements AWSCredentialsProvider { @@ -383,7 +399,7 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { } public AWSCredentials getCredentials() { - return credentials; + return this.credentials; } public void refresh() { @@ -391,4 +407,5 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider { } } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/CredentialException.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/CredentialException.java index ab222d80..884934e5 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/CredentialException.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/CredentialException.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,6 @@ package org.springframework.cloud.config.server.support; @SuppressWarnings("serial") public class CredentialException extends RuntimeException { - /** - * - */ public CredentialException(String message, Throwable cause) { super(message, cause); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/EnvironmentPropertySource.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/EnvironmentPropertySource.java index d1e91bf8..4c0f9580 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/EnvironmentPropertySource.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/EnvironmentPropertySource.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.support; import java.util.Map; @@ -12,6 +28,14 @@ import org.springframework.core.env.StandardEnvironment; */ public class EnvironmentPropertySource extends PropertySource { + // "\${" (from text) or "\\${" from JSON to signal escaped placeholder + private static final Pattern ESCAPED_PLACEHOLDERS = Pattern + .compile("[\\\\]{1,2}\\$\\{"); + + public EnvironmentPropertySource(Environment sources) { + super("cloudEnvironment", sources); + } + public static StandardEnvironment prepareEnvironment(Environment environment) { StandardEnvironment standardEnvironment = new StandardEnvironment(); standardEnvironment.getPropertySources() @@ -23,18 +47,11 @@ public class EnvironmentPropertySource extends PropertySource { return standardEnvironment; } - // "\${" (from text) or "\\${" from JSON to signal escaped placeholder - private static final Pattern ESCAPED_PLACEHOLDERS = Pattern.compile("[\\\\]{1,2}\\$\\{"); - public static String resolvePlaceholders(StandardEnvironment preparedEnvironment, String text) { - // Mask out escaped placeholders - text = ESCAPED_PLACEHOLDERS.matcher(text).replaceAll("\\$_{"); - return preparedEnvironment.resolvePlaceholders(text).replace("$_{", "${"); - } - - public EnvironmentPropertySource(Environment sources) { - super("cloudEnvironment", sources); + // Mask out escaped placeholders + text = ESCAPED_PLACEHOLDERS.matcher(text).replaceAll("\\$_{"); + return preparedEnvironment.resolvePlaceholders(text).replace("$_{", "${"); } @Override diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/EnvironmentRepositoryProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/EnvironmentRepositoryProperties.java index 1e080ec0..1a191ea2 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/EnvironmentRepositoryProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/EnvironmentRepositoryProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.support; /** * @author Dylan Roberts */ public interface EnvironmentRepositoryProperties { - void setOrder(int order); + + void setOrder(int order); + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitCredentialsProviderFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitCredentialsProviderFactory.java index a35c2b8e..4233114e 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitCredentialsProviderFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitCredentialsProviderFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,19 +28,19 @@ import static org.springframework.util.StringUtils.hasText; /** * A CredentialsProvider factory for Git repositories. Can handle AWS CodeCommit * repositories and other repositories with username/password. - * + * * @author Don Laidlaw * @author Gareth Clay * */ public class GitCredentialsProviderFactory { + protected Log logger = LogFactory.getLog(getClass()); /** - * Enable the AWS Code Commit credentials provider for Git URI's - * that match the AWS Code Commit pattern of - * https://git-codecommit.${AWS_REGION}.amazonaws.com/${repoPath}. - * Enabled by default. + * Enable the AWS Code Commit credentials provider for Git URI's that match the AWS + * Code Commit pattern of + * https://git-codecommit.${AWS_REGION}.amazonaws.com/${repoPath}. Enabled by default. */ protected boolean awsCodeCommitEnabled = true; @@ -53,11 +53,12 @@ public class GitCredentialsProviderFactory { * @param password the password provided for the repository (may be null) * @param passphrase the passphrase to unlock the ssh private key (may be null) * @return the first matched credentials provider or the default or null. - * @deprecated in favour of {@link #createFor(String, String, String, String, boolean)} + * @deprecated in favour of + * {@link #createFor(String, String, String, String, boolean)} */ @Deprecated public CredentialsProvider createFor(String uri, String username, String password, - String passphrase) { + String passphrase) { return createFor(uri, username, password, passphrase, false); } @@ -66,9 +67,9 @@ public class GitCredentialsProviderFactory { * and the username or passphrase has text, then create a default using the provided * username and password or passphrase. * - * If skipSslValidation is true and the URI has an https scheme, the default credential - * provider's behaviour is modified to suppress any SSL validation errors that occur - * when communicating via the URI. + * If skipSslValidation is true and the URI has an https scheme, the default + * credential provider's behaviour is modified to suppress any SSL validation errors + * that occur when communicating via the URI. * * Otherwise null. * @param uri the URI of the repository (cannot be null) @@ -82,49 +83,54 @@ public class GitCredentialsProviderFactory { String passphrase, boolean skipSslValidation) { CredentialsProvider provider = null; if (awsAvailable() && AwsCodeCommitCredentialProvider.canHandle(uri)) { - logger.debug("Constructing AwsCodeCommitCredentialProvider for URI " + uri); + this.logger + .debug("Constructing AwsCodeCommitCredentialProvider for URI " + uri); AwsCodeCommitCredentialProvider aws = new AwsCodeCommitCredentialProvider(); aws.setUsername(username); aws.setPassword(password); provider = aws; } else if (hasText(username)) { - logger.debug("Constructing UsernamePasswordCredentialsProvider for URI " + uri); - provider = new UsernamePasswordCredentialsProvider(username, password.toCharArray()); + this.logger.debug( + "Constructing UsernamePasswordCredentialsProvider for URI " + uri); + provider = new UsernamePasswordCredentialsProvider(username, + password.toCharArray()); } else if (hasText(passphrase)) { - logger.debug("Constructing PassphraseCredentialsProvider for URI " + uri); + this.logger + .debug("Constructing PassphraseCredentialsProvider for URI " + uri); provider = new PassphraseCredentialsProvider(passphrase); } if (skipSslValidation && GitSkipSslValidationCredentialsProvider.canHandle(uri)) { - logger.debug("Constructing GitSkipSslValidationCredentialsProvider for URI " - + uri); + this.logger + .debug("Constructing GitSkipSslValidationCredentialsProvider for URI " + + uri); provider = new GitSkipSslValidationCredentialsProvider(provider); } if (provider == null) { - logger.debug("No credentials provider required for URI " + uri); + this.logger.debug("No credentials provider required for URI " + uri); } return provider; } - + /** * Check to see if the AWS Authentication API is available. - * @return true if the com.amazonaws.auth.DefaultAWSCredentialsProviderChain is present, - * false otherwise. + * @return true if the com.amazonaws.auth.DefaultAWSCredentialsProviderChain is + * present, false otherwise. */ private boolean awsAvailable() { - return awsCodeCommitEnabled - && ClassUtils.isPresent("com.amazonaws.auth.DefaultAWSCredentialsProviderChain", null); + return this.awsCodeCommitEnabled && ClassUtils + .isPresent("com.amazonaws.auth.DefaultAWSCredentialsProviderChain", null); } /** * @return the awsCodeCommitEnabled */ public boolean isAwsCodeCommitEnabled() { - return awsCodeCommitEnabled; + return this.awsCodeCommitEnabled; } /** @@ -133,5 +139,5 @@ public class GitCredentialsProviderFactory { public void setAwsCodeCommitEnabled(boolean awsCodeCommitEnabled) { this.awsCodeCommitEnabled = awsCodeCommitEnabled; } - + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProvider.java index 955fc184..93cb5c6d 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.support; import java.util.ArrayList; @@ -38,7 +39,8 @@ import org.eclipse.jgit.transport.URIish; */ public class GitSkipSslValidationCredentialsProvider extends CredentialsProvider { - private static final Pattern FORMAT_PLACEHOLDER_PATTERN = Pattern.compile("\\s*\\{\\d}\\s*"); + private static final Pattern FORMAT_PLACEHOLDER_PATTERN = Pattern + .compile("\\s*\\{\\d}\\s*"); private final CredentialsProvider delegate; @@ -47,15 +49,21 @@ public class GitSkipSslValidationCredentialsProvider extends CredentialsProvider } /** - * This provider can handle uris like https://github.com/org/repo + * This provider can handle uris like https://github.com/org/repo . + * @param uri uri to verify if can be handled + * @return {@code true} if it can be handled */ public static boolean canHandle(String uri) { return uri != null && uri.toLowerCase().startsWith("https://"); } + private static String stripFormattingPlaceholders(String string) { + return FORMAT_PLACEHOLDER_PATTERN.matcher(string).replaceAll(""); + } + @Override public boolean isInteractive() { - return (delegate != null) && delegate.isInteractive(); + return (this.delegate != null) && this.delegate.isInteractive(); } @Override @@ -65,8 +73,9 @@ public class GitSkipSslValidationCredentialsProvider extends CredentialsProvider for (CredentialItem item : items) { if (item instanceof CredentialItem.InformationalMessage && item.getPromptText() != null && item.getPromptText() - .contains(JGitText.get().sslFailureTrustExplanation)) + .contains(JGitText.get().sslFailureTrustExplanation)) { continue; + } if (item instanceof CredentialItem.YesNoType && item.getPromptText() != null && (item.getPromptText().equals(JGitText.get().sslTrustNow) @@ -74,14 +83,15 @@ public class GitSkipSslValidationCredentialsProvider extends CredentialsProvider .startsWith(stripFormattingPlaceholders( JGitText.get().sslTrustForRepo)) || item.getPromptText() - .equals(JGitText.get().sslTrustAlways))) + .equals(JGitText.get().sslTrustAlways))) { continue; + } unprocessedItems.add(item); } - return unprocessedItems.isEmpty() || (delegate != null - && delegate.supports(unprocessedItems.toArray(new CredentialItem[0]))); + return unprocessedItems.isEmpty() || (this.delegate != null && this.delegate + .supports(unprocessedItems.toArray(new CredentialItem[0]))); } @Override @@ -116,8 +126,9 @@ public class GitSkipSslValidationCredentialsProvider extends CredentialsProvider if (unprocessedItems.isEmpty()) { return true; } - if (delegate != null) { - return delegate.get(uri, unprocessedItems.toArray(new CredentialItem[0])); + if (this.delegate != null) { + return this.delegate.get(uri, + unprocessedItems.toArray(new CredentialItem[0])); } throw new UnsupportedCredentialItem(uri, unprocessedItems.size() + " credential items not supported"); @@ -125,12 +136,9 @@ public class GitSkipSslValidationCredentialsProvider extends CredentialsProvider @Override public void reset(URIish uri) { - if (delegate != null) { - delegate.reset(uri); + if (this.delegate != null) { + this.delegate.reset(uri); } } - private static String stripFormattingPlaceholders(String string) { - return FORMAT_PLACEHOLDER_PATTERN.matcher(string).replaceAll(""); - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClientSupport.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClientSupport.java index 47eddbf3..8080c7fc 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClientSupport.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClientSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.support; import java.net.ProxySelector; @@ -34,35 +35,45 @@ import org.springframework.util.CollectionUtils; /** * @author Dylan Roberts */ -public class HttpClientSupport { +public final class HttpClientSupport { - public static HttpClientBuilder builder(HttpEnvironmentRepositoryProperties environmentProperties) - throws GeneralSecurityException { - SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); - HttpClientBuilder httpClientBuilder = HttpClients.custom(); + private HttpClientSupport() { + throw new IllegalStateException("Can't instantiate a utility class"); + } - if (environmentProperties.isSkipSslValidation()) { - sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true); - httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier()); - } + public static HttpClientBuilder builder( + HttpEnvironmentRepositoryProperties environmentProperties) + throws GeneralSecurityException { + SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); + HttpClientBuilder httpClientBuilder = HttpClients.custom(); - if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) { - ProxyHostProperties httpsProxy = environmentProperties.getProxy().get(ProxyHostProperties.ProxyForScheme.HTTPS); - ProxyHostProperties httpProxy = environmentProperties.getProxy().get(ProxyHostProperties.ProxyForScheme.HTTP); + if (environmentProperties.isSkipSslValidation()) { + sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true); + httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier()); + } - httpClientBuilder.setRoutePlanner(new SchemeBasedRoutePlanner(httpsProxy, httpProxy)); - httpClientBuilder.setDefaultCredentialsProvider(new ProxyHostCredentialsProvider(httpProxy, httpsProxy)); - } else { - httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); - httpClientBuilder.setDefaultCredentialsProvider(new SystemDefaultCredentialsProvider()); - } + if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) { + ProxyHostProperties httpsProxy = environmentProperties.getProxy() + .get(ProxyHostProperties.ProxyForScheme.HTTPS); + ProxyHostProperties httpProxy = environmentProperties.getProxy() + .get(ProxyHostProperties.ProxyForScheme.HTTP); + + httpClientBuilder + .setRoutePlanner(new SchemeBasedRoutePlanner(httpsProxy, httpProxy)); + httpClientBuilder.setDefaultCredentialsProvider( + new ProxyHostCredentialsProvider(httpProxy, httpsProxy)); + } + else { + httpClientBuilder.setRoutePlanner( + new SystemDefaultRoutePlanner(ProxySelector.getDefault())); + httpClientBuilder.setDefaultCredentialsProvider( + new SystemDefaultCredentialsProvider()); + } + + int timeout = environmentProperties.getTimeout() * 1000; + return httpClientBuilder.setSSLContext(sslContextBuilder.build()) + .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(timeout) + .setConnectTimeout(timeout).build()); + } - int timeout = environmentProperties.getTimeout() * 1000; - return httpClientBuilder - .setSSLContext(sslContextBuilder.build()) - .setDefaultRequestConfig(RequestConfig.custom() - .setSocketTimeout(timeout) - .setConnectTimeout(timeout) - .build()); - } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpEnvironmentRepositoryProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpEnvironmentRepositoryProperties.java index 12dc2154..fb6e7c16 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpEnvironmentRepositoryProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpEnvironmentRepositoryProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.support; import java.util.Map; import org.springframework.cloud.config.server.proxy.ProxyHostProperties; -import org.springframework.cloud.config.server.support.EnvironmentRepositoryProperties; /** * @author Dylan Roberts */ -public interface HttpEnvironmentRepositoryProperties extends EnvironmentRepositoryProperties { +public interface HttpEnvironmentRepositoryProperties + extends EnvironmentRepositoryProperties { - Map getProxy(); + Map getProxy(); - boolean isSkipSslValidation(); + boolean isSkipSslValidation(); + + int getTimeout(); - int getTimeout(); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/PassphraseCredentialsProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/PassphraseCredentialsProvider.java index 9e27088f..1deb2d73 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/PassphraseCredentialsProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/PassphraseCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,23 @@ import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.URIish; +/** + * A {@link CredentialsProvider} that uses a passphrase. + * + * @author Chris Fraser + */ public class PassphraseCredentialsProvider extends CredentialsProvider { + + /** + * Prompt to skip iteration for. + */ public static final String PROMPT = "Passphrase for"; + private final String passphrase; /** * Initialize the provider with a the ssh passphrase. - * - * @param passphrase + * @param passphrase passphrase to populate the credential items with */ public PassphraseCredentialsProvider(String passphrase) { super(); @@ -51,9 +60,11 @@ public class PassphraseCredentialsProvider extends CredentialsProvider { @Override public boolean supports(CredentialItem... items) { for (final CredentialItem item : items) { - if (item instanceof CredentialItem.StringType && item.getPromptText().startsWith(PROMPT)) { + if (item instanceof CredentialItem.StringType + && item.getPromptText().startsWith(PROMPT)) { continue; - } else { + } + else { return false; } } @@ -62,26 +73,26 @@ public class PassphraseCredentialsProvider extends CredentialsProvider { /** * Ask for the credential items to be populated with the passphrase. - * - * @param uri - * the URI of the remote resource that needs authentication. - * @param items - * the items the application requires to complete authentication. - * @return {@code true} if the request was successful and values were - * supplied; {@code false} if the user canceled the request and did - * not supply all requested values. - * @throws UnsupportedCredentialItem - * if one of the items supplied is not supported. - */ + * @param uri the URI of the remote resource that needs authentication. + * @param items the items the application requires to complete authentication. + * @return {@code true} if the request was successful and values were supplied; + * {@code false} if the user canceled the request and did not supply all requested + * values. + * @throws UnsupportedCredentialItem if one of the items supplied is not supported. + */ @Override - public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem { + public boolean get(URIish uri, CredentialItem... items) + throws UnsupportedCredentialItem { for (final CredentialItem item : items) { - if (item instanceof CredentialItem.StringType && item.getPromptText().startsWith(PROMPT)) { - ((CredentialItem.StringType) item).setValue(passphrase); + if (item instanceof CredentialItem.StringType + && item.getPromptText().startsWith(PROMPT)) { + ((CredentialItem.StringType) item).setValue(this.passphrase); continue; } - throw new UnsupportedCredentialItem(uri, item.getClass().getName() + ":" + item.getPromptText()); + throw new UnsupportedCredentialItem(uri, + item.getClass().getName() + ":" + item.getPromptText()); } return true; } + } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/test/ConfigServerTestUtils.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/test/ConfigServerTestUtils.java index 748df3da..78c9fb7a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/test/ConfigServerTestUtils.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/test/ConfigServerTestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,26 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.test; +import java.io.File; +import java.io.IOException; + import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryCache.FileKey; import org.eclipse.jgit.util.FS; import org.eclipse.jgit.util.FileUtils; + import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.environment.PropertySource; import org.springframework.util.FileSystemUtils; import org.springframework.util.StringUtils; -import java.io.File; -import java.io.IOException; - /** * @author Dave Syer * @author Daniel Lavoie */ -public class ConfigServerTestUtils { +public final class ConfigServerTestUtils { + private ConfigServerTestUtils() { + throw new IllegalStateException("Can't instantiate utility class"); + } + + /** + * Location where the repos get copied to. + */ public static final String REPO_PREFIX = "target/repos/"; public static Repository prepareBareRemote() throws IOException { @@ -57,8 +66,8 @@ public class ConfigServerTestUtils { return prepareLocalRepo("./", "target/repos", repoPath, "target/config"); } - public static String prepareLocalRepo(String baseDir, String buildDir, String repoPath, - String checkoutDir) throws IOException { + public static String prepareLocalRepo(String baseDir, String buildDir, + String repoPath, String checkoutDir) throws IOException { buildDir = baseDir + buildDir; new File(buildDir).mkdirs(); if (!repoPath.startsWith("/")) { @@ -91,7 +100,8 @@ public class ConfigServerTestUtils { return "file:" + buildDir + repoPath; } - public static String prepareLocalSvnRepo(String sourceDir, String checkoutDir) throws Exception { + public static String prepareLocalSvnRepo(String sourceDir, String checkoutDir) + throws Exception { File sourceDirFile = new File(sourceDir); sourceDirFile.mkdirs(); File local = new File(checkoutDir); @@ -101,7 +111,6 @@ public class ConfigServerTestUtils { local.mkdirs(); FileSystemUtils.copyRecursively(sourceDirFile, local); return StringUtils.cleanPath("file:///" + local.getAbsolutePath()); - } public static String getBaseDirectory(String potentialRoot) { @@ -120,9 +129,10 @@ public class ConfigServerTestUtils { return FileSystemUtils.deleteRecursively(dest); } - public static Object getProperty(Environment env, String sourceNameEndsWith, String property) { - for(PropertySource source: env.getPropertySources()) { - if(source.getName().endsWith(sourceNameEndsWith)) { + public static Object getProperty(Environment env, String sourceNameEndsWith, + String property) { + for (PropertySource source : env.getPropertySources()) { + if (source.getName().endsWith(sourceNameEndsWith)) { return source.getSource().get(property); } } diff --git a/spring-cloud-config-server/src/main/resources/META-INF/spring.factories b/spring-cloud-config-server/src/main/resources/META-INF/spring.factories index 4c3a8b2e..2ff4c24f 100644 --- a/spring-cloud-config-server/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-config-server/src/main/resources/META-INF/spring.factories @@ -2,15 +2,12 @@ org.springframework.cloud.bootstrap.BootstrapConfiguration=\ org.springframework.cloud.config.server.bootstrap.ConfigServerBootstrapConfiguration,\ org.springframework.cloud.config.server.config.EncryptionAutoConfiguration - # Application listeners org.springframework.context.ApplicationListener=\ org.springframework.cloud.config.server.bootstrap.ConfigServerBootstrapApplicationListener - # Autoconfiguration org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.config.server.config.ConfigServerAutoConfiguration,\ org.springframework.cloud.config.server.config.EncryptionAutoConfiguration - org.springframework.boot.diagnostics.FailureAnalyzer=\ org.springframework.cloud.config.server.diagnostics.GitUriFailureAnalyzer diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/AdhocTestSuite.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/AdhocTestSuite.java index 3ca53211..ba131c46 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/AdhocTestSuite.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/AdhocTestSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,25 +63,19 @@ import org.springframework.cloud.config.server.ssh.SshUriPropertyProcessorTest; */ @RunWith(Suite.class) @SuiteClasses({ NativeConfigServerIntegrationTests.class, - GenericResourceRepositoryTests.class, - ResourceControllerTests.class, - ResourceControllerIntegrationTests.class, - ConfigClientOnIntegrationTests.class, - ConfigServerApplicationTests.class, - VanillaConfigServerIntegrationTests.class, + GenericResourceRepositoryTests.class, ResourceControllerTests.class, + ResourceControllerIntegrationTests.class, ConfigClientOnIntegrationTests.class, + ConfigServerApplicationTests.class, VanillaConfigServerIntegrationTests.class, EnvironmentControllerIntegrationTests.class, MultipleJGitEnvironmentRepositoryIntegrationTests.class, EnvironmentEncryptorEnvironmentRepositoryTests.class, EnvironmentControllerTests.class, SVNKitEnvironmentRepositoryIntegrationTests.class, MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.class, - JdbcEnvironmentRepositoryTests.class, - CompositeEnvironmentRepositoryTests.class, + JdbcEnvironmentRepositoryTests.class, CompositeEnvironmentRepositoryTests.class, JGitEnvironmentRepositoryConcurrencyTests.class, - NativeEnvironmentRepositoryTests.class, - JGitEnvironmentRepositoryTests.class, - SVNKitEnvironmentRepositoryTests.class, - VaultEnvironmentRepositoryTests.class, + NativeEnvironmentRepositoryTests.class, JGitEnvironmentRepositoryTests.class, + SVNKitEnvironmentRepositoryTests.class, VaultEnvironmentRepositoryTests.class, MultipleJGitEnvironmentRepositoryTests.class, JGitEnvironmentRepositoryIntegrationTests.class, MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.class, @@ -97,18 +91,14 @@ import org.springframework.cloud.config.server.ssh.SshUriPropertyProcessorTest; EncryptionControllerTests.class, EncryptionIntegrationTests.ConfigSymmetricEncryptionIntegrationTests.class, EncryptionIntegrationTests.KeystoreConfigurationIntegrationTests.class, - KeyStoreTextEncryptorLocatorTests.class, - EnvironmentPrefixHelperTests.class, - SshUriPropertyProcessorTest.class, - PropertyBasedSshSessionFactoryTest.class, - SshPropertyValidatorTest.class, - CompositeIntegrationTests.class, + KeyStoreTextEncryptorLocatorTests.class, EnvironmentPrefixHelperTests.class, + SshUriPropertyProcessorTest.class, PropertyBasedSshSessionFactoryTest.class, + SshPropertyValidatorTest.class, CompositeIntegrationTests.class, SubversionConfigServerIntegrationTests.class, ConfigServerHealthIndicatorTests.class, CustomCompositeEnvironmentRepositoryTests.class, CustomEnvironmentRepositoryTests.class, - BootstrapConfigServerIntegrationTests.class, -}) + BootstrapConfigServerIntegrationTests.class }) @Ignore public class AdhocTestSuite { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/BootstrapConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/BootstrapConfigServerIntegrationTests.java index 167365e8..9ade9a00 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/BootstrapConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/BootstrapConfigServerIntegrationTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server; import java.io.IOException; @@ -5,23 +21,23 @@ import java.io.IOException; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.server.test.ConfigServerTestUtils; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, properties = {"spring.cloud.bootstrap.name:enable-bootstrap", - "encrypt.rsa.algorithm=DEFAULT", "encrypt.rsa.strong=false"}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles({"test", "encrypt"}) +@SpringBootTest(classes = ConfigServerApplication.class, properties = { + "spring.cloud.bootstrap.name:enable-bootstrap", "encrypt.rsa.algorithm=DEFAULT", + "encrypt.rsa.strong=false" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles({ "test", "encrypt" }) public class BootstrapConfigServerIntegrationTests { @LocalServerPort @@ -40,17 +56,17 @@ public class BootstrapConfigServerIntegrationTests { @Test public void contextLoads() { - Environment environment = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/", Environment.class); - assertFalse(environment.getPropertySources().isEmpty()); - assertEquals("bar", - environment.getPropertySources().get(0).getSource().get("info.foo")); + Environment environment = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + "/foo/development/", Environment.class); + assertThat(environment.getPropertySources().isEmpty()).isFalse(); + assertThat(environment.getPropertySources().get(0).getSource().get("info.foo")) + .isEqualTo("bar"); } @Test public void environmentBootstraps() throws Exception { - assertEquals("bar", foo); - assertEquals("foo", config); + assertThat(this.foo).isEqualTo("bar"); + assertThat(this.config).isEqualTo("foo"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeClasspathTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeClasspathTests.java index b98573e2..fdf1bc50 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeClasspathTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeClasspathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server; import org.junit.Test; @@ -25,87 +26,92 @@ import org.springframework.cloud.test.ModifiedClassPathRunner; public class CompositeClasspathTests { - @RunWith(ModifiedClassPathRunner.class) - @ClassPathExclusions("spring-jdbc-*.jar") - public static class JdbcTests { + @RunWith(ModifiedClassPathRunner.class) + @ClassPathExclusions("spring-jdbc-*.jar") + public static class JdbcTests { - @Test - public void contextLoads() { - new WebApplicationContextRunner() - .withUserConfiguration(ConfigServerApplication.class) - .withPropertyValues("spring.profiles.active:test,composite", - "spring.jmx.enabled=false", - "spring.config.name:compositeconfigserver", - "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[0].type:git", - "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", - "spring.cloud.config.server.composite[1].type:svn") - .run(context -> { - CompositeUtils.getCompositeTypeList(context.getEnvironment()); - }); - } - } + @Test + public void contextLoads() { + new WebApplicationContextRunner() + .withUserConfiguration(ConfigServerApplication.class) + .withPropertyValues("spring.profiles.active:test,composite", + "spring.jmx.enabled=false", + "spring.config.name:compositeconfigserver", + "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[0].type:git", + "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", + "spring.cloud.config.server.composite[1].type:svn") + .run(context -> { + CompositeUtils.getCompositeTypeList(context.getEnvironment()); + }); + } - @RunWith(ModifiedClassPathRunner.class) - @ClassPathExclusions("httpclient-*.jar") - public static class HttpClientTests { + } - @Test - public void contextLoads() { - new WebApplicationContextRunner() - .withUserConfiguration(ConfigServerApplication.class) - .withPropertyValues("spring.profiles.active:test,composite", - "spring.jmx.enabled=false", - "spring.config.name:compositeconfigserver", - "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[0].type:git", - "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", - "spring.cloud.config.server.composite[1].type:svn") - .run(context -> { - CompositeUtils.getCompositeTypeList(context.getEnvironment()); - }); - } - } + @RunWith(ModifiedClassPathRunner.class) + @ClassPathExclusions("httpclient-*.jar") + public static class HttpClientTests { - @RunWith(ModifiedClassPathRunner.class) - @ClassPathExclusions("svnkit-*.jar") - public static class SvnTests { + @Test + public void contextLoads() { + new WebApplicationContextRunner() + .withUserConfiguration(ConfigServerApplication.class) + .withPropertyValues("spring.profiles.active:test,composite", + "spring.jmx.enabled=false", + "spring.config.name:compositeconfigserver", + "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[0].type:git", + "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", + "spring.cloud.config.server.composite[1].type:svn") + .run(context -> { + CompositeUtils.getCompositeTypeList(context.getEnvironment()); + }); + } - @Test - public void contextLoads() { - new WebApplicationContextRunner() - .withUserConfiguration(ConfigServerApplication.class) - .withPropertyValues("spring.profiles.active:test,composite", - "spring.jmx.enabled=false", - "spring.config.name:compositeconfigserver", - "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[0].type:git", - "spring.cloud.config.server.composite[1].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[1].type:native") - .run(context -> { - CompositeUtils.getCompositeTypeList(context.getEnvironment()); - }); - } - } + } - @RunWith(ModifiedClassPathRunner.class) - @ClassPathExclusions("org.eclipse.jgit-*.jar") - public static class JGitTests { + @RunWith(ModifiedClassPathRunner.class) + @ClassPathExclusions("svnkit-*.jar") + public static class SvnTests { + + @Test + public void contextLoads() { + new WebApplicationContextRunner() + .withUserConfiguration(ConfigServerApplication.class) + .withPropertyValues("spring.profiles.active:test,composite", + "spring.jmx.enabled=false", + "spring.config.name:compositeconfigserver", + "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[0].type:git", + "spring.cloud.config.server.composite[1].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[1].type:native") + .run(context -> { + CompositeUtils.getCompositeTypeList(context.getEnvironment()); + }); + } + + } + + @RunWith(ModifiedClassPathRunner.class) + @ClassPathExclusions("org.eclipse.jgit-*.jar") + public static class JGitTests { + + @Test + public void contextLoads() { + new WebApplicationContextRunner() + .withUserConfiguration(ConfigServerApplication.class) + .withPropertyValues("spring.profiles.active:test,composite", + "spring.jmx.enabled=false", + "spring.config.name:compositeconfigserver", + "spring.cloud.config.server.composite[0].uri:file:///./target/repos/svn-config-repo", + "spring.cloud.config.server.composite[0].type:svn", + "spring.cloud.config.server.composite[1].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[1].type:native") + .run(context -> { + CompositeUtils.getCompositeTypeList(context.getEnvironment()); + }); + } + + } - @Test - public void contextLoads() { - new WebApplicationContextRunner() - .withUserConfiguration(ConfigServerApplication.class) - .withPropertyValues("spring.profiles.active:test,composite", - "spring.jmx.enabled=false", - "spring.config.name:compositeconfigserver", - "spring.cloud.config.server.composite[0].uri:file:///./target/repos/svn-config-repo", - "spring.cloud.config.server.composite[0].type:svn", - "spring.cloud.config.server.composite[1].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[1].type:native") - .run(context -> { - CompositeUtils.getCompositeTypeList(context.getEnvironment()); - }); - } - } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java index 2339742c..9b5315cc 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; @@ -26,8 +28,7 @@ import org.springframework.cloud.config.server.test.ConfigServerTestUtils; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** @@ -35,104 +36,121 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Dylan Roberts */ public class CompositeIntegrationTests { + @RunWith(SpringRunner.class) - @SpringBootTest(classes = ConfigServerApplication.class, - properties = { "spring.config.name:compositeconfigserver", - "spring.cloud.config.server.svn.uri:file:///./target/repos/svn-config-repo", - "spring.cloud.config.server.svn.order:2", - "spring.cloud.config.server.git.uri:file:./target/repos/config-repo", - "spring.cloud.config.server.git.order:1"}, - webEnvironment = RANDOM_PORT) + @SpringBootTest(classes = ConfigServerApplication.class, properties = { + "spring.config.name:compositeconfigserver", + "spring.cloud.config.server.svn.uri:file:///./target/repos/svn-config-repo", + "spring.cloud.config.server.svn.order:2", + "spring.cloud.config.server.git.uri:file:./target/repos/config-repo", + "spring.cloud.config.server.git.order:1" }, webEnvironment = RANDOM_PORT) @ActiveProfiles({ "test", "git", "subversion" }) public static class StaticTests { + @LocalServerPort private int port; @BeforeClass public static void init() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); - ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/svn-config-repo", - "target/repos/svn-config-repo"); + ConfigServerTestUtils.prepareLocalSvnRepo( + "src/test/resources/svn-config-repo", "target/repos/svn-config-repo"); } @Test public void contextLoads() { - Environment environment = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/", Environment.class); - assertEquals(3, environment.getPropertySources().size()); - assertEquals("overrides", environment.getPropertySources().get(0).getName()); - assertTrue(environment.getPropertySources().get(1).getName().contains("config-repo") && - !environment.getPropertySources().get(1).getName().contains("svn-config-repo")); - assertTrue(environment.getPropertySources().get(2).getName().contains("svn-config-repo")); - assertEquals("{spring.cloud.config.enabled=true}", environment - .getPropertySources().get(0).getSource().toString()); + Environment environment = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + "/foo/development/", + Environment.class); + assertThat(3).isEqualTo(environment.getPropertySources().size()); + assertThat("overrides") + .isEqualTo(environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().get(1).getName() + .contains("config-repo") + && !environment.getPropertySources().get(1).getName() + .contains("svn-config-repo")).isTrue(); + assertThat(environment.getPropertySources().get(2).getName() + .contains("svn-config-repo")).isTrue(); + assertThat("{spring.cloud.config.enabled=true}").isEqualTo( + environment.getPropertySources().get(0).getSource().toString()); } @Test public void resourceEndpointsWork() { - //This request will get the file from the Git Repo - String text = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/composite/bar.properties", String.class); + // This request will get the file from the Git Repo + String text = new TestRestTemplate() + .getForObject( + "http://localhost:" + this.port + + "/foo/development/composite/bar.properties", + String.class); String expected = "foo: bar"; - assertEquals("invalid content", expected, text); + assertThat(expected).isEqualTo(text).as("invalid content"); - //This request will get the file from the SVN Repo - text = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/composite/bar.properties", String.class); - assertEquals("invalid content", expected, text); + // This request will get the file from the SVN Repo + text = new TestRestTemplate().getForObject("http://localhost:" + this.port + + "/foo/development/composite/bar.properties", String.class); + assertThat(expected).isEqualTo(text).as("invalid content"); } + } @RunWith(SpringRunner.class) - @SpringBootTest(classes = ConfigServerApplication.class, - properties = { "spring.config.name:compositeconfigserver", - "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[0].type:git", - "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", - "spring.cloud.config.server.composite[1].type:svn" - }, - webEnvironment = RANDOM_PORT) - @ActiveProfiles({ "test", "composite"}) + @SpringBootTest(classes = ConfigServerApplication.class, properties = { + "spring.config.name:compositeconfigserver", + "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[0].type:git", + "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", + "spring.cloud.config.server.composite[1].type:svn" }, webEnvironment = RANDOM_PORT) + @ActiveProfiles({ "test", "composite" }) public static class ListTests { + @LocalServerPort private int port; @BeforeClass public static void init() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); - ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/svn-config-repo", - "target/repos/svn-config-repo"); + ConfigServerTestUtils.prepareLocalSvnRepo( + "src/test/resources/svn-config-repo", "target/repos/svn-config-repo"); } @Test public void contextLoads() { - Environment environment = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/", Environment.class); - assertEquals(3, environment.getPropertySources().size()); - assertEquals("overrides", environment.getPropertySources().get(0).getName()); - assertTrue(environment.getPropertySources().get(1).getName().contains("config-repo") && - !environment.getPropertySources().get(1).getName().contains("svn-config-repo")); - assertTrue(environment.getPropertySources().get(2).getName().contains("svn-config-repo")); - assertEquals("{spring.cloud.config.enabled=true}", environment - .getPropertySources().get(0).getSource().toString()); + Environment environment = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + "/foo/development/", + Environment.class); + assertThat(environment.getPropertySources()).hasSize(3); + assertThat("overrides") + .isEqualTo(environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().get(1).getName() + .contains("config-repo") + && !environment.getPropertySources().get(1).getName() + .contains("svn-config-repo")).isTrue(); + assertThat(environment.getPropertySources().get(2).getName() + .contains("svn-config-repo")).isTrue(); + assertThat("{spring.cloud.config.enabled=true}").isEqualTo( + environment.getPropertySources().get(0).getSource().toString()); } @Test public void resourceEndpointsWork() { - //This request will get the file from the Git Repo - String text = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/composite/bar.properties", String.class); + // This request will get the file from the Git Repo + String text = new TestRestTemplate() + .getForObject( + "http://localhost:" + this.port + + "/foo/development/composite/bar.properties", + String.class); String expected = "foo: bar"; - assertEquals("invalid content", expected, text); + assertThat(expected).isEqualTo(text).as("invalid content"); - //This request will get the file from the SVN Repo - text = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/composite/bar.properties", String.class); - assertEquals("invalid content", expected, text); + // This request will get the file from the SVN Repo + text = new TestRestTemplate().getForObject("http://localhost:" + this.port + + "/foo/development/composite/bar.properties", String.class); + assertThat(expected).isEqualTo(text).as("invalid content"); } + } - } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOffIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOffIntegrationTests.java index db718625..08edda5b 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOffIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOffIntegrationTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server; import java.io.IOException; @@ -6,6 +22,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; + import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -25,8 +42,7 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.anyString; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @@ -49,15 +65,15 @@ public class ConfigClientOffIntegrationTests { @Test public void contextLoads() { - Environment environment = new TestRestTemplate().getForObject("http://localhost:" - + this.port + "/foo/development/", Environment.class); - assertTrue(environment.getPropertySources().isEmpty()); + Environment environment = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + "/foo/development/", Environment.class); + assertThat(environment.getPropertySources().isEmpty()).isTrue(); } @Test public void configClientDisabled() throws Exception { - assertEquals(0, BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.context, - ConfigServicePropertySourceLocator.class).length); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.context, + ConfigServicePropertySourceLocator.class).length).isEqualTo(0); } @Configuration @@ -67,14 +83,16 @@ public class ConfigClientOffIntegrationTests { @Bean public EnvironmentRepository environmentRepository() { EnvironmentRepository repository = Mockito.mock(EnvironmentRepository.class); - given(repository.findOne(anyString(), anyString(), anyString())).willReturn(new Environment("", "")); + given(repository.findOne(anyString(), anyString(), anyString())) + .willReturn(new Environment("", "")); return repository; } @Bean public ResourceRepository resourceRepository() { ResourceRepository repository = Mockito.mock(ResourceRepository.class); - given(repository.findOne(anyString(), anyString(), anyString(), anyString())).willReturn(new ByteArrayResource("".getBytes())); + given(repository.findOne(anyString(), anyString(), anyString(), anyString())) + .willReturn(new ByteArrayResource("".getBytes())); return repository; } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java index 0afd6e71..3c228a1f 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,21 @@ package org.springframework.cloud.config.server; +import java.io.IOException; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; + import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.config.client.ConfigServicePropertySourceLocator; import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.server.ConfigClientOnIntegrationTests.TestConfiguration; @@ -42,16 +45,12 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.anyString; @RunWith(SpringRunner.class) -@SpringBootTest(classes = TestConfiguration.class, properties = "spring.cloud.config.enabled:true", - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = TestConfiguration.class, properties = "spring.cloud.config.enabled:true", webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @DirtiesContext public class ConfigClientOnIntegrationTests { @@ -76,15 +75,15 @@ public class ConfigClientOnIntegrationTests { @Test public void contextLoads() { - Environment environment = new TestRestTemplate().getForObject("http://localhost:" - + this.port + "/foo/development/", Environment.class); - assertTrue(environment.getPropertySources().isEmpty()); + Environment environment = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + "/foo/development/", Environment.class); + assertThat(environment.getPropertySources().isEmpty()).isTrue(); } @Test public void configClientEnabled() throws Exception { - assertEquals(1, BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.context, - ConfigServicePropertySourceLocator.class).length); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.context, + ConfigServicePropertySourceLocator.class).length).isEqualTo(1); } @Configuration @@ -95,14 +94,16 @@ public class ConfigClientOnIntegrationTests { @Bean public EnvironmentRepository environmentRepository() { EnvironmentRepository repository = Mockito.mock(EnvironmentRepository.class); - given(repository.findOne(anyString(), anyString(), anyString())).willReturn(new Environment("", "")); + given(repository.findOne(anyString(), anyString(), anyString())) + .willReturn(new Environment("", "")); return repository; } @Bean public ResourceRepository resourceRepository() { ResourceRepository repository = Mockito.mock(ResourceRepository.class); - given(repository.findOne(anyString(), anyString(), anyString(), anyString())).willReturn(new ByteArrayResource("".getBytes())); + given(repository.findOne(anyString(), anyString(), anyString(), anyString())) + .willReturn(new ByteArrayResource("".getBytes())); return repository; } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigServerApplicationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigServerApplicationTests.java index f4bf6d60..78bb77f2 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigServerApplicationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigServerApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.cloud.config.server; import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; @@ -34,9 +35,11 @@ public class ConfigServerApplicationTests { @Test public void contextLoads() { - try (ConfigurableApplicationContext context = new SpringApplicationBuilder(ConfigServerApplication.class) - .properties("spring.config.name=configserver").run("--server.port=0")) { - + try (ConfigurableApplicationContext context = new SpringApplicationBuilder( + ConfigServerApplication.class) + .properties("spring.config.name=configserver") + .run("--server.port=0")) { + // empty } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java index 4a638a24..5180245c 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server; import org.junit.Test; @@ -24,21 +25,17 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.config.environment.Environment; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author Alberto C. Ríos */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, - properties = { - "spring.profiles.active:composite", - "spring.cloud.config.server.composite[0].type:credhub", - "spring.cloud.config.server.composite[0].url:https://credhub:8844" - }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ConfigServerApplication.class, properties = { + "spring.profiles.active:composite", + "spring.cloud.config.server.composite[0].type:credhub", + "spring.cloud.config.server.composite[0].url:https://credhub:8844" }, webEnvironment = RANDOM_PORT) public class CredhubCompositeConfigServerIntegrationTests extends CredhubIntegrationTest { @LocalServerPort @@ -47,12 +44,14 @@ public class CredhubCompositeConfigServerIntegrationTests extends CredhubIntegra @Test public void shouldRetrieveValuesFromCredhub() { Environment environment = new TestRestTemplate().getForObject( - "http://localhost:" + this.port + "/myapp/master/default", Environment.class); + "http://localhost:" + this.port + "/myapp/master/default", + Environment.class); - assertFalse(environment.getPropertySources().isEmpty()); - assertEquals("credhub-myapp", environment.getPropertySources().get(0).getName()); - assertEquals("{key=value}", - environment.getPropertySources().get(0).getSource().toString()); + assertThat(environment.getPropertySources().isEmpty()).isFalse(); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("credhub-myapp"); + assertThat(environment.getPropertySources().get(0).getSource().toString()) + .isEqualTo("{key=value}"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java index a408771b..53d2b811 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server; import org.junit.Test; @@ -24,20 +25,16 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.config.environment.Environment; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author Alberto C. Ríos */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, - properties = { - "spring.profiles.active:credhub", - "spring.cloud.config.server.credhub.url:https://credhub:8844" - }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ConfigServerApplication.class, properties = { + "spring.profiles.active:credhub", + "spring.cloud.config.server.credhub.url:https://credhub:8844" }, webEnvironment = RANDOM_PORT) public class CredhubConfigServerIntegrationTests extends CredhubIntegrationTest { @LocalServerPort @@ -46,12 +43,14 @@ public class CredhubConfigServerIntegrationTests extends CredhubIntegrationTest @Test public void shouldRetrieveValuesFromCredhub() { Environment environment = new TestRestTemplate().getForObject( - "http://localhost:" + this.port + "/myapp/master/default", Environment.class); + "http://localhost:" + this.port + "/myapp/master/default", + Environment.class); - assertFalse(environment.getPropertySources().isEmpty()); - assertEquals("credhub-myapp", environment.getPropertySources().get(0).getName()); - assertEquals("{key=value}", - environment.getPropertySources().get(0).getSource().toString()); + assertThat(environment.getPropertySources().isEmpty()).isFalse(); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("credhub-myapp"); + assertThat(environment.getPropertySources().get(0).getSource().toString()) + .isEqualTo("{key=value}"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubIntegrationTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubIntegrationTest.java index bcf60f37..8e76cc25 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubIntegrationTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubIntegrationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server; import org.junit.Before; @@ -40,20 +41,24 @@ public class CredhubIntegrationTest { @Before public void setUp() { - CredHubCredentialOperations credhubCredentialOperations = Mockito.mock(CredHubCredentialOperations.class); + CredHubCredentialOperations credhubCredentialOperations = Mockito + .mock(CredHubCredentialOperations.class); String expectedPath = "/myapp/master/default"; - SimpleCredentialName togglesCredentialName = new SimpleCredentialName(expectedPath + "/toggles"); - when(credhubCredentialOperations - .findByPath(expectedPath)) + SimpleCredentialName togglesCredentialName = new SimpleCredentialName( + expectedPath + "/toggles"); + when(credhubCredentialOperations.findByPath(expectedPath)) .thenReturn(singletonList(new CredentialSummary(togglesCredentialName))); JsonCredential credentials = new JsonCredential(); credentials.put("key", "value"); - when(credhubCredentialOperations - .getByName(new SimpleCredentialName(expectedPath + "/toggles"), JsonCredential.class)) - .thenReturn(new CredentialDetails<>("id1", togglesCredentialName, CredentialType.JSON, credentials)); + when(credhubCredentialOperations.getByName( + new SimpleCredentialName(expectedPath + "/toggles"), + JsonCredential.class)) + .thenReturn(new CredentialDetails<>("id1", togglesCredentialName, + CredentialType.JSON, credentials)); - when(credHubOperations.credentials()).thenReturn(credhubCredentialOperations); + when(this.credHubOperations.credentials()) + .thenReturn(credhubCredentialOperations); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeBootstrapFailureAnalyzerTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeBootstrapFailureAnalyzerTests.java index 85f1a79c..f12964da 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeBootstrapFailureAnalyzerTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeBootstrapFailureAnalyzerTests.java @@ -1,15 +1,31 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server; -import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; + import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.cloud.config.server.diagnostics.GitUriFailureAnalyzer; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * @author Ryan Baxter @@ -18,18 +34,22 @@ public class NativeBootstrapFailureAnalyzerTests { @Rule public OutputCapture outputCapture = new OutputCapture(); - + @Test - public void contextLoads(){ + public void contextLoads() { try { new SpringApplicationBuilder(ConfigServerApplication.class) - .web(WebApplicationType.SERVLET).properties("spring.cloud.bootstrap.name:enable-nativebootstrap").profiles("test","native").run(); + .web(WebApplicationType.SERVLET) + .properties("spring.cloud.bootstrap.name:enable-nativebootstrap") + .profiles("test", "native").run(); fail("Application started successfully"); } catch (Exception ex) { assertThat(this.outputCapture.toString()) .contains(GitUriFailureAnalyzer.ACTION); - assertThat(this.outputCapture.toString()).contains(GitUriFailureAnalyzer.DESCRIPTION); + assertThat(this.outputCapture.toString()) + .contains(GitUriFailureAnalyzer.DESCRIPTION); } } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java index 8a7fc970..5d0e75df 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server; import java.io.IOException; @@ -16,37 +32,39 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, - properties = { "spring.config.name:configserver" }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ConfigServerApplication.class, properties = { + "spring.config.name:configserver" }, webEnvironment = RANDOM_PORT) @ActiveProfiles({ "test", "native" }) public class NativeConfigServerIntegrationTests { - + @LocalServerPort private int port; - + @BeforeClass - public static void init() throws IOException{ + public static void init() throws IOException { ConfigServerTestUtils.prepareLocalRepo(); } @Test public void contextLoads() { - Environment environment = new TestRestTemplate().getForObject("http://localhost:" + port + "/foo/development/", Environment.class); - assertFalse(environment.getPropertySources().isEmpty()); - assertEquals("overrides", environment.getPropertySources().get(0).getName()); - assertEquals("{spring.cloud.config.enabled=true}", environment.getPropertySources().get(0).getSource().toString()); + Environment environment = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + "/foo/development/", Environment.class); + assertThat(environment.getPropertySources().isEmpty()).isFalse(); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("overrides"); + assertThat(environment.getPropertySources().get(0).getSource().toString()) + .isEqualTo("{spring.cloud.config.enabled=true}"); } @Test public void badYaml() { - ResponseEntity response = new TestRestTemplate().getForEntity("http://localhost:" - + port + "/bad/default/", String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + ResponseEntity response = new TestRestTemplate().getForEntity( + "http://localhost:" + this.port + "/bad/default/", String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/SubversionConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/SubversionConfigServerIntegrationTests.java index c9736ba0..6a126bff 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/SubversionConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/SubversionConfigServerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server; import java.io.File; @@ -21,6 +22,7 @@ import java.io.IOException; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; @@ -33,8 +35,6 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.cloud.config.server.test.ConfigServerTestUtils.REPO_PREFIX; @@ -67,17 +67,18 @@ public class SubversionConfigServerIntegrationTests { public void contextLoads() { Environment environment = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/foo/development/", Environment.class); - assertFalse(environment.getPropertySources().isEmpty()); - assertEquals("overrides", environment.getPropertySources().get(0).getName()); - assertEquals("{spring.cloud.config.enabled=true}", - environment.getPropertySources().get(0).getSource().toString()); + assertThat(environment.getPropertySources().isEmpty()).isFalse(); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("overrides"); + assertThat(environment.getPropertySources().get(0).getSource().toString()) + .isEqualTo("{spring.cloud.config.enabled=true}"); } @Test public void defaultLabel() throws Exception { SvnKitEnvironmentRepository repository = this.context .getBean(SvnKitEnvironmentRepository.class); - assertEquals("trunk", repository.getDefaultLabel()); + assertThat(repository.getDefaultLabel()).isEqualTo("trunk"); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java index 3d755412..99b211fe 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,17 +39,13 @@ import org.springframework.cloud.config.server.ssh.SshPropertyValidator; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static junit.framework.TestCase.assertTrue; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** - * Integration tests for property based SSH config support + * Integration tests for property based SSH config support. + * * @author Ollie Hughes */ public class TransportConfigurationIntegrationTests { @@ -57,10 +53,10 @@ public class TransportConfigurationIntegrationTests { public static class PropertyBasedCallbackTest { @RunWith(SpringRunner.class) - @SpringBootTest(classes = {ConfigServerApplication.class, SshPropertyValidator.class}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = {"spring.config.name:ssh/ssh-private-key-block"}) - @ActiveProfiles({"test", "git"}) + @SpringBootTest(classes = { ConfigServerApplication.class, + SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.config.name:ssh/ssh-private-key-block" }) + @ActiveProfiles({ "test", "git" }) public static class StaticTest { @Autowired @@ -68,16 +64,19 @@ public class TransportConfigurationIntegrationTests { @Test public void propertyBasedTransportCallbackIsConfigured() throws Exception { - TransportConfigCallback transportConfigCallback = jGitEnvironmentRepository.getTransportConfigCallback(); - assertThat(transportConfigCallback, is(instanceOf(PropertiesBasedSshTransportConfigCallback.class))); + TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository + .getTransportConfigCallback(); + assertThat(transportConfigCallback) + .isInstanceOf(PropertiesBasedSshTransportConfigCallback.class); } + } @RunWith(SpringRunner.class) - @SpringBootTest(classes = {ConfigServerApplication.class, SshPropertyValidator.class}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = {"spring.config.name:ssh/ssh-private-key-block-list"}) - @ActiveProfiles({"test", "composite"}) + @SpringBootTest(classes = { ConfigServerApplication.class, + SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.config.name:ssh/ssh-private-key-block-list" }) + @ActiveProfiles({ "test", "composite" }) public static class ListTest { @Autowired @@ -85,277 +84,311 @@ public class TransportConfigurationIntegrationTests { @Test public void propertyBasedTransportCallbackIsConfigured() throws Exception { - TransportConfigCallback transportConfigCallback = jGitEnvironmentRepository.getTransportConfigCallback(); - assertThat(transportConfigCallback, is(instanceOf(PropertiesBasedSshTransportConfigCallback.class))); + TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository + .getTransportConfigCallback(); + assertThat(transportConfigCallback) + .isInstanceOf(PropertiesBasedSshTransportConfigCallback.class); } + } } public static class PrivateKeyPropertyWithLineBreaks { - @RunWith(SpringRunner.class) - @SpringBootTest(classes = {ConfigServerApplication.class, SshPropertyValidator.class}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "spring.config.name:ssh/ssh-private-key-newline" - }) - @ActiveProfiles({"test", "git"}) - public static class StaticTest { + @RunWith(SpringRunner.class) + @SpringBootTest(classes = { ConfigServerApplication.class, + SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.config.name:ssh/ssh-private-key-newline" }) + @ActiveProfiles({ "test", "git" }) + public static class StaticTest { - @Autowired - private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; + @Autowired + private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; - @Test - public void privateKeyPropertyWithLineBreaks() throws Exception { - TransportConfigCallback transportConfigCallback = jGitEnvironmentRepository.getTransportConfigCallback(); - assertThat(transportConfigCallback, is(instanceOf(PropertiesBasedSshTransportConfigCallback.class))); + @Test + public void privateKeyPropertyWithLineBreaks() throws Exception { + TransportConfigCallback callback = this.jGitEnvironmentRepository + .getTransportConfigCallback(); + assertThat(callback) + .isInstanceOf(PropertiesBasedSshTransportConfigCallback.class); - PropertiesBasedSshTransportConfigCallback configCallback = - (PropertiesBasedSshTransportConfigCallback) transportConfigCallback; - assertThat(configCallback.getSshUriProperties().getPrivateKey(), is(equalTo(TestProperties.TEST_PRIVATE_KEY_1))); - } - } + PropertiesBasedSshTransportConfigCallback configCallback = (PropertiesBasedSshTransportConfigCallback) callback; + assertThat(configCallback.getSshUriProperties().getPrivateKey()) + .isEqualTo(TestProperties.TEST_PRIVATE_KEY_1); + } - @RunWith(SpringRunner.class) - @SpringBootTest(classes = {ConfigServerApplication.class, SshPropertyValidator.class}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "spring.config.name:ssh/ssh-private-key-newline-list" - }) - @ActiveProfiles({"test", "composite"}) - public static class ListTest { + } - @Autowired - private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; + @RunWith(SpringRunner.class) + @SpringBootTest(classes = { ConfigServerApplication.class, + SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.config.name:ssh/ssh-private-key-newline-list" }) + @ActiveProfiles({ "test", "composite" }) + public static class ListTest { - @Test - public void privateKeyPropertyWithLineBreaks() throws Exception { - TransportConfigCallback transportConfigCallback = jGitEnvironmentRepository.getTransportConfigCallback(); - assertThat(transportConfigCallback, is(instanceOf(PropertiesBasedSshTransportConfigCallback.class))); + @Autowired + private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; - PropertiesBasedSshTransportConfigCallback configCallback = - (PropertiesBasedSshTransportConfigCallback) transportConfigCallback; - assertThat(configCallback.getSshUriProperties().getPrivateKey(), is(equalTo(TestProperties.TEST_PRIVATE_KEY_1))); - } - } + @Test + public void privateKeyPropertyWithLineBreaks() throws Exception { + TransportConfigCallback callback = this.jGitEnvironmentRepository + .getTransportConfigCallback(); + assertThat(callback) + .isInstanceOf(PropertiesBasedSshTransportConfigCallback.class); + + PropertiesBasedSshTransportConfigCallback configCallback = (PropertiesBasedSshTransportConfigCallback) callback; + assertThat(configCallback.getSshUriProperties().getPrivateKey()) + .isEqualTo(TestProperties.TEST_PRIVATE_KEY_1); + } + + } } public static class SshPropertiesWithinNestedRepo { - @RunWith(SpringRunner.class) - @SpringBootTest(classes = {ConfigServerApplication.class, SshPropertyValidator.class}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "spring.config.name:ssh/ssh-nested-settings" - }) - @ActiveProfiles({"test", "git"}) - public static class StaticTest { - @Autowired - private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; + @RunWith(SpringRunner.class) + @SpringBootTest(classes = { ConfigServerApplication.class, + SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.config.name:ssh/ssh-nested-settings" }) + @ActiveProfiles({ "test", "git" }) + public static class StaticTest { - @Test - public void sshPropertiesWithinNestedRepo() throws Exception { - TransportConfigCallback transportConfigCallback = jGitEnvironmentRepository.getTransportConfigCallback(); - assertThat(transportConfigCallback, is(instanceOf(PropertiesBasedSshTransportConfigCallback.class))); + @Autowired + private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; - PropertiesBasedSshTransportConfigCallback configCallback = - (PropertiesBasedSshTransportConfigCallback) transportConfigCallback; - MultipleJGitEnvironmentProperties sshUriProperties = configCallback.getSshUriProperties(); - assertThat(sshUriProperties.getPrivateKey(), is(equalTo(TestProperties.TEST_PRIVATE_KEY_1))); + @Test + public void sshPropertiesWithinNestedRepo() throws Exception { + TransportConfigCallback callback = this.jGitEnvironmentRepository + .getTransportConfigCallback(); + assertThat(callback) + .isInstanceOf(PropertiesBasedSshTransportConfigCallback.class); - assertThat(sshUriProperties.getRepos().get("repo1"), is(notNullValue())); - assertThat(sshUriProperties.getRepos().get("repo1").getPrivateKey(), is(equalTo(TestProperties.TEST_PRIVATE_KEY_2))); - } - } + PropertiesBasedSshTransportConfigCallback configCallback = (PropertiesBasedSshTransportConfigCallback) callback; + MultipleJGitEnvironmentProperties sshUriProperties = configCallback + .getSshUriProperties(); + assertThat(configCallback.getSshUriProperties().getPrivateKey()) + .isEqualTo(TestProperties.TEST_PRIVATE_KEY_1); - @RunWith(SpringRunner.class) - @SpringBootTest(classes = {ConfigServerApplication.class, SshPropertyValidator.class}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "spring.config.name:ssh/ssh-nested-settings-list" - }) - @ActiveProfiles({"test", "composite"}) - public static class ListTest { - @Autowired - private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; + assertThat(sshUriProperties.getRepos().get("repo1")).isNotNull(); + assertThat(sshUriProperties.getRepos().get("repo1").getPrivateKey()) + .isEqualTo(TestProperties.TEST_PRIVATE_KEY_2); + } - @Test - public void sshPropertiesWithinNestedRepo() throws Exception { - TransportConfigCallback transportConfigCallback = jGitEnvironmentRepository.getTransportConfigCallback(); - assertThat(transportConfigCallback, is(instanceOf(PropertiesBasedSshTransportConfigCallback.class))); + } - PropertiesBasedSshTransportConfigCallback configCallback = - (PropertiesBasedSshTransportConfigCallback) transportConfigCallback; - MultipleJGitEnvironmentProperties sshUriProperties = configCallback.getSshUriProperties(); - assertThat(sshUriProperties.getPrivateKey(), is(equalTo(TestProperties.TEST_PRIVATE_KEY_1))); + @RunWith(SpringRunner.class) + @SpringBootTest(classes = { ConfigServerApplication.class, + SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.config.name:ssh/ssh-nested-settings-list" }) + @ActiveProfiles({ "test", "composite" }) + public static class ListTest { - assertThat(sshUriProperties.getRepos().get("repo1"), is(notNullValue())); - assertThat(sshUriProperties.getRepos().get("repo1").getPrivateKey(), is(equalTo(TestProperties.TEST_PRIVATE_KEY_2))); - } - } + @Autowired + private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; + + @Test + public void sshPropertiesWithinNestedRepo() throws Exception { + TransportConfigCallback callback = this.jGitEnvironmentRepository + .getTransportConfigCallback(); + assertThat(callback) + .isInstanceOf(PropertiesBasedSshTransportConfigCallback.class); + + PropertiesBasedSshTransportConfigCallback configCallback = (PropertiesBasedSshTransportConfigCallback) callback; + MultipleJGitEnvironmentProperties sshUriProperties = configCallback + .getSshUriProperties(); + assertThat(configCallback.getSshUriProperties().getPrivateKey()) + .isEqualTo(TestProperties.TEST_PRIVATE_KEY_1); + + assertThat(sshUriProperties.getRepos().get("repo1")).isNotNull(); + assertThat(sshUriProperties.getRepos().get("repo1").getPrivateKey()) + .isEqualTo(TestProperties.TEST_PRIVATE_KEY_2); + } + + } } public static class FileBasedCallbackTest { - @RunWith(SpringRunner.class) - @SpringBootTest(classes = {ConfigServerApplication.class, SshPropertyValidator.class}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "spring.cloud.config.server.git.uri=git@gitserver.com:team/repo.git", - "spring.cloud.config.server.git.ignoreLocalSshSettings=false",}) - @ActiveProfiles({"test", "git"}) - public static class StaticTest { - @Autowired - private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; + @RunWith(SpringRunner.class) + @SpringBootTest(classes = { ConfigServerApplication.class, + SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.cloud.config.server.git.uri=git@gitserver.com:team/repo.git", + "spring.cloud.config.server.git.ignoreLocalSshSettings=false" }) + @ActiveProfiles({ "test", "git" }) + public static class StaticTest { - @Test - public void fileBasedTransportCallbackIsConfigured() throws Exception { - TransportConfigCallback transportConfigCallback = jGitEnvironmentRepository.getTransportConfigCallback(); - assertThat(transportConfigCallback, is(instanceOf(FileBasedSshTransportConfigCallback.class))); - } + @Autowired + private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; - @Test - public void strictHostKeyCheckShouldCheck() throws Exception { - String uri = "git+ssh://git@somegitserver/somegitrepo"; - SshSessionFactory.setInstance(null); - jGitEnvironmentRepository.setUri(uri); - jGitEnvironmentRepository.setBasedir(new File("./mybasedir")); - assertTrue(jGitEnvironmentRepository.isStrictHostKeyChecking()); - jGitEnvironmentRepository.setCloneOnStart(true); - try { - // this will throw but we don't care about connecting. - jGitEnvironmentRepository.afterPropertiesSet(); - } catch (Exception e) { - final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect()).lookup("github.com"); - JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory.getInstance(); - // There's no public method that can be used to inspect the ssh - // configuration, so we'll reflect - // the configure method to allow us to check that the config - // property is set as expected. - Method configure = factory.getClass().getDeclaredMethod("configure", OpenSshConfig.Host.class, - Session.class); - configure.setAccessible(true); - Session session = mock(Session.class); - ArgumentCaptor keyCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor valueCaptor = ArgumentCaptor.forClass(String.class); - configure.invoke(factory, hc, session); - verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture()); - configure.setAccessible(false); - assertTrue("yes".equals(valueCaptor.getValue())); - } - } - } + @Test + public void fileBasedTransportCallbackIsConfigured() throws Exception { + TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository + .getTransportConfigCallback(); + assertThat(transportConfigCallback) + .isInstanceOf(FileBasedSshTransportConfigCallback.class); + } - @RunWith(SpringRunner.class) - @SpringBootTest(classes = {ConfigServerApplication.class, SshPropertyValidator.class}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "spring.cloud.config.server.composite[0].type=git", - "spring.cloud.config.server.composite[0].uri=git@gitserver.com:team/repo.git", - "spring.cloud.config.server.composite[0].ignoreLocalSshSettings=false",}) - @ActiveProfiles({"test", "composite"}) - public static class ListTest { - @Autowired - private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; + @Test + public void strictHostKeyCheckShouldCheck() throws Exception { + String uri = "git+ssh://git@somegitserver/somegitrepo"; + SshSessionFactory.setInstance(null); + this.jGitEnvironmentRepository.setUri(uri); + this.jGitEnvironmentRepository.setBasedir(new File("./mybasedir")); + assertThat(this.jGitEnvironmentRepository.isStrictHostKeyChecking()) + .isTrue(); + this.jGitEnvironmentRepository.setCloneOnStart(true); + try { + // this will throw but we don't care about connecting. + this.jGitEnvironmentRepository.afterPropertiesSet(); + } + catch (Exception e) { + final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect()) + .lookup("github.com"); + JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory + .getInstance(); + // There's no public method that can be used to inspect the ssh + // configuration, so we'll reflect + // the configure method to allow us to check that the config + // property is set as expected. + Method configure = factory.getClass().getDeclaredMethod("configure", + OpenSshConfig.Host.class, Session.class); + configure.setAccessible(true); + Session session = mock(Session.class); + ArgumentCaptor keyCaptor = ArgumentCaptor + .forClass(String.class); + ArgumentCaptor valueCaptor = ArgumentCaptor + .forClass(String.class); + configure.invoke(factory, hc, session); + verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture()); + configure.setAccessible(false); + assertThat("yes".equals(valueCaptor.getValue())).isTrue(); + } + } - @Test - public void fileBasedTransportCallbackIsConfigured() throws Exception { - TransportConfigCallback transportConfigCallback = jGitEnvironmentRepository.getTransportConfigCallback(); - assertThat(transportConfigCallback, is(instanceOf(FileBasedSshTransportConfigCallback.class))); - } + } - @Test - public void strictHostKeyCheckShouldCheck() throws Exception { - String uri = "git+ssh://git@somegitserver/somegitrepo"; - SshSessionFactory.setInstance(null); - jGitEnvironmentRepository.setUri(uri); - jGitEnvironmentRepository.setBasedir(new File("./mybasedir")); - assertTrue(jGitEnvironmentRepository.isStrictHostKeyChecking()); - jGitEnvironmentRepository.setCloneOnStart(true); - try { - // this will throw but we don't care about connecting. - jGitEnvironmentRepository.afterPropertiesSet(); - } catch (Exception e) { - final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect()).lookup("github.com"); - JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory.getInstance(); - // There's no public method that can be used to inspect the ssh - // configuration, so we'll reflect - // the configure method to allow us to check that the config - // property is set as expected. - Method configure = factory.getClass().getDeclaredMethod("configure", OpenSshConfig.Host.class, - Session.class); - configure.setAccessible(true); - Session session = mock(Session.class); - ArgumentCaptor keyCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor valueCaptor = ArgumentCaptor.forClass(String.class); - configure.invoke(factory, hc, session); - verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture()); - configure.setAccessible(false); - assertTrue("yes".equals(valueCaptor.getValue())); - } - } - } + @RunWith(SpringRunner.class) + @SpringBootTest(classes = { ConfigServerApplication.class, + SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.cloud.config.server.composite[0].type=git", + "spring.cloud.config.server.composite[0].uri=git@gitserver.com:team/repo.git", + "spring.cloud.config.server.composite[0].ignoreLocalSshSettings=false" }) + @ActiveProfiles({ "test", "composite" }) + public static class ListTest { + + @Autowired + private MultipleJGitEnvironmentRepository jGitEnvironmentRepository; + + @Test + public void fileBasedTransportCallbackIsConfigured() throws Exception { + TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository + .getTransportConfigCallback(); + assertThat(transportConfigCallback) + .isInstanceOf(FileBasedSshTransportConfigCallback.class); + } + + @Test + public void strictHostKeyCheckShouldCheck() throws Exception { + String uri = "git+ssh://git@somegitserver/somegitrepo"; + SshSessionFactory.setInstance(null); + this.jGitEnvironmentRepository.setUri(uri); + this.jGitEnvironmentRepository.setBasedir(new File("./mybasedir")); + assertThat(this.jGitEnvironmentRepository.isStrictHostKeyChecking()) + .isTrue(); + this.jGitEnvironmentRepository.setCloneOnStart(true); + try { + // this will throw but we don't care about connecting. + this.jGitEnvironmentRepository.afterPropertiesSet(); + } + catch (Exception e) { + final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect()) + .lookup("github.com"); + JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory + .getInstance(); + // There's no public method that can be used to inspect the ssh + // configuration, so we'll reflect + // the configure method to allow us to check that the config + // property is set as expected. + Method configure = factory.getClass().getDeclaredMethod("configure", + OpenSshConfig.Host.class, Session.class); + configure.setAccessible(true); + Session session = mock(Session.class); + ArgumentCaptor keyCaptor = ArgumentCaptor + .forClass(String.class); + ArgumentCaptor valueCaptor = ArgumentCaptor + .forClass(String.class); + configure.invoke(factory, hc, session); + verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture()); + configure.setAccessible(false); + assertThat("yes".equals(valueCaptor.getValue())).isTrue(); + } + } + + } } private static class TestProperties { - private static final String TEST_PRIVATE_KEY_1 = "-----BEGIN RSA PRIVATE KEY-----\n" + - "MIIEpAIBAAKCAQEAoqyz6YaYMTr7L8GLPSQpAQXaM04gRx4CCsGK2kfLQdw4BlqI\n" + - "yyxp38YcuZG9cUDBAxby+K2TKmwHaC1R61QTwbPuCRdIPrDwRz+FLoegm3iDLCmn\n" + - "uP6rjZDneYsqfU1KSdrOwIbCnONfDdvYL/vnZC/o8DDMlk5Orw2SfHkT3pq0o8km\n" + - "ayBwN4Sf3bpyWTY0oZcmNeSCCoIdE59k8Pa7/t9bwY9caLj05C3DEsjucc7Ei/Eq\n" + - "TOyGyobtXwaya5CqKLUHes74Poz1aEP/yVFdUud91uezd8ZK1P1t5/ZKA3R6aHir\n" + - "+diDJ2/GQ2tD511FW46yw+EtBUJTO6ADVv4UnQIDAQABAoIBAF+5qwEfX82QfKFk\n" + - "jfADqFFexUDtl1biFKeJrpC2MKhn01wByH9uejrhFKQqW8UaKroLthyZ34DWIyGt\n" + - "lDnHGv0gSVF2LuAdNLdobJGt49e4+c9yD61vxzm97Eh8mRs08SM2q/VlF35E2fmI\n" + - "xdWusUImYzd8L9e+6tRd8zZl9UhG5vR5XIstKqxC6S0g79aAt0hasE4Gw1FKOf2V\n" + - "4mlL15atjQSKCPdOicuyc4zpjAtU1A9AfF51iG8oOUuJebPW8tCftfOQxaeGFgMG\n" + - "7M9aai1KzXR6M5IBAKEv31yBvz/SHTneP7oZXNLeC1GIR420PKybmeZdNK8BbEAu\n" + - "3reKgm0CgYEA03Sx8JoF5UBsIvFPpP1fjSlTgKryM5EJR6KQtj5e4YfyxccJepN8\n" + - "q4MrqDfNKleG/a1acEtDMhBNovU7Usp2QIP7zpAeioHBOhmE5WSieZGc3icOGWWq\n" + - "mRkdulSONruqWKv76ZoluxftekE03bDhZDNlcCgmrslEKB/ufHd2oc8CgYEAxPFa\n" + - "lKOdSeiYFV5CtvO8Ro8em6rGpSsVz4qkPxbeBqUDCb9KXHhq6YrhRxOIfQJKfT7M\n" + - "ZFCn8ArJXKgOGu+KsvwIErFHF9g2jJMG4DOUTpkQgi2yveihFxcmz/AltyVXgrnv\n" + - "ZWQbAerH77pdKKhNivLGgEv72GYawdYjYNjemdMCgYA2kEMmMahZyrDcp2YEzfit\n" + - "BT/t0K6kzcUWPgWXcSqsiZcEn+J7RbmCzFskkhmX1nQX23adyV3yejB+X0dKisHO\n" + - "zf/ZAmlPFkJVCqa3RquCMSfIT02dEhXeYZPBM/Zqeyxuqxpa4hLgX0FBLbhFiFHw\n" + - "uC5xrXql2XuD2xF//peXEwKBgQC+pa28Cg7vRxxCQzduB9CQtWc55j3aEjVQ7bNF\n" + - "54sS/5ZLT0Ra8677WZfuyDfuW9NkHvCZg4Ku2qJG8eCFrrGjxlrCTZ62tHVJ6+JS\n" + - "E1xUIdRbUIWhVZrr0VufG6hG/P0T7Y6Tpi6G0pKtvMkF3LcD9TS3adboix8H2ZXx\n" + - "4L7MRQKBgQC0OO3qqNXOjIVYWOoqXLybOY/Wqu9lxCAgGyCYaMcstnBI7W0MZTBr\n" + - "/syluvGsaFc1sE7MMGOOzKi1tF4YvDmSnzA/R1nmaPguuD9fOA+w7Pwkv5vLvuJq\n" + - "2U7EeNwxq1I1L3Ag6E7wH4BHLHd4TKaZR6agFkn8oomz71yZPGjuZQ==\n" + - "-----END RSA PRIVATE KEY-----"; - private static final String TEST_PRIVATE_KEY_2 = "-----BEGIN RSA PRIVATE KEY-----\n" + - "MIIEpgIBAAKCAQEAx4UbaDzY5xjW6hc9jwN0mX33XpTDVW9WqHp5AKaRbtAC3DqX\n" + - "IXFMPgw3K45jxRb93f8tv9vL3rD9CUG1Gv4FM+o7ds7FRES5RTjv2RT/JVNJCoqF\n" + - "ol8+ngLqRZCyBtQN7zYByWMRirPGoDUqdPYrj2yq+ObBBNhg5N+hOwKjjpzdj2Ud\n" + - "1l7R+wxIqmJo1IYyy16xS8WsjyQuyC0lL456qkd5BDZ0Ag8j2X9H9D5220Ln7s9i\n" + - "oezTipXipS7p7Jekf3Ywx6abJwOmB0rX79dV4qiNcGgzATnG1PkXxqt76VhcGa0W\n" + - "DDVHEEYGbSQ6hIGSh0I7BQun0aLRZojfE3gqHQIDAQABAoIBAQCZmGrk8BK6tXCd\n" + - "fY6yTiKxFzwb38IQP0ojIUWNrq0+9Xt+NsypviLHkXfXXCKKU4zUHeIGVRq5MN9b\n" + - "BO56/RrcQHHOoJdUWuOV2qMqJvPUtC0CpGkD+valhfD75MxoXU7s3FK7yjxy3rsG\n" + - "EmfA6tHV8/4a5umo5TqSd2YTm5B19AhRqiuUVI1wTB41DjULUGiMYrnYrhzQlVvj\n" + - "5MjnKTlYu3V8PoYDfv1GmxPPh6vlpafXEeEYN8VB97e5x3DGHjZ5UrurAmTLTdO8\n" + - "+AahyoKsIY612TkkQthJlt7FJAwnCGMgY6podzzvzICLFmmTXYiZ/28I4BX/mOSe\n" + - "pZVnfRixAoGBAO6Uiwt40/PKs53mCEWngslSCsh9oGAaLTf/XdvMns5VmuyyAyKG\n" + - "ti8Ol5wqBMi4GIUzjbgUvSUt+IowIrG3f5tN85wpjQ1UGVcpTnl5Qo9xaS1PFScQ\n" + - "xrtWZ9eNj2TsIAMp/svJsyGG3OibxfnuAIpSXNQiJPwRlW3irzpGgVx/AoGBANYW\n" + - "dnhshUcEHMJi3aXwR12OTDnaLoanVGLwLnkqLSYUZA7ZegpKq90UAuBdcEfgdpyi\n" + - "PhKpeaeIiAaNnFo8m9aoTKr+7I6/uMTlwrVnfrsVTZv3orxjwQV20YIBCVRKD1uX\n" + - "VhE0ozPZxwwKSPAFocpyWpGHGreGF1AIYBE9UBtjAoGBAI8bfPgJpyFyMiGBjO6z\n" + - "FwlJc/xlFqDusrcHL7abW5qq0L4v3R+FrJw3ZYufzLTVcKfdj6GelwJJO+8wBm+R\n" + - "gTKYJItEhT48duLIfTDyIpHGVm9+I1MGhh5zKuCqIhxIYr9jHloBB7kRm0rPvYY4\n" + - "VAykcNgyDvtAVODP+4m6JvhjAoGBALbtTqErKN47V0+JJpapLnF0KxGrqeGIjIRV\n" + - "cYA6V4WYGr7NeIfesecfOC356PyhgPfpcVyEztwlvwTKb3RzIT1TZN8fH4YBr6Ee\n" + - "KTbTjefRFhVUjQqnucAvfGi29f+9oE3Ei9f7wA+H35ocF6JvTYUsHNMIO/3gZ38N\n" + - "CPjyCMa9AoGBAMhsITNe3QcbsXAbdUR00dDsIFVROzyFJ2m40i4KCRM35bC/BIBs\n" + - "q0TY3we+ERB40U8Z2BvU61QuwaunJ2+uGadHo58VSVdggqAo0BSkH58innKKt96J\n" + - "69pcVH/4rmLbXdcmNYGm6iu+MlPQk4BUZknHSmVHIFdJ0EPupVaQ8RHT\n" + - "-----END RSA PRIVATE KEY-----\n"; + private static final String TEST_PRIVATE_KEY_1 = "-----BEGIN RSA PRIVATE KEY-----\n" + + "MIIEpAIBAAKCAQEAoqyz6YaYMTr7L8GLPSQpAQXaM04gRx4CCsGK2kfLQdw4BlqI\n" + + "yyxp38YcuZG9cUDBAxby+K2TKmwHaC1R61QTwbPuCRdIPrDwRz+FLoegm3iDLCmn\n" + + "uP6rjZDneYsqfU1KSdrOwIbCnONfDdvYL/vnZC/o8DDMlk5Orw2SfHkT3pq0o8km\n" + + "ayBwN4Sf3bpyWTY0oZcmNeSCCoIdE59k8Pa7/t9bwY9caLj05C3DEsjucc7Ei/Eq\n" + + "TOyGyobtXwaya5CqKLUHes74Poz1aEP/yVFdUud91uezd8ZK1P1t5/ZKA3R6aHir\n" + + "+diDJ2/GQ2tD511FW46yw+EtBUJTO6ADVv4UnQIDAQABAoIBAF+5qwEfX82QfKFk\n" + + "jfADqFFexUDtl1biFKeJrpC2MKhn01wByH9uejrhFKQqW8UaKroLthyZ34DWIyGt\n" + + "lDnHGv0gSVF2LuAdNLdobJGt49e4+c9yD61vxzm97Eh8mRs08SM2q/VlF35E2fmI\n" + + "xdWusUImYzd8L9e+6tRd8zZl9UhG5vR5XIstKqxC6S0g79aAt0hasE4Gw1FKOf2V\n" + + "4mlL15atjQSKCPdOicuyc4zpjAtU1A9AfF51iG8oOUuJebPW8tCftfOQxaeGFgMG\n" + + "7M9aai1KzXR6M5IBAKEv31yBvz/SHTneP7oZXNLeC1GIR420PKybmeZdNK8BbEAu\n" + + "3reKgm0CgYEA03Sx8JoF5UBsIvFPpP1fjSlTgKryM5EJR6KQtj5e4YfyxccJepN8\n" + + "q4MrqDfNKleG/a1acEtDMhBNovU7Usp2QIP7zpAeioHBOhmE5WSieZGc3icOGWWq\n" + + "mRkdulSONruqWKv76ZoluxftekE03bDhZDNlcCgmrslEKB/ufHd2oc8CgYEAxPFa\n" + + "lKOdSeiYFV5CtvO8Ro8em6rGpSsVz4qkPxbeBqUDCb9KXHhq6YrhRxOIfQJKfT7M\n" + + "ZFCn8ArJXKgOGu+KsvwIErFHF9g2jJMG4DOUTpkQgi2yveihFxcmz/AltyVXgrnv\n" + + "ZWQbAerH77pdKKhNivLGgEv72GYawdYjYNjemdMCgYA2kEMmMahZyrDcp2YEzfit\n" + + "BT/t0K6kzcUWPgWXcSqsiZcEn+J7RbmCzFskkhmX1nQX23adyV3yejB+X0dKisHO\n" + + "zf/ZAmlPFkJVCqa3RquCMSfIT02dEhXeYZPBM/Zqeyxuqxpa4hLgX0FBLbhFiFHw\n" + + "uC5xrXql2XuD2xF//peXEwKBgQC+pa28Cg7vRxxCQzduB9CQtWc55j3aEjVQ7bNF\n" + + "54sS/5ZLT0Ra8677WZfuyDfuW9NkHvCZg4Ku2qJG8eCFrrGjxlrCTZ62tHVJ6+JS\n" + + "E1xUIdRbUIWhVZrr0VufG6hG/P0T7Y6Tpi6G0pKtvMkF3LcD9TS3adboix8H2ZXx\n" + + "4L7MRQKBgQC0OO3qqNXOjIVYWOoqXLybOY/Wqu9lxCAgGyCYaMcstnBI7W0MZTBr\n" + + "/syluvGsaFc1sE7MMGOOzKi1tF4YvDmSnzA/R1nmaPguuD9fOA+w7Pwkv5vLvuJq\n" + + "2U7EeNwxq1I1L3Ag6E7wH4BHLHd4TKaZR6agFkn8oomz71yZPGjuZQ==\n" + + "-----END RSA PRIVATE KEY-----"; + + private static final String TEST_PRIVATE_KEY_2 = "-----BEGIN RSA PRIVATE KEY-----\n" + + "MIIEpgIBAAKCAQEAx4UbaDzY5xjW6hc9jwN0mX33XpTDVW9WqHp5AKaRbtAC3DqX\n" + + "IXFMPgw3K45jxRb93f8tv9vL3rD9CUG1Gv4FM+o7ds7FRES5RTjv2RT/JVNJCoqF\n" + + "ol8+ngLqRZCyBtQN7zYByWMRirPGoDUqdPYrj2yq+ObBBNhg5N+hOwKjjpzdj2Ud\n" + + "1l7R+wxIqmJo1IYyy16xS8WsjyQuyC0lL456qkd5BDZ0Ag8j2X9H9D5220Ln7s9i\n" + + "oezTipXipS7p7Jekf3Ywx6abJwOmB0rX79dV4qiNcGgzATnG1PkXxqt76VhcGa0W\n" + + "DDVHEEYGbSQ6hIGSh0I7BQun0aLRZojfE3gqHQIDAQABAoIBAQCZmGrk8BK6tXCd\n" + + "fY6yTiKxFzwb38IQP0ojIUWNrq0+9Xt+NsypviLHkXfXXCKKU4zUHeIGVRq5MN9b\n" + + "BO56/RrcQHHOoJdUWuOV2qMqJvPUtC0CpGkD+valhfD75MxoXU7s3FK7yjxy3rsG\n" + + "EmfA6tHV8/4a5umo5TqSd2YTm5B19AhRqiuUVI1wTB41DjULUGiMYrnYrhzQlVvj\n" + + "5MjnKTlYu3V8PoYDfv1GmxPPh6vlpafXEeEYN8VB97e5x3DGHjZ5UrurAmTLTdO8\n" + + "+AahyoKsIY612TkkQthJlt7FJAwnCGMgY6podzzvzICLFmmTXYiZ/28I4BX/mOSe\n" + + "pZVnfRixAoGBAO6Uiwt40/PKs53mCEWngslSCsh9oGAaLTf/XdvMns5VmuyyAyKG\n" + + "ti8Ol5wqBMi4GIUzjbgUvSUt+IowIrG3f5tN85wpjQ1UGVcpTnl5Qo9xaS1PFScQ\n" + + "xrtWZ9eNj2TsIAMp/svJsyGG3OibxfnuAIpSXNQiJPwRlW3irzpGgVx/AoGBANYW\n" + + "dnhshUcEHMJi3aXwR12OTDnaLoanVGLwLnkqLSYUZA7ZegpKq90UAuBdcEfgdpyi\n" + + "PhKpeaeIiAaNnFo8m9aoTKr+7I6/uMTlwrVnfrsVTZv3orxjwQV20YIBCVRKD1uX\n" + + "VhE0ozPZxwwKSPAFocpyWpGHGreGF1AIYBE9UBtjAoGBAI8bfPgJpyFyMiGBjO6z\n" + + "FwlJc/xlFqDusrcHL7abW5qq0L4v3R+FrJw3ZYufzLTVcKfdj6GelwJJO+8wBm+R\n" + + "gTKYJItEhT48duLIfTDyIpHGVm9+I1MGhh5zKuCqIhxIYr9jHloBB7kRm0rPvYY4\n" + + "VAykcNgyDvtAVODP+4m6JvhjAoGBALbtTqErKN47V0+JJpapLnF0KxGrqeGIjIRV\n" + + "cYA6V4WYGr7NeIfesecfOC356PyhgPfpcVyEztwlvwTKb3RzIT1TZN8fH4YBr6Ee\n" + + "KTbTjefRFhVUjQqnucAvfGi29f+9oE3Ei9f7wA+H35ocF6JvTYUsHNMIO/3gZ38N\n" + + "CPjyCMa9AoGBAMhsITNe3QcbsXAbdUR00dDsIFVROzyFJ2m40i4KCRM35bC/BIBs\n" + + "q0TY3we+ERB40U8Z2BvU61QuwaunJ2+uGadHo58VSVdggqAo0BSkH58innKKt96J\n" + + "69pcVH/4rmLbXdcmNYGm6iu+MlPQk4BUZknHSmVHIFdJ0EPupVaQ8RHT\n" + + "-----END RSA PRIVATE KEY-----\n"; + } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java index e7614dbd..a6793231 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server; import java.io.IOException; @@ -20,14 +36,13 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) @SpringBootTest(classes = ConfigServerApplication.class, properties = { - "spring.config.name:configserver", "spring.cloud.config.server.git.uri:file:./target/repos/config-repo"}, - webEnvironment = RANDOM_PORT) + "spring.config.name:configserver", + "spring.cloud.config.server.git.uri:file:./target/repos/config-repo" }, webEnvironment = RANDOM_PORT) @ActiveProfiles("test") public class VanillaConfigServerIntegrationTests { @@ -41,29 +56,32 @@ public class VanillaConfigServerIntegrationTests { @Test public void contextLoads() { - Environment environment = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/", Environment.class); - assertFalse(environment.getPropertySources().isEmpty()); - assertEquals("overrides", environment.getPropertySources().get(0).getName()); - assertEquals("{spring.cloud.config.enabled=true}", environment - .getPropertySources().get(0).getSource().toString()); + Environment environment = new TestRestTemplate().getForObject( + "http://localhost:" + this.port + "/foo/development/", Environment.class); + assertThat(environment.getPropertySources().isEmpty()).isFalse(); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("overrides"); + assertThat(environment.getPropertySources().get(0).getSource().toString()) + .isEqualTo("{spring.cloud.config.enabled=true}"); } @Test public void resourseEndpointsWork() { - String text = new TestRestTemplate().getForObject("http://localhost:" - + port + "/foo/development/master/bar.properties", String.class); + String text = new TestRestTemplate().getForObject("http://localhost:" + this.port + + "/foo/development/master/bar.properties", String.class); String expected = "foo: bar"; - assertEquals("invalid content", expected, text); + assertThat(text).as("invalid content").isEqualTo(expected); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM)); - ResponseEntity response = new TestRestTemplate().exchange("http://localhost:" - + port + "/foo/development/raw/bar.properties", HttpMethod.GET, new HttpEntity<>(headers), byte[].class); - //FIXME: this is calling the text endpoint, not the binary one - // assertTrue("invalid content type", response.getHeaders().getContentType().isCompatibleWith(MediaType.APPLICATION_OCTET_STREAM)); - assertEquals(expected.length(), response.getBody().length); + ResponseEntity response = new TestRestTemplate().exchange( + "http://localhost:" + this.port + "/foo/development/raw/bar.properties", + HttpMethod.GET, new HttpEntity<>(headers), byte[].class); + // FIXME: this is calling the text endpoint, not the binary one + // assertTrue("invalid content type", + // response.getHeaders().getContentType().isCompatibleWith(MediaType.APPLICATION_OCTET_STREAM)); + assertThat(response.getBody().length).isEqualTo(expected.length()); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/composite/CompositUtilsTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/composite/CompositUtilsTests.java index 8289ff02..3749ecb1 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/composite/CompositUtilsTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/composite/CompositUtilsTests.java @@ -1,11 +1,27 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.composite; import java.util.List; import org.junit.Rule; import org.junit.Test; - import org.junit.rules.ExpectedException; + import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.cloud.config.server.ConfigServerApplication; @@ -13,41 +29,43 @@ import static org.assertj.core.api.Assertions.assertThat; public class CompositUtilsTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); + @Rule + public ExpectedException thrown = ExpectedException.none(); - @Test - public void getCompositeTypeListWorks() { - new WebApplicationContextRunner() - .withUserConfiguration(ConfigServerApplication.class) - .withPropertyValues("spring.profiles.active:test,composite", - "spring.config.name:compositeconfigserver", - "spring.jmx.enabled=false", - "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[0].type:git", - "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", - "spring.cloud.config.server.composite[1].type:svn") - .run(context -> { - List types = CompositeUtils.getCompositeTypeList(context.getEnvironment()); - assertThat(types).containsExactly("git", "svn"); - }); - } + @Test + public void getCompositeTypeListWorks() { + new WebApplicationContextRunner() + .withUserConfiguration(ConfigServerApplication.class) + .withPropertyValues("spring.profiles.active:test,composite", + "spring.config.name:compositeconfigserver", + "spring.jmx.enabled=false", + "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[0].type:git", + "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", + "spring.cloud.config.server.composite[1].type:svn") + .run(context -> { + List types = CompositeUtils + .getCompositeTypeList(context.getEnvironment()); + assertThat(types).containsExactly("git", "svn"); + }); + } - @Test - public void getCompositeTypeListFails() { - thrown.expect(IllegalStateException.class); + @Test + public void getCompositeTypeListFails() { + this.thrown.expect(IllegalStateException.class); + + new WebApplicationContextRunner() + .withUserConfiguration(ConfigServerApplication.class) + .withPropertyValues("spring.profiles.active:test,composite", + "spring.config.name:compositeconfigserver", + "spring.jmx.enabled=false", + "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[0].type:git", + "spring.cloud.config.server.composite[2].uri:file:///./target/repos/svn-config-repo", + "spring.cloud.config.server.composite[2].type:svn") + .run(context -> { + CompositeUtils.getCompositeTypeList(context.getEnvironment()); + }); + } - new WebApplicationContextRunner() - .withUserConfiguration(ConfigServerApplication.class) - .withPropertyValues("spring.profiles.active:test,composite", - "spring.config.name:compositeconfigserver", - "spring.jmx.enabled=false", - "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[0].type:git", - "spring.cloud.config.server.composite[2].uri:file:///./target/repos/svn-config-repo", - "spring.cloud.config.server.composite[2].type:svn") - .run(context -> { - CompositeUtils.getCompositeTypeList(context.getEnvironment()); - }); - } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicatorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicatorTests.java index f338c861..3db6bcee 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicatorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicatorTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.config; import java.util.Collections; @@ -13,7 +29,7 @@ import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.server.config.ConfigServerHealthIndicator.Repository; import org.springframework.cloud.config.server.environment.EnvironmentRepository; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; @@ -34,20 +50,24 @@ public class ConfigServerHealthIndicatorTests { @Before public void init() { initMocks(this); - indicator = new ConfigServerHealthIndicator(repository); - indicator.init(); + this.indicator = new ConfigServerHealthIndicator(this.repository); + this.indicator.init(); } @Test public void defaultStatusWorks() { - when(repository.findOne(anyString(), anyString(), Mockito.isNull())).thenReturn(environment); - assertEquals("wrong default status", Status.UP, indicator.health().getStatus()); + when(this.repository.findOne(anyString(), anyString(), Mockito.isNull())) + .thenReturn(this.environment); + assertThat(this.indicator.health().getStatus()).as("wrong default status") + .isEqualTo(Status.UP); } @Test public void exceptionStatusIsDown() { - when(repository.findOne(anyString(), anyString(), Mockito.isNull())).thenThrow(new RuntimeException()); - assertEquals("wrong exception status", Status.DOWN, indicator.health().getStatus()); + when(this.repository.findOne(anyString(), anyString(), Mockito.isNull())) + .thenThrow(new RuntimeException()); + assertThat(this.indicator.health().getStatus()).as("wrong exception status") + .isEqualTo(Status.DOWN); } @Test @@ -57,7 +77,10 @@ public class ConfigServerHealthIndicatorTests { repo.setProfiles("myprofile"); repo.setLabel("mylabel"); this.indicator.setRepositories(Collections.singletonMap("myname", repo)); - when(repository.findOne("myname", "myprofile", "mylabel")).thenReturn(environment); - assertEquals("wrong default status", Status.UP, indicator.health().getStatus()); + when(this.repository.findOne("myname", "myprofile", "mylabel")) + .thenReturn(this.environment); + assertThat(this.indicator.health().getStatus()).as("wrong default status") + .isEqualTo(Status.UP); } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java index 6881d05c..ecc80a3c 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.config; import java.util.HashMap; @@ -42,8 +43,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter @@ -51,12 +51,11 @@ import static org.junit.Assert.assertTrue; public class CustomCompositeEnvironmentRepositoryTests { @RunWith(SpringRunner.class) - @SpringBootTest(classes = CustomCompositeEnvironmentRepositoryTests - .StaticTests.Config.class, properties = { + @SpringBootTest(classes = CustomCompositeEnvironmentRepositoryTests.StaticTests.Config.class, properties = { "spring.config.name:compositeconfigserver", "spring.cloud.config.server.git.uri:file:./target/repos/config-repo", "spring.cloud.config.server.git.order:1" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) - @ActiveProfiles({"test", "git"}) + @ActiveProfiles({ "test", "git" }) @DirtiesContext public static class StaticTests { @@ -71,12 +70,13 @@ public class CustomCompositeEnvironmentRepositoryTests { @Test public void contextLoads() { Environment environment = new TestRestTemplate().getForObject( - "http://localhost:" + port + "/foo/development/", Environment.class); + "http://localhost:" + this.port + "/foo/development/", + Environment.class); List propertySources = environment.getPropertySources(); - assertEquals(3, propertySources.size()); - assertEquals("overrides", propertySources.get(0).getName()); - assertTrue(propertySources.get(1).getName().contains("config-repo")); - assertEquals("p", propertySources.get(2).getName()); + assertThat(3).isEqualTo(propertySources.size()); + assertThat("overrides").isEqualTo(propertySources.get(0).getName()); + assertThat(propertySources.get(1).getName().contains("config-repo")).isTrue(); + assertThat("p").isEqualTo(propertySources.get(2).getName()); } @Configuration @@ -84,30 +84,32 @@ public class CustomCompositeEnvironmentRepositoryTests { @EnableConfigServer protected static class Config { - @Bean - public EnvironmentRepository environmentRepository() { - return new CustomEnvironmentRepository(new CustomEnvironmentProperties("p")); + public static void main(String[] args) throws Exception { + SpringApplication.run( + CustomEnvironmentRepositoryTests.TestApplication.class, args); } - public static void main(String[] args) throws Exception { - SpringApplication.run(CustomEnvironmentRepositoryTests.TestApplication.class, - args); + @Bean + public EnvironmentRepository environmentRepository() { + return new CustomEnvironmentRepository( + new CustomEnvironmentProperties("p")); } + } + } @RunWith(SpringRunner.class) - @SpringBootTest(classes = CustomCompositeEnvironmentRepositoryTests - .ListTests.Config.class, properties = { + @SpringBootTest(classes = CustomCompositeEnvironmentRepositoryTests.ListTests.Config.class, properties = { "spring.config.name:compositeconfigserver", "spring.cloud.config.server.composite[0].type:git", "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", "spring.cloud.config.server.composite[1].type:custom", - "spring.cloud.config.server.composite[1].propertySourceName:p" - }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) - @ActiveProfiles({"test", "composite"}) + "spring.cloud.config.server.composite[1].propertySourceName:p" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + @ActiveProfiles({ "test", "composite" }) @DirtiesContext public static class ListTests { + @LocalServerPort private int port; @@ -119,12 +121,13 @@ public class CustomCompositeEnvironmentRepositoryTests { @Test public void contextLoads() { Environment environment = new TestRestTemplate().getForObject( - "http://localhost:" + port + "/foo/development/", Environment.class); + "http://localhost:" + this.port + "/foo/development/", + Environment.class); List propertySources = environment.getPropertySources(); - assertEquals(3, propertySources.size()); - assertEquals("overrides", propertySources.get(0).getName()); - assertTrue(propertySources.get(1).getName().contains("config-repo")); - assertEquals("p", propertySources.get(2).getName()); + assertThat(3).isEqualTo(propertySources.size()); + assertThat("overrides").isEqualTo(propertySources.get(0).getName()); + assertThat(propertySources.get(1).getName().contains("config-repo")).isTrue(); + assertThat("p").isEqualTo(propertySources.get(2).getName()); } @Configuration @@ -132,41 +135,45 @@ public class CustomCompositeEnvironmentRepositoryTests { @EnableConfigServer protected static class Config { + public static void main(String[] args) throws Exception { + SpringApplication.run( + CustomEnvironmentRepositoryTests.TestApplication.class, args); + } + @Bean - public CustomEnvironmentRepositoryFactory customEnvironmentRepositoryFactory(ConfigurableEnvironment environment) - { + public CustomEnvironmentRepositoryFactory customEnvironmentRepositoryFactory( + ConfigurableEnvironment environment) { return new CustomEnvironmentRepositoryFactory(); } - public static void main(String[] args) throws Exception { - SpringApplication.run(CustomEnvironmentRepositoryTests.TestApplication.class, - args); - } - } + } - static class CustomEnvironmentRepositoryFactory implements EnvironmentRepositoryFactory { + static class CustomEnvironmentRepositoryFactory implements + EnvironmentRepositoryFactory { @Override - public CustomEnvironmentRepository build(CustomEnvironmentProperties environmentProperties) throws Exception { + public CustomEnvironmentRepository build( + CustomEnvironmentProperties environmentProperties) throws Exception { return new CustomEnvironmentRepository(environmentProperties); } + } static class CustomEnvironmentProperties implements EnvironmentRepositoryProperties { + private String propertySourceName; - public CustomEnvironmentProperties() { + CustomEnvironmentProperties() { } - public CustomEnvironmentProperties(String propertySourceName) { + CustomEnvironmentProperties(String propertySourceName) { this.propertySourceName = propertySourceName; } public String getPropertySourceName() { - return propertySourceName; + return this.propertySourceName; } public void setPropertySourceName(String propertySourceName) { @@ -177,13 +184,14 @@ public class CustomCompositeEnvironmentRepositoryTests { public void setOrder(int order) { } + } static class CustomEnvironmentRepository implements EnvironmentRepository, Ordered { private final CustomEnvironmentProperties properties; - public CustomEnvironmentRepository(CustomEnvironmentProperties properties) { + CustomEnvironmentRepository(CustomEnvironmentProperties properties) { this.properties = properties; } @@ -191,7 +199,8 @@ public class CustomCompositeEnvironmentRepositoryTests { public Environment findOne(String application, String profile, String label) { Environment e = new Environment("test", new String[0], "label", "version", "state"); - PropertySource p = new PropertySource(properties.getPropertySourceName(), new HashMap<>()); + PropertySource p = new PropertySource(this.properties.getPropertySourceName(), + new HashMap<>()); e.add(p); return e; } @@ -200,5 +209,7 @@ public class CustomCompositeEnvironmentRepositoryTests { public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } + } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java index ebcff449..50a74f46 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.cloud.config.server.config; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -34,7 +35,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -53,8 +54,8 @@ public class CustomEnvironmentRepositoryTests { @Test public void contextLoads() { Environment environment = new TestRestTemplate().getForObject( - "http://localhost:" + port + "/foo/development/", Environment.class); - assertFalse(environment.getPropertySources().isEmpty()); + "http://localhost:" + this.port + "/foo/development/", Environment.class); + assertThat(environment.getPropertySources().isEmpty()).isFalse(); } @Configuration @@ -62,6 +63,11 @@ public class CustomEnvironmentRepositoryTests { @EnableConfigServer protected static class TestApplication { + public static void main(String[] args) throws Exception { + SpringApplication.run(CustomEnvironmentRepositoryTests.TestApplication.class, + args); + } + @Bean public EnvironmentRepository environmentRepository() { return new EnvironmentRepository() { @@ -75,11 +81,6 @@ public class CustomEnvironmentRepositoryTests { }; } - public static void main(String[] args) throws Exception { - SpringApplication.run(CustomEnvironmentRepositoryTests.TestApplication.class, - args); - } - } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/HttpClientVaultRestTemplateFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/HttpClientVaultRestTemplateFactoryTest.java index 70853c51..ef343a1e 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/HttpClientVaultRestTemplateFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/HttpClientVaultRestTemplateFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.config; import java.net.UnknownHostException; @@ -38,113 +39,125 @@ import static org.hamcrest.Matchers.instanceOf; * @author Dylan Roberts */ public class HttpClientVaultRestTemplateFactoryTest { - private static final ProxyHostProperties AUTHENTICATED_HTTP_PROXY = new ProxyHostProperties(); - static { - AUTHENTICATED_HTTP_PROXY.setHost("http://authenticated.http.proxy"); - AUTHENTICATED_HTTP_PROXY.setPort(8080); - AUTHENTICATED_HTTP_PROXY.setUsername("username"); - AUTHENTICATED_HTTP_PROXY.setPassword("password"); - } - private static final ProxyHostProperties AUTHENTICATED_HTTPS_PROXY = new ProxyHostProperties(); - static { - AUTHENTICATED_HTTPS_PROXY.setHost("http://authenticated.https.proxy"); - AUTHENTICATED_HTTPS_PROXY.setPort(8081); - AUTHENTICATED_HTTPS_PROXY.setUsername("username2"); - AUTHENTICATED_HTTPS_PROXY.setPassword("password2"); - } - private static final ProxyHostProperties HTTP_PROXY = new ProxyHostProperties(); - static { - HTTP_PROXY.setHost("http://http.proxy"); - HTTP_PROXY.setPort(8080); - } - private static final ProxyHostProperties HTTPS_PROXY = new ProxyHostProperties(); - static { - HTTPS_PROXY.setHost("http://https.proxy"); - HTTPS_PROXY.setPort(8081); - } - private HttpClientVaultRestTemplateFactory factory; + private static final ProxyHostProperties AUTHENTICATED_HTTP_PROXY = new ProxyHostProperties(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); + private static final ProxyHostProperties AUTHENTICATED_HTTPS_PROXY = new ProxyHostProperties(); - @Before - public void setUp() { - factory = new HttpClientVaultRestTemplateFactory(); - } + private static final ProxyHostProperties HTTP_PROXY = new ProxyHostProperties(); - @Test - public void authenticatedHttpsProxy() throws Exception { - VaultEnvironmentProperties properties = getVaultEnvironmentProperties(null, AUTHENTICATED_HTTPS_PROXY); - RestTemplate restTemplate = factory.build(properties); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(AUTHENTICATED_HTTPS_PROXY.getHost())))); + private static final ProxyHostProperties HTTPS_PROXY = new ProxyHostProperties(); - restTemplate.getForObject("https://somehost", String.class); - } + static { + AUTHENTICATED_HTTP_PROXY.setHost("http://authenticated.http.proxy"); + AUTHENTICATED_HTTP_PROXY.setPort(8080); + AUTHENTICATED_HTTP_PROXY.setUsername("username"); + AUTHENTICATED_HTTP_PROXY.setPassword("password"); + } - @Test - public void httpsProxy() throws Exception { - VaultEnvironmentProperties properties = getVaultEnvironmentProperties(null, HTTPS_PROXY); - RestTemplate restTemplate = factory.build(properties); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(HTTPS_PROXY.getHost())))); + static { + AUTHENTICATED_HTTPS_PROXY.setHost("http://authenticated.https.proxy"); + AUTHENTICATED_HTTPS_PROXY.setPort(8081); + AUTHENTICATED_HTTPS_PROXY.setUsername("username2"); + AUTHENTICATED_HTTPS_PROXY.setPassword("password2"); + } - restTemplate.getForObject("https://somehost", String.class); - } + static { + HTTP_PROXY.setHost("http://http.proxy"); + HTTP_PROXY.setPort(8080); + } - @Test - public void httpsProxy_notCalled() throws Exception { - VaultEnvironmentProperties properties = getVaultEnvironmentProperties(null, HTTPS_PROXY); - RestTemplate restTemplate = factory.build(properties); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString("somehost")))); + static { + HTTPS_PROXY.setHost("http://https.proxy"); + HTTPS_PROXY.setPort(8081); + } - restTemplate.getForObject("http://somehost", String.class); - } + @Rule + public ExpectedException expectedException = ExpectedException.none(); - @Test - public void authenticatedHttpProxy() throws Exception { - VaultEnvironmentProperties properties = getVaultEnvironmentProperties(AUTHENTICATED_HTTP_PROXY, null); - RestTemplate restTemplate = factory.build(properties); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(AUTHENTICATED_HTTP_PROXY.getHost())))); + private HttpClientVaultRestTemplateFactory factory; - restTemplate.getForObject("http://somehost", String.class); - } + @Before + public void setUp() { + this.factory = new HttpClientVaultRestTemplateFactory(); + } - @Test - public void httpProxy() throws Exception { - VaultEnvironmentProperties properties = getVaultEnvironmentProperties(HTTP_PROXY, null); - RestTemplate restTemplate = factory.build(properties); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(HTTP_PROXY.getHost())))); + @Test + public void authenticatedHttpsProxy() throws Exception { + VaultEnvironmentProperties properties = getVaultEnvironmentProperties(null, + AUTHENTICATED_HTTPS_PROXY); + RestTemplate restTemplate = this.factory.build(properties); + this.expectedException.expectCause( + allOf(instanceOf(UnknownHostException.class), hasProperty("message", + containsString(AUTHENTICATED_HTTPS_PROXY.getHost())))); - restTemplate.getForObject("http://somehost", String.class); - } + restTemplate.getForObject("https://somehost", String.class); + } - @Test - public void httpProxy_notCalled() throws Exception { - VaultEnvironmentProperties properties = getVaultEnvironmentProperties(HTTP_PROXY, null); - RestTemplate restTemplate = factory.build(properties); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString("somehost")))); + @Test + public void httpsProxy() throws Exception { + VaultEnvironmentProperties properties = getVaultEnvironmentProperties(null, + HTTPS_PROXY); + RestTemplate restTemplate = this.factory.build(properties); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString(HTTPS_PROXY.getHost())))); - restTemplate.getForObject("https://somehost", String.class); - } + restTemplate.getForObject("https://somehost", String.class); + } - private VaultEnvironmentProperties getVaultEnvironmentProperties(ProxyHostProperties httpProxy, ProxyHostProperties httpsProxy) { - Map proxyMap = new HashMap<>(); - proxyMap.put(ProxyHostProperties.ProxyForScheme.HTTP, httpProxy); - proxyMap.put(ProxyHostProperties.ProxyForScheme.HTTPS, httpsProxy); - VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); - properties.setProxy(proxyMap); - return properties; - } -} \ No newline at end of file + @Test + public void httpsProxy_notCalled() throws Exception { + VaultEnvironmentProperties properties = getVaultEnvironmentProperties(null, + HTTPS_PROXY); + RestTemplate restTemplate = this.factory.build(properties); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString("somehost")))); + + restTemplate.getForObject("http://somehost", String.class); + } + + @Test + public void authenticatedHttpProxy() throws Exception { + VaultEnvironmentProperties properties = getVaultEnvironmentProperties( + AUTHENTICATED_HTTP_PROXY, null); + RestTemplate restTemplate = this.factory.build(properties); + this.expectedException.expectCause( + allOf(instanceOf(UnknownHostException.class), hasProperty("message", + containsString(AUTHENTICATED_HTTP_PROXY.getHost())))); + + restTemplate.getForObject("http://somehost", String.class); + } + + @Test + public void httpProxy() throws Exception { + VaultEnvironmentProperties properties = getVaultEnvironmentProperties(HTTP_PROXY, + null); + RestTemplate restTemplate = this.factory.build(properties); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString(HTTP_PROXY.getHost())))); + + restTemplate.getForObject("http://somehost", String.class); + } + + @Test + public void httpProxy_notCalled() throws Exception { + VaultEnvironmentProperties properties = getVaultEnvironmentProperties(HTTP_PROXY, + null); + RestTemplate restTemplate = this.factory.build(properties); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString("somehost")))); + + restTemplate.getForObject("https://somehost", String.class); + } + + private VaultEnvironmentProperties getVaultEnvironmentProperties( + ProxyHostProperties httpProxy, ProxyHostProperties httpsProxy) { + Map proxyMap = new HashMap<>(); + proxyMap.put(ProxyHostProperties.ProxyForScheme.HTTP, httpProxy); + proxyMap.put(ProxyHostProperties.ProxyForScheme.HTTPS, httpsProxy); + VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); + properties.setProxy(proxyMap); + return properties; + } + +} diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java index 9909d491..bdededa8 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,131 +28,144 @@ import org.junit.Test; import org.springframework.cloud.config.server.support.AwsCodeCommitCredentialProvider; import org.springframework.cloud.config.server.support.GitCredentialsProviderFactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** - * It would be nice to do an integration test, however, this would require - * using real AWS credentials. How can we test the credential generation - * without real credentials? - * + * It would be nice to do an integration test, however, this would require using real AWS + * credentials. How can we test the credential generation without real credentials? + * * @author don laidlaw * */ public class AwsCodeCommitCredentialsProviderTests { + private static final String PASSWORD = "secret"; + private static final String USER = "test"; + private static final String AWS_REPO = "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/test"; + private static final String BAD_REPO = "https://amazonaws.com/v1/repos/test"; - private static final String CURLY_BRACES_REPO = "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/{application}"; + + private static final String CURLY_BRACES_REPO = "https://git-codecommit.us-east-1.amazonaws.com/" + + "v1/repos/{application}"; private AwsCodeCommitCredentialProvider provider; - + @Before public void init() { GitCredentialsProviderFactory factory = new GitCredentialsProviderFactory(); - provider = (AwsCodeCommitCredentialProvider) - factory.createFor(AWS_REPO, USER, PASSWORD, null, false); + this.provider = (AwsCodeCommitCredentialProvider) factory.createFor(AWS_REPO, + USER, PASSWORD, null, false); } - + @Test public void basics() { - assertNotNull(provider); - assertEquals(USER, provider.getUsername()); - assertEquals(PASSWORD, provider.getPassword()); - assertFalse(provider.isInteractive()); + assertThat(this.provider).isNotNull(); + assertThat(this.provider.getUsername()).isEqualTo(USER); + assertThat(this.provider.getPassword()).isEqualTo(PASSWORD); + assertThat(this.provider.isInteractive()).isFalse(); } @Test public void testSupportsUsernamePassword() { - assertTrue(provider.supports(new CredentialItem[] { - new CredentialItem.Username(), - new CredentialItem.Password() - })); + assertThat(this.provider.supports(new CredentialItem[] { + new CredentialItem.Username(), new CredentialItem.Password() })).isTrue(); } @Test public void testNotSupportsOther() { - assertFalse(provider.supports(new CredentialItem[] { - new CredentialItem.YesNoType("OK To Login?") // this is not ok - })); - assertFalse(provider.supports(new CredentialItem[] { - new CredentialItem.StringType("OK To Login?", true) // this is not ok - })); - assertFalse(provider.supports(new CredentialItem[] { - new CredentialItem.Username(), // this is ok - new CredentialItem.Password(), // this is ok - new CredentialItem.StringType("OK To Login?", true) // this is not ok - })); + assertThat(this.provider.supports( + new CredentialItem[] { new CredentialItem.YesNoType("OK To Login?") // this + // is + // not + // ok + })).isFalse(); + assertThat(this.provider.supports( + new CredentialItem[] { new CredentialItem.StringType("OK To Login?", true) // this + // is + // not + // ok + })).isFalse(); + assertThat(this.provider + .supports(new CredentialItem[] { new CredentialItem.Username(), // this + // is + // ok + new CredentialItem.Password(), // this is ok + new CredentialItem.StringType("OK To Login?", true) // this is not + // ok + })).isFalse(); } - + @Test public void testAwsCredentialsProviderIsNullInitially() { - AWSCredentialsProvider awsProvider = provider.getAwsCredentialProvider(); - assertNull(awsProvider); + AWSCredentialsProvider awsProvider = this.provider.getAwsCredentialProvider(); + assertThat(awsProvider).isNull(); } @Test public void testAwsCredentialsProviderIsDefinedAfterGet() throws URISyntaxException { - AWSCredentialsProvider awsProvider = provider.getAwsCredentialProvider(); - assertNull(awsProvider); - assertTrue(provider.get(new URIish(AWS_REPO), makeCredentialItems())); - awsProvider = provider.getAwsCredentialProvider(); - assertNotNull(awsProvider); - assertTrue(awsProvider instanceof AwsCodeCommitCredentialProvider.AWSStaticCredentialsProvider); + AWSCredentialsProvider awsProvider = this.provider.getAwsCredentialProvider(); + assertThat(awsProvider).isNull(); + assertThat(this.provider.get(new URIish(AWS_REPO), makeCredentialItems())) + .isTrue(); + awsProvider = this.provider.getAwsCredentialProvider(); + assertThat(awsProvider).isNotNull(); + assertThat( + awsProvider instanceof AwsCodeCommitCredentialProvider.AWSStaticCredentialsProvider) + .isTrue(); } - + @Test - public void testBadUriReturnsFalse() throws UnsupportedCredentialItem, URISyntaxException { + public void testBadUriReturnsFalse() + throws UnsupportedCredentialItem, URISyntaxException { CredentialItem[] credentialItems = makeCredentialItems(); - assertFalse(provider.get(new URIish(BAD_REPO), credentialItems)); + assertThat(this.provider.get(new URIish(BAD_REPO), credentialItems)).isFalse(); } - + @Test - public void testUriWithCurlyBracesReturnsTrue() throws UnsupportedCredentialItem, URISyntaxException { + public void testUriWithCurlyBracesReturnsTrue() + throws UnsupportedCredentialItem, URISyntaxException { GitCredentialsProviderFactory factory = new GitCredentialsProviderFactory(); - provider = (AwsCodeCommitCredentialProvider) - factory.createFor(CURLY_BRACES_REPO, USER, PASSWORD, null, false); + this.provider = (AwsCodeCommitCredentialProvider) factory + .createFor(CURLY_BRACES_REPO, USER, PASSWORD, null, false); CredentialItem[] credentialItems = makeCredentialItems(); - assertTrue(provider.get(new URIish(CURLY_BRACES_REPO), credentialItems)); + assertThat(this.provider.get(new URIish(CURLY_BRACES_REPO), credentialItems)) + .isTrue(); } - + @Test public void testThrowsUnsupportedCredentialException() throws URISyntaxException { CredentialItem[] goodCredentialItems = makeCredentialItems(); CredentialItem[] badCredentialItems = new CredentialItem[] { - goodCredentialItems[0], - goodCredentialItems[1], - new CredentialItem.YesNoType("OK?") - }; + goodCredentialItems[0], goodCredentialItems[1], + new CredentialItem.YesNoType("OK?") }; try { - provider.get(new URIish(AWS_REPO), badCredentialItems); + this.provider.get(new URIish(AWS_REPO), badCredentialItems); fail("Expected UnsupportedCredentialItem exception"); - } catch (UnsupportedCredentialItem e) { - assertNotNull(e.getMessage()); + } + catch (UnsupportedCredentialItem e) { + assertThat(e.getMessage()).isNotNull(); } } - + @Test public void testReturnsCredentials() throws URISyntaxException { CredentialItem[] credentialItems = makeCredentialItems(); - assertTrue(provider.get(new URIish(AWS_REPO), credentialItems)); - + assertThat(this.provider.get(new URIish(AWS_REPO), credentialItems)).isTrue(); + String theUsername = ((CredentialItem.Username) credentialItems[0]).getValue(); char[] thePassword = ((CredentialItem.Password) credentialItems[1]).getValue(); - - assertEquals(USER, theUsername); - assertNotNull(thePassword); - + + assertThat(theUsername).isEqualTo(USER); + assertThat(thePassword).isNotNull(); + // The password will always begin with a timestamp like // 20161113T121314Z - assertTrue(thePassword.length > 16); - assertEquals('T', thePassword[8]); - assertEquals('Z', thePassword[15]); + assertThat(thePassword.length > 16).isTrue(); + assertThat(thePassword[8]).isEqualTo('T'); + assertThat(thePassword[15]).isEqualTo('Z'); } private CredentialItem[] makeCredentialItems() { @@ -161,4 +174,5 @@ public class AwsCodeCommitCredentialsProviderTests { credentialItems[1] = new CredentialItem.Password(); return credentialItems; } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/GitCredentialsProviderFactoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/GitCredentialsProviderFactoryTests.java index 5718fe01..0f99d76c 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/GitCredentialsProviderFactoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/GitCredentialsProviderFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,139 +23,143 @@ import org.junit.Test; import org.springframework.cloud.config.server.support.AwsCodeCommitCredentialProvider; import org.springframework.cloud.config.server.support.GitCredentialsProviderFactory; -import org.springframework.cloud.config.server.support.PassphraseCredentialsProvider; import org.springframework.cloud.config.server.support.GitSkipSslValidationCredentialsProvider; +import org.springframework.cloud.config.server.support.PassphraseCredentialsProvider; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author don laidlaw * @author Gareth Clay */ public class GitCredentialsProviderFactoryTests { + private static final String PASSWORD = "secret"; + private static final String USER = "test"; + private static final String FILE_REPO = "file:///home/user/repo"; + private static final String HTTPS_GIT_REPO = "https://github.com/spring-cloud/spring-cloud-config-test"; + private static final String SSH_GIT_REPO = "git@github.com:spring-cloud/spring-cloud-config-test.git"; + private static final String AWS_REPO = "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/test"; private GitCredentialsProviderFactory factory; - + @Before public void init() { - factory = new GitCredentialsProviderFactory(); + this.factory = new GitCredentialsProviderFactory(); } @Test public void testCreateForFileNoUsernameIsNull() { - CredentialsProvider provider = factory.createFor(FILE_REPO, null, null, null, + CredentialsProvider provider = this.factory.createFor(FILE_REPO, null, null, null, false); - assertNull(provider); + assertThat(provider).isNull(); } @Test public void testCreateForFileWithUsername() { - CredentialsProvider provider = factory.createFor(FILE_REPO, USER, PASSWORD, null, - false); - assertNotNull(provider); - assertTrue(provider instanceof UsernamePasswordCredentialsProvider); + CredentialsProvider provider = this.factory.createFor(FILE_REPO, USER, PASSWORD, + null, false); + assertThat(provider).isNotNull(); + assertThat(provider instanceof UsernamePasswordCredentialsProvider).isTrue(); } @Test public void testCreateForServerNoUsernameIsNull() { - CredentialsProvider provider = factory.createFor(HTTPS_GIT_REPO, null, null, null, - false); - assertNull(provider); + CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, null, null, + null, false); + assertThat(provider).isNull(); } @Test public void testCreateForServerWithUsername() { - CredentialsProvider provider = factory.createFor(HTTPS_GIT_REPO, USER, PASSWORD, - null, false); - assertNotNull(provider); - assertTrue(provider instanceof UsernamePasswordCredentialsProvider); + CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, USER, + PASSWORD, null, false); + assertThat(provider).isNotNull(); + assertThat(provider instanceof UsernamePasswordCredentialsProvider).isTrue(); } @Test public void testCreateForHttpsServerWithSkipSslValidation() { - CredentialsProvider provider = factory.createFor(HTTPS_GIT_REPO, USER, PASSWORD, - null, true); - assertNotNull(provider); - assertTrue(provider instanceof GitSkipSslValidationCredentialsProvider); + CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, USER, + PASSWORD, null, true); + assertThat(provider).isNotNull(); + assertThat(provider instanceof GitSkipSslValidationCredentialsProvider).isTrue(); } @Test public void testCreateForHttpsServerWithoutSpecifyingSkipSslValidation() { - CredentialsProvider provider = factory.createFor(HTTPS_GIT_REPO, USER, PASSWORD, null); - assertNotNull(provider); - assertTrue("deprecated createFor() should not enable ssl validation skipping", - provider instanceof UsernamePasswordCredentialsProvider); + CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, USER, + PASSWORD, null); + assertThat(provider).isNotNull(); + assertThat(provider instanceof UsernamePasswordCredentialsProvider) + .as("deprecated createFor() should not enable ssl validation skipping") + .isTrue(); } @Test public void testCreateForSshServerWithSkipSslValidation() { - CredentialsProvider provider = factory.createFor(SSH_GIT_REPO, USER, PASSWORD, - null, true); - assertNotNull(provider); - assertTrue(provider instanceof UsernamePasswordCredentialsProvider); + CredentialsProvider provider = this.factory.createFor(SSH_GIT_REPO, USER, + PASSWORD, null, true); + assertThat(provider).isNotNull(); + assertThat(provider instanceof UsernamePasswordCredentialsProvider).isTrue(); } @Test public void testCreateForAwsNoUsername() { - CredentialsProvider provider = factory.createFor(AWS_REPO, null, null, null, + CredentialsProvider provider = this.factory.createFor(AWS_REPO, null, null, null, false); - assertNotNull(provider); - assertTrue(provider instanceof AwsCodeCommitCredentialProvider); + assertThat(provider).isNotNull(); + assertThat(provider instanceof AwsCodeCommitCredentialProvider).isTrue(); AwsCodeCommitCredentialProvider aws = (AwsCodeCommitCredentialProvider) provider; - assertNull(aws.getUsername()); - assertNull(aws.getPassword()); + assertThat(aws.getUsername()).isNull(); + assertThat(aws.getPassword()).isNull(); } @Test public void testCreateForAwsWithUsername() { - CredentialsProvider provider = factory.createFor(AWS_REPO, USER, PASSWORD, null, - false); - assertNotNull(provider); - assertTrue(provider instanceof AwsCodeCommitCredentialProvider); + CredentialsProvider provider = this.factory.createFor(AWS_REPO, USER, PASSWORD, + null, false); + assertThat(provider).isNotNull(); + assertThat(provider instanceof AwsCodeCommitCredentialProvider).isTrue(); AwsCodeCommitCredentialProvider aws = (AwsCodeCommitCredentialProvider) provider; - assertEquals(USER, aws.getUsername()); - assertEquals(PASSWORD, aws.getPassword()); + assertThat(aws.getUsername()).isEqualTo(USER); + assertThat(aws.getPassword()).isEqualTo(PASSWORD); } - + @Test public void testCreateForAwsDisabled() { - factory.setAwsCodeCommitEnabled(false); - CredentialsProvider provider = factory.createFor(AWS_REPO, null, null, null, + this.factory.setAwsCodeCommitEnabled(false); + CredentialsProvider provider = this.factory.createFor(AWS_REPO, null, null, null, false); - assertNull(provider); - provider = factory.createFor(AWS_REPO, USER, PASSWORD, null, false); - assertNotNull(provider); - assertTrue(provider instanceof UsernamePasswordCredentialsProvider); + assertThat(provider).isNull(); + provider = this.factory.createFor(AWS_REPO, USER, PASSWORD, null, false); + assertThat(provider).isNotNull(); + assertThat(provider instanceof UsernamePasswordCredentialsProvider).isTrue(); } - + @Test public void testCreatePassphraseCredentialProvider() { - CredentialsProvider provider = factory.createFor(HTTPS_GIT_REPO, null, null, + CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, null, null, PASSWORD, false); - assertNotNull(provider); - assertTrue(provider instanceof PassphraseCredentialsProvider); + assertThat(provider).isNotNull(); + assertThat(provider instanceof PassphraseCredentialsProvider).isTrue(); } @Test public void testIsAwsCodeCommitEnabled() { - assertTrue(factory.isAwsCodeCommitEnabled()); + assertThat(this.factory.isAwsCodeCommitEnabled()).isTrue(); } @Test public void testSetAwsCodeCommitEnabled() { - assertTrue(factory.isAwsCodeCommitEnabled()); - factory.setAwsCodeCommitEnabled(false); - assertFalse(factory.isAwsCodeCommitEnabled()); + assertThat(this.factory.isAwsCodeCommitEnabled()).isTrue(); + this.factory.setAwsCodeCommitEnabled(false); + assertThat(this.factory.isAwsCodeCommitEnabled()).isFalse(); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptorTests.java index ceddb803..5f4466b4 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import org.springframework.cloud.context.encrypt.EncryptorFactory; import org.springframework.security.crypto.encrypt.TextEncryptor; import static java.util.UUID.randomUUID; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class CipherEnvironmentEncryptorTests { @@ -41,17 +41,9 @@ public class CipherEnvironmentEncryptorTests { EnvironmentEncryptor encryptor; - @Parameters - public static List params() { - List list = new ArrayList<>(); - list.add(new Object[] { "deadbeef", "foo" }); - list.add(new Object[] { "4567890a12345678", "bar" }); - return list; - } - public CipherEnvironmentEncryptorTests(String salt, String key) { - textEncryptor = new EncryptorFactory(salt).create(key); - encryptor = new CipherEnvironmentEncryptor(new TextEncryptorLocator() { + this.textEncryptor = new EncryptorFactory(salt).create(key); + this.encryptor = new CipherEnvironmentEncryptor(new TextEncryptorLocator() { @Override public TextEncryptor locate(Map keys) { @@ -60,6 +52,14 @@ public class CipherEnvironmentEncryptorTests { }); } + @Parameters + public static List params() { + List list = new ArrayList<>(); + list.add(new Object[] { "deadbeef", "foo" }); + list.add(new Object[] { "4567890a12345678", "bar" }); + return list; + } + @Test public void shouldDecryptEnvironment() { // given @@ -71,8 +71,8 @@ public class CipherEnvironmentEncryptorTests { environment.getName(), "{cipher}" + this.textEncryptor.encrypt(secret)))); // then - assertEquals(secret, this.encryptor.decrypt(environment).getPropertySources() - .get(0).getSource().get(environment.getName())); + assertThat(this.encryptor.decrypt(environment).getPropertySources().get(0) + .getSource().get(environment.getName())).isEqualTo(secret); } @Test @@ -87,21 +87,21 @@ public class CipherEnvironmentEncryptorTests { "{cipher}{key:test}" + this.textEncryptor.encrypt(secret)))); // then - assertEquals(secret, this.encryptor.decrypt(environment).getPropertySources() - .get(0).getSource().get(environment.getName())); + assertThat(this.encryptor.decrypt(environment).getPropertySources().get(0) + .getSource().get(environment.getName())).isEqualTo(secret); } + @Test public void shouldBeAbleToUseNullAsPropertyValue() { // when Environment environment = new Environment("name", "profile", "label"); environment.add(new PropertySource("a", - Collections.singletonMap(environment.getName(), - null))); + Collections.singletonMap(environment.getName(), null))); // then - assertEquals(null, this.encryptor.decrypt(environment).getPropertySources() - .get(0).getSource().get(environment.getName())); + assertThat(this.encryptor.decrypt(environment).getPropertySources().get(0) + .getSource().get(environment.getName())).isEqualTo(null); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerMultiTextEncryptorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerMultiTextEncryptorTests.java index a19c7cb4..841208db 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerMultiTextEncryptorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerMultiTextEncryptorTests.java @@ -1,11 +1,28 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.encryption; -import static org.junit.Assert.assertEquals; -import static org.springframework.http.MediaType.TEXT_PLAIN; - import org.junit.Test; + import org.springframework.security.crypto.encrypt.Encryptors; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.http.MediaType.TEXT_PLAIN; + /** * @author Bartosz Wojtkiewicz * @@ -17,7 +34,9 @@ public class EncryptionControllerMultiTextEncryptorTests { new SingleTextEncryptorLocator(Encryptors.noOpText())); String application = "application"; + String profiles = "profile1,profile2"; + String data = "foo"; @Test @@ -31,8 +50,8 @@ public class EncryptionControllerMultiTextEncryptorTests { this.data, TEXT_PLAIN); // then - assertEquals(this.data, this.controller.decrypt(this.application, this.profiles, - encrypted, TEXT_PLAIN)); + assertThat(this.controller.decrypt(this.application, this.profiles, encrypted, + TEXT_PLAIN)).isEqualTo(this.data); } @Test(expected = EncryptionTooWeakException.class) diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerTests.java index 101d25cc..4c951511 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.config.server.encryption; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +package org.springframework.cloud.config.server.encryption; import java.util.Map; import org.junit.Test; import org.mockito.ArgumentCaptor; + import org.springframework.http.MediaType; import org.springframework.security.crypto.encrypt.Encryptors; import org.springframework.security.crypto.encrypt.TextEncryptor; import org.springframework.security.rsa.crypto.RsaSecretEncryptor; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + /** * @author Dave Syer * @@ -59,7 +56,7 @@ public class EncryptionControllerTests { public void shouldThrowExceptionOnDecryptInvalidData() { this.controller = new EncryptionController( new SingleTextEncryptorLocator(new RsaSecretEncryptor())); - controller.decrypt("foo", MediaType.TEXT_PLAIN); + this.controller.decrypt("foo", MediaType.TEXT_PLAIN); } @Test(expected = InvalidCipherException.class) @@ -67,7 +64,7 @@ public class EncryptionControllerTests { RsaSecretEncryptor encryptor = new RsaSecretEncryptor(); this.controller = new EncryptionController( new SingleTextEncryptorLocator(new RsaSecretEncryptor())); - controller.decrypt(encryptor.encrypt("foo"), MediaType.TEXT_PLAIN); + this.controller.decrypt(encryptor.encrypt("foo"), MediaType.TEXT_PLAIN); } @Test @@ -75,7 +72,8 @@ public class EncryptionControllerTests { this.controller = new EncryptionController( new SingleTextEncryptorLocator(new RsaSecretEncryptor())); String cipher = this.controller.encrypt("foo", MediaType.TEXT_PLAIN); - assertEquals("foo", this.controller.decrypt(cipher, MediaType.TEXT_PLAIN)); + assertThat(this.controller.decrypt(cipher, MediaType.TEXT_PLAIN)) + .isEqualTo("foo"); } @Test @@ -83,7 +81,7 @@ public class EncryptionControllerTests { this.controller = new EncryptionController( new SingleTextEncryptorLocator(new RsaSecretEncryptor())); String key = this.controller.getPublicKey(); - assertTrue("Wrong key format: " + key, key.startsWith("ssh-rsa")); + assertThat(key.startsWith("ssh-rsa")).as("Wrong key format: " + key).isTrue(); } @Test @@ -95,7 +93,8 @@ public class EncryptionControllerTests { MediaType.TEXT_PLAIN); String decrypt = this.controller.decrypt("app", "default", cipher, MediaType.TEXT_PLAIN); - assertEquals("Wrong decrypted plaintext: " + decrypt, "foo bar", decrypt); + assertThat(decrypt).as("Wrong decrypted plaintext: " + decrypt) + .isEqualTo("foo bar"); } @Test @@ -107,7 +106,8 @@ public class EncryptionControllerTests { MediaType.APPLICATION_FORM_URLENCODED); String decrypt = this.controller.decrypt(cipher + "=", MediaType.APPLICATION_FORM_URLENCODED); - assertEquals("Wrong decrypted plaintext: " + decrypt, "foo bar", decrypt); + assertThat(decrypt).as("Wrong decrypted plaintext: " + decrypt) + .isEqualTo("foo bar"); } @Test @@ -119,7 +119,8 @@ public class EncryptionControllerTests { MediaType.APPLICATION_FORM_URLENCODED); String decrypt = this.controller.decrypt(cipher + "=", MediaType.APPLICATION_FORM_URLENCODED); - assertEquals("Wrong decrypted plaintext: " + decrypt, "foo bar", decrypt); + assertThat(decrypt).as("Wrong decrypted plaintext: " + decrypt) + .isEqualTo("foo bar"); } @Test @@ -127,12 +128,14 @@ public class EncryptionControllerTests { TextEncryptor encryptor = mock(TextEncryptor.class); when(encryptor.encrypt(anyString())).thenReturn("myEncryptedValue"); - this.controller = new EncryptionController(new SingleTextEncryptorLocator(encryptor)); + this.controller = new EncryptionController( + new SingleTextEncryptorLocator(encryptor)); this.controller.encrypt("{key:test}foo", MediaType.TEXT_PLAIN); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(encryptor, atLeastOnce()).encrypt(captor.capture()); - assertThat("Prefix must be stripped prior to encrypt", captor.getValue(), not(containsString("{key:test}"))); + assertThat(captor.getValue()).doesNotContain("{key:test}") + .as("Prefix must be stripped prior to encrypt"); } @Test @@ -146,7 +149,7 @@ public class EncryptionControllerTests { MediaType.APPLICATION_FORM_URLENCODED); String decrypt = this.controller.decrypt(cipher, MediaType.APPLICATION_FORM_URLENCODED); - assertEquals(plain, decrypt); + assertThat(decrypt).isEqualTo(plain); } @Test @@ -164,10 +167,11 @@ public class EncryptionControllerTests { // Add space to input String cipher = this.controller.encrypt("app", "default", "foo bar", MediaType.TEXT_PLAIN); - assertFalse("Wrong cipher: " + cipher, cipher.contains("{name:app}")); + assertThat(cipher.contains("{name:app}")).as("Wrong cipher: " + cipher).isFalse(); String decrypt = this.controller.decrypt("app", "default", cipher, MediaType.TEXT_PLAIN); - assertEquals("Wrong decrypted plaintext: " + decrypt, "foo bar", decrypt); + assertThat(decrypt).as("Wrong decrypted plaintext: " + decrypt) + .isEqualTo("foo bar"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionIntegrationTests.java index f8354d4c..6abf8746 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,7 @@ public class EncryptionIntegrationTests { @RunWith(SpringRunner.class) @SpringBootTest(classes = { - ConfigServerApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = "encrypt.key=foobar") + ConfigServerApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "encrypt.key=foobar") @ActiveProfiles({ "test", "native" }) @DirtiesContext public static class ConfigSymmetricEncryptionIntegrationTests { @@ -46,14 +45,16 @@ public class EncryptionIntegrationTests { @Test public void symmetricEncryptionEnabled() throws Exception { - ResponseEntity entity = testRestTemplate + ResponseEntity entity = this.testRestTemplate .getForEntity("/encrypt/status", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } + } @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class}, properties = "spring.cloud.bootstrap.name:symmetric-key-bootstrap", webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + @SpringBootTest(classes = { + ConfigServerApplication.class }, properties = "spring.cloud.bootstrap.name:symmetric-key-bootstrap", webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({ "test", "native" }) @DirtiesContext public static class BootstrapConfigSymmetricEncryptionIntegrationTests { @@ -63,16 +64,16 @@ public class EncryptionIntegrationTests { @Test public void symmetricEncryptionBootstrapConfig() throws Exception { - ResponseEntity entity = testRestTemplate + ResponseEntity entity = this.testRestTemplate .getForEntity("/encrypt/status", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } + } @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class}, - properties = "spring.cloud.bootstrap.name:keystore-bootstrap", - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + @SpringBootTest(classes = { + ConfigServerApplication.class }, properties = "spring.cloud.bootstrap.name:keystore-bootstrap", webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({ "test", "native" }) @DirtiesContext public static class KeystoreConfigurationIntegrationTests { @@ -82,10 +83,11 @@ public class EncryptionIntegrationTests { @Test public void keystoreBootstrapConfig() throws Exception { - ResponseEntity entity = testRestTemplate + ResponseEntity entity = this.testRestTemplate .getForEntity("/encrypt/status", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } + } -} \ No newline at end of file +} diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelperTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelperTests.java index b1b997e9..7ad799ce 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelperTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,13 @@ package org.springframework.cloud.config.server.encryption; -import static org.junit.Assert.assertEquals; - import java.util.Collections; import java.util.Map; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @@ -33,62 +33,66 @@ public class EnvironmentPrefixHelperTests { @Test public void testAddPrefix() { - assertEquals("{bar:spam}foo", - this.helper.addPrefix(Collections.singletonMap("bar", "spam"), "foo")); + assertThat(this.helper.addPrefix(Collections.singletonMap("bar", "spam"), "foo")) + .isEqualTo("{bar:spam}foo"); } @Test public void testAddNoPrefix() { - assertEquals("foo", - this.helper.addPrefix(Collections. emptyMap(), "foo")); + assertThat(this.helper.addPrefix(Collections.emptyMap(), "foo")) + .isEqualTo("foo"); } @Test public void testStripNoPrefix() { - assertEquals("foo", this.helper.stripPrefix("foo")); + assertThat(this.helper.stripPrefix("foo")).isEqualTo("foo"); } @Test public void testStripPrefix() { - assertEquals("foo", this.helper.stripPrefix("{key:foo}foo")); + assertThat(this.helper.stripPrefix("{key:foo}foo")).isEqualTo("foo"); } @Test public void testStripPrefixWithEscape() { - assertEquals("{key:foo}foo", this.helper.stripPrefix("{plain}{key:foo}foo")); + assertThat(this.helper.stripPrefix("{plain}{key:foo}foo")) + .isEqualTo("{key:foo}foo"); } @Test public void testKeysDefaults() { Map keys = this.helper.getEncryptorKeys("foo", "bar", "spam"); - assertEquals("foo", keys.get("name")); - assertEquals("bar", keys.get("profiles")); + assertThat(keys.get("name")).isEqualTo("foo"); + assertThat(keys.get("profiles")).isEqualTo("bar"); } @Test public void testKeysWithPrefix() { Map keys = this.helper.getEncryptorKeys("foo", "bar", "{key:mykey}foo"); - assertEquals(3, keys.size()); - assertEquals("mykey", keys.get("key")); + assertThat(keys.size()).isEqualTo(3); + assertThat(keys.get("key")).isEqualTo("mykey"); } @Test public void testKeysWithPrefixAndEscape() { Map keys = this.helper.getEncryptorKeys("foo", "bar", "{key:mykey}{plain}{foo:bar}foo"); - assertEquals(3, keys.size()); - assertEquals("mykey", keys.get("key")); + assertThat(keys.size()).isEqualTo(3); + assertThat(keys.get("key")).isEqualTo("mykey"); } @Test public void testTextWithCurlyBracesNoPrefix() { - assertEquals("textwith}brac{es", this.helper.stripPrefix("textwith}brac{es")); + assertThat(this.helper.stripPrefix("textwith}brac{es")) + .isEqualTo("textwith}brac{es"); } @Test public void testTextWithCurlyBracesPrefix() { - assertEquals("textwith}brac{es{and}prefix", this.helper - .stripPrefix("{key:foo}{name:bar}textwith}brac{es{and}prefix")); + assertThat( + this.helper.stripPrefix("{key:foo}{name:bar}textwith}brac{es{and}prefix")) + .isEqualTo("textwith}brac{es{and}prefix"); } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/KeyStoreTextEncryptorLocatorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/KeyStoreTextEncryptorLocatorTests.java index af06e411..9be8d116 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/KeyStoreTextEncryptorLocatorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/KeyStoreTextEncryptorLocatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,18 @@ package org.springframework.cloud.config.server.encryption; -import static org.junit.Assert.assertEquals; - import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.Test; + import org.springframework.core.io.ClassPathResource; import org.springframework.security.crypto.encrypt.TextEncryptor; import org.springframework.security.rsa.crypto.KeyStoreKeyFactory; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @@ -35,13 +36,14 @@ public class KeyStoreTextEncryptorLocatorTests { private KeyStoreTextEncryptorLocator locator = new KeyStoreTextEncryptorLocator( new KeyStoreKeyFactory(new ClassPathResource("server.jks"), - "letmein".toCharArray()), "changeme", "mytestkey"); + "letmein".toCharArray()), + "changeme", "mytestkey"); @Test public void testDefaults() { - TextEncryptor encryptor = this.locator.locate(Collections - . emptyMap()); - assertEquals("foo", encryptor.decrypt(encryptor.encrypt("foo"))); + TextEncryptor encryptor = this.locator + .locate(Collections.emptyMap()); + assertThat(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo"); } @Test @@ -50,14 +52,14 @@ public class KeyStoreTextEncryptorLocatorTests { @Override public char[] locate(String secret) { - assertEquals("changeme", secret); + assertThat(secret).isEqualTo("changeme"); // The actual secret for "mykey" is the same as the keystore password return "letmein".toCharArray(); } }); - TextEncryptor encryptor = this.locator.locate(Collections - . singletonMap("key", "mykey")); - assertEquals("foo", encryptor.decrypt(encryptor.encrypt("foo"))); + TextEncryptor encryptor = this.locator + .locate(Collections.singletonMap("key", "mykey")); + assertThat(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo"); } @Test @@ -66,7 +68,7 @@ public class KeyStoreTextEncryptorLocatorTests { map.put("key", "mytestkey"); map.put("secret", "changeme"); TextEncryptor encryptor = this.locator.locate(map); - assertEquals("foo", encryptor.decrypt(encryptor.encrypt("foo"))); + assertThat(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java index c455b62f..8fd78236 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.Test; + import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.environment.PropertySource; import org.springframework.cloud.config.server.config.CompositeConfiguration; @@ -29,7 +32,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.Ordered; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -38,34 +41,6 @@ import static org.mockito.Mockito.mock; */ public class CompositeEnvironmentRepositoryTests { - private static class TestOrderedEnvironmentRepository implements EnvironmentRepository, SearchPathLocator, Ordered { - - private Environment env; - private Locations locations; - private int order = Ordered.LOWEST_PRECEDENCE; - - public TestOrderedEnvironmentRepository(int order, Environment env, Locations locations) { - this.order = order; - this.env = env; - this.locations = locations; - } - - @Override - public Environment findOne(String application, String profile, String label) { - return env; - } - - @Override - public Locations getLocations(String application, String profile, String label) { - return locations; - } - - @Override - public int getOrder() { - return order; - } - } - @Test public void testOrder() { PropertySource p1 = mock(PropertySource.class); @@ -91,31 +66,36 @@ public class CompositeEnvironmentRepositoryTests { Environment e3 = new Environment("app", "dev"); e3.add(p3); e3.add(p4); - SearchPathLocator.Locations loc1 = new SearchPathLocator.Locations("app", "dev", "label", "version", new String[]{sLoc1}); - SearchPathLocator.Locations loc2 = new SearchPathLocator.Locations("app", "dev", "label", "version", new String[]{sLoc5, sLoc4}); - SearchPathLocator.Locations loc3 = new SearchPathLocator.Locations("app", "dev", "label", "version", new String[]{sLoc3, sLoc2}); + SearchPathLocator.Locations loc1 = new SearchPathLocator.Locations("app", "dev", + "label", "version", new String[] { sLoc1 }); + SearchPathLocator.Locations loc2 = new SearchPathLocator.Locations("app", "dev", + "label", "version", new String[] { sLoc5, sLoc4 }); + SearchPathLocator.Locations loc3 = new SearchPathLocator.Locations("app", "dev", + "label", "version", new String[] { sLoc3, sLoc2 }); List repos = new ArrayList(); repos.add(new TestOrderedEnvironmentRepository(3, e1, loc1)); repos.add(new TestOrderedEnvironmentRepository(2, e3, loc2)); repos.add(new TestOrderedEnvironmentRepository(1, e2, loc3)); - SearchPathCompositeEnvironmentRepository compositeRepo = new SearchPathCompositeEnvironmentRepository(repos); + SearchPathCompositeEnvironmentRepository compositeRepo = new SearchPathCompositeEnvironmentRepository( + repos); Environment compositeEnv = compositeRepo.findOne("foo", "bar", "world"); List propertySources = compositeEnv.getPropertySources(); - assertEquals(5, propertySources.size()); - assertEquals("p2", propertySources.get(0).getName()); - assertEquals("p3", propertySources.get(1).getName()); - assertEquals("p4", propertySources.get(2).getName()); - assertEquals("p1", propertySources.get(3).getName()); - assertEquals("p5", propertySources.get(4).getName()); + assertThat(propertySources.size()).isEqualTo(5); + assertThat(propertySources.get(0).getName()).isEqualTo("p2"); + assertThat(propertySources.get(1).getName()).isEqualTo("p3"); + assertThat(propertySources.get(2).getName()).isEqualTo("p4"); + assertThat(propertySources.get(3).getName()).isEqualTo("p1"); + assertThat(propertySources.get(4).getName()).isEqualTo("p5"); - SearchPathLocator.Locations locations = compositeRepo.getLocations("app", "dev", "label"); + SearchPathLocator.Locations locations = compositeRepo.getLocations("app", "dev", + "label"); String[] locationStrings = locations.getLocations(); - assertEquals(5, locationStrings.length); - assertEquals(sLoc3, locationStrings[0]); - assertEquals(sLoc2, locationStrings[1]); - assertEquals(sLoc5, locationStrings[2]); - assertEquals(sLoc4, locationStrings[3]); - assertEquals(sLoc1, locationStrings[4]); + assertThat(locationStrings.length).isEqualTo(5); + assertThat(locationStrings[0]).isEqualTo(sLoc3); + assertThat(locationStrings[1]).isEqualTo(sLoc2); + assertThat(locationStrings[2]).isEqualTo(sLoc5); + assertThat(locationStrings[3]).isEqualTo(sLoc4); + assertThat(locationStrings[4]).isEqualTo(sLoc1); } @Test @@ -134,38 +114,81 @@ public class CompositeEnvironmentRepositoryTests { e2.add(p2); e2.setVersion("2"); e2.setState("state2"); - SearchPathLocator.Locations loc1 = new SearchPathLocator.Locations("app", "dev", "label", "version", new String[]{sLoc1}); - SearchPathLocator.Locations loc2 = new SearchPathLocator.Locations("app", "dev", "label", "version", new String[]{sLoc1, sLoc2}); + SearchPathLocator.Locations loc1 = new SearchPathLocator.Locations("app", "dev", + "label", "version", new String[] { sLoc1 }); + SearchPathLocator.Locations loc2 = new SearchPathLocator.Locations("app", "dev", + "label", "version", new String[] { sLoc1, sLoc2 }); List repos = new ArrayList(); repos.add(new TestOrderedEnvironmentRepository(3, e1, loc1)); List repos2 = new ArrayList(); repos2.add(new TestOrderedEnvironmentRepository(3, e1, loc1)); repos2.add(new TestOrderedEnvironmentRepository(3, e2, loc2)); - SearchPathCompositeEnvironmentRepository compositeRepo = new SearchPathCompositeEnvironmentRepository(repos); - SearchPathCompositeEnvironmentRepository multiCompositeRepo = new SearchPathCompositeEnvironmentRepository(repos2); + SearchPathCompositeEnvironmentRepository compositeRepo = new SearchPathCompositeEnvironmentRepository( + repos); + SearchPathCompositeEnvironmentRepository multiCompositeRepo = new SearchPathCompositeEnvironmentRepository( + repos2); Environment env = compositeRepo.findOne("app", "dev", "label"); - assertEquals("1", env.getVersion()); - assertEquals("state", env.getState()); + assertThat(env.getVersion()).isEqualTo("1"); + assertThat(env.getState()).isEqualTo("state"); Environment multiEnv = multiCompositeRepo.findOne("app", "dev", "label"); - assertEquals(null, multiEnv.getVersion()); - assertEquals(null, multiEnv.getState()); + assertThat(multiEnv.getVersion()).isEqualTo(null); + assertThat(multiEnv.getState()).isEqualTo(null); } @Test public void overridingCompositeEnvRepo_contextLoads() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { - context.register(OverrideCompositeConfig.class, CompositeConfiguration.class, ConfigServerHealthIndicator.class); + context.register(OverrideCompositeConfig.class, CompositeConfiguration.class, + ConfigServerHealthIndicator.class); context.refresh(); } } + private static class TestOrderedEnvironmentRepository + implements EnvironmentRepository, SearchPathLocator, Ordered { + + private Environment env; + + private Locations locations; + + private int order = Ordered.LOWEST_PRECEDENCE; + + TestOrderedEnvironmentRepository(int order, Environment env, + Locations locations) { + this.order = order; + this.env = env; + this.locations = locations; + } + + @Override + public Environment findOne(String application, String profile, String label) { + return this.env; + } + + @Override + public Locations getLocations(String application, String profile, String label) { + return this.locations; + } + + @Override + public int getOrder() { + return this.order; + } + + } + @Configuration static class OverrideCompositeConfig { + @Bean @Primary CompositeEnvironmentRepository customCompositeEnvironmentRepository() { - return new CompositeEnvironmentRepository(Arrays.asList(new TestOrderedEnvironmentRepository(1, new Environment("app", "dev"), null))); + return new CompositeEnvironmentRepository(Arrays + .asList(new TestOrderedEnvironmentRepository(1, + new Environment("app", "dev"), null))); } + } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactoryIntegrationTests.java index aa9dbdff..7bcd7c03 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.IOException; @@ -60,231 +61,236 @@ import static org.hamcrest.Matchers.instanceOf; * @author Dylan Roberts */ public class ConfigurableHttpConnectionFactoryIntegrationTests { - private static final ProxyHostProperties AUTHENTICATED_HTTP_PROXY = new ProxyHostProperties(); - static { - AUTHENTICATED_HTTP_PROXY.setHost("http://authenticated.http.proxy"); - AUTHENTICATED_HTTP_PROXY.setPort(8080); - AUTHENTICATED_HTTP_PROXY.setUsername("username"); - AUTHENTICATED_HTTP_PROXY.setPassword("password"); - } - private static final ProxyHostProperties AUTHENTICATED_HTTPS_PROXY = new ProxyHostProperties(); - static { - AUTHENTICATED_HTTPS_PROXY.setHost("http://authenticated.https.proxy"); - AUTHENTICATED_HTTPS_PROXY.setPort(8081); - AUTHENTICATED_HTTPS_PROXY.setUsername("username2"); - AUTHENTICATED_HTTPS_PROXY.setPassword("password2"); - } - private static final ProxyHostProperties HTTP_PROXY = new ProxyHostProperties(); - static { - HTTP_PROXY.setHost("http://http.proxy"); - HTTP_PROXY.setPort(8080); - } - private static final ProxyHostProperties HTTPS_PROXY = new ProxyHostProperties(); - static { - HTTPS_PROXY.setHost("http://https.proxy"); - HTTPS_PROXY.setPort(8081); - } - @Rule - public ExpectedException expectedException = ExpectedException.none(); + private static final ProxyHostProperties AUTHENTICATED_HTTP_PROXY = new ProxyHostProperties(); - @Test - public void authenticatedHttpsProxy() throws Exception { - String repoUrl = "https://myrepo/repo.git"; - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, null, AUTHENTICATED_HTTPS_PROXY)) - .run(); - HttpClient httpClient = getHttpClientForUrl(repoUrl); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(AUTHENTICATED_HTTPS_PROXY.getHost())))); + private static final ProxyHostProperties AUTHENTICATED_HTTPS_PROXY = new ProxyHostProperties(); - makeRequest(httpClient, "https://somehost"); - } + private static final ProxyHostProperties HTTP_PROXY = new ProxyHostProperties(); - @Test - public void httpsProxy() throws Exception { - String repoUrl = "https://myrepo/repo.git"; - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, null, HTTPS_PROXY)) - .run(); - HttpClient httpClient = getHttpClientForUrl(repoUrl); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(HTTPS_PROXY.getHost())))); + private static final ProxyHostProperties HTTPS_PROXY = new ProxyHostProperties(); - makeRequest(httpClient, "https://somehost"); - } + static { + AUTHENTICATED_HTTP_PROXY.setHost("http://authenticated.http.proxy"); + AUTHENTICATED_HTTP_PROXY.setPort(8080); + AUTHENTICATED_HTTP_PROXY.setUsername("username"); + AUTHENTICATED_HTTP_PROXY.setPassword("password"); + } - @Test - public void httpsProxy_placeholderUrl() throws Exception { - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(gitProperties("https://myrepo/{placeholder1}/{placeholder2}-repo.git", null, HTTPS_PROXY)) - .run(); - HttpClient httpClient = getHttpClientForUrl("https://myrepo/someplaceholdervalue/anotherplaceholdervalue-repo.git"); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(HTTPS_PROXY.getHost())))); + static { + AUTHENTICATED_HTTPS_PROXY.setHost("http://authenticated.https.proxy"); + AUTHENTICATED_HTTPS_PROXY.setPort(8081); + AUTHENTICATED_HTTPS_PROXY.setUsername("username2"); + AUTHENTICATED_HTTPS_PROXY.setPassword("password2"); + } - makeRequest(httpClient, "https://somehost"); - } + static { + HTTP_PROXY.setHost("http://http.proxy"); + HTTP_PROXY.setPort(8080); + } - @Test - public void httpsProxy_notCalled() throws Exception { - String repoUrl = "https://myrepo/repo.git"; - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, null, HTTPS_PROXY)) - .run(); - HttpClient httpClient = getHttpClientForUrl(repoUrl); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString("somehost")))); + static { + HTTPS_PROXY.setHost("http://https.proxy"); + HTTPS_PROXY.setPort(8081); + } - makeRequest(httpClient, "http://somehost"); - } + @Rule + public ExpectedException expectedException = ExpectedException.none(); - @Test - public void authenticatedHttpProxy() throws Exception { - String repoUrl = "https://myrepo/repo.git"; - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, AUTHENTICATED_HTTP_PROXY, null)) - .run(); - HttpClient httpClient = getHttpClientForUrl(repoUrl); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(AUTHENTICATED_HTTP_PROXY.getHost())))); + @Test + public void authenticatedHttpsProxy() throws Exception { + String repoUrl = "https://myrepo/repo.git"; + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .properties(gitProperties(repoUrl, null, AUTHENTICATED_HTTPS_PROXY)) + .run(); + HttpClient httpClient = getHttpClientForUrl(repoUrl); + this.expectedException.expectCause( + allOf(instanceOf(UnknownHostException.class), hasProperty("message", + containsString(AUTHENTICATED_HTTPS_PROXY.getHost())))); - makeRequest(httpClient, "http://somehost"); - } + makeRequest(httpClient, "https://somehost"); + } - @Test - public void httpProxy() throws Exception { - String repoUrl = "https://myrepo/repo.git"; - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, HTTP_PROXY, null)) - .run(); - HttpClient httpClient = getHttpClientForUrl(repoUrl); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(HTTP_PROXY.getHost())))); + @Test + public void httpsProxy() throws Exception { + String repoUrl = "https://myrepo/repo.git"; + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .properties(gitProperties(repoUrl, null, HTTPS_PROXY)).run(); + HttpClient httpClient = getHttpClientForUrl(repoUrl); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString(HTTPS_PROXY.getHost())))); - makeRequest(httpClient, "http://somehost"); - } + makeRequest(httpClient, "https://somehost"); + } - @Test - public void httpProxy_placeholderUrl() throws Exception { - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(gitProperties("https://myrepo/{placeholder}-repo.git", HTTP_PROXY, null)) - .run(); - HttpClient httpClient = getHttpClientForUrl("https://myrepo/someplaceholdervalue-repo.git"); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(HTTP_PROXY.getHost())))); + @Test + public void httpsProxy_placeholderUrl() throws Exception { + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .properties(gitProperties( + "https://myrepo/{placeholder1}/{placeholder2}-repo.git", null, + HTTPS_PROXY)) + .run(); + HttpClient httpClient = getHttpClientForUrl( + "https://myrepo/someplaceholdervalue/anotherplaceholdervalue-repo.git"); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString(HTTPS_PROXY.getHost())))); - makeRequest(httpClient, "http://somehost"); - } + makeRequest(httpClient, "https://somehost"); + } - @Test - public void httpProxy_notCalled() throws Exception { - String repoUrl = "https://myrepo/repo.git"; - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, HTTP_PROXY, null)) - .run(); - HttpClient httpClient = getHttpClientForUrl(repoUrl); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString("somehost")))); + @Test + public void httpsProxy_notCalled() throws Exception { + String repoUrl = "https://myrepo/repo.git"; + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .properties(gitProperties(repoUrl, null, HTTPS_PROXY)).run(); + HttpClient httpClient = getHttpClientForUrl(repoUrl); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString("somehost")))); - makeRequest(httpClient, "https://somehost"); - } + makeRequest(httpClient, "http://somehost"); + } - @Test - public void httpProxy_fromSystemProperty() throws Exception { - ProxySelector defaultProxySelector = ProxySelector.getDefault(); - try { - ProxySelector.setDefault(new ProxySelector() { - @Override - public List select(URI uri) { - InetSocketAddress address = new InetSocketAddress(HTTP_PROXY.getHost(), HTTP_PROXY.getPort()); - Proxy proxy = new Proxy(Proxy.Type.HTTP, address); - return Collections.singletonList(proxy); - } + @Test + public void authenticatedHttpProxy() throws Exception { + String repoUrl = "https://myrepo/repo.git"; + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .properties(gitProperties(repoUrl, AUTHENTICATED_HTTP_PROXY, null)).run(); + HttpClient httpClient = getHttpClientForUrl(repoUrl); + this.expectedException.expectCause( + allOf(instanceOf(UnknownHostException.class), hasProperty("message", + containsString(AUTHENTICATED_HTTP_PROXY.getHost())))); - @Override - public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { + makeRequest(httpClient, "http://somehost"); + } - } - }); - String repoUrl = "https://myrepo/repo.git"; - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE) - .properties(new String[] {"spring.cloud.config.server.git.uri=" + repoUrl}) - .run(); - HttpClient httpClient = getHttpClientForUrl(repoUrl); - expectedException.expectCause(allOf( - instanceOf(UnknownHostException.class), - hasProperty("message", containsString(HTTP_PROXY.getHost())))); + @Test + public void httpProxy() throws Exception { + String repoUrl = "https://myrepo/repo.git"; + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .properties(gitProperties(repoUrl, HTTP_PROXY, null)).run(); + HttpClient httpClient = getHttpClientForUrl(repoUrl); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString(HTTP_PROXY.getHost())))); - makeRequest(httpClient, "http://somehost"); - } finally { - ProxySelector.setDefault(defaultProxySelector); - } - } + makeRequest(httpClient, "http://somehost"); + } - private String[] gitProperties(String repoUrl, ProxyHostProperties httpProxy, ProxyHostProperties httpsProxy) { - List result = new ArrayList<>(); - result.add("spring.cloud.config.server.git.uri=" + repoUrl); - if (httpProxy != null) { - result.addAll(Arrays.asList( - "spring.cloud.config.server.git.proxy.http.host=" + httpProxy.getHost(), - "spring.cloud.config.server.git.proxy.http.port=" + httpProxy.getPort() - )); - if (httpProxy.getUsername() != null && httpProxy.getPassword() != null) { - result.addAll(Arrays.asList( - "spring.cloud.config.server.git.proxy.http.username=" + httpProxy.getUsername(), - "spring.cloud.config.server.git.proxy.http.password=" + httpProxy.getPassword() - )); - } - } - if (httpsProxy != null) { - result.addAll(Arrays.asList( - "spring.cloud.config.server.git.proxy.https.host=" + httpsProxy.getHost(), - "spring.cloud.config.server.git.proxy.https.port=" + httpsProxy.getPort() - )); - if (httpsProxy.getUsername() != null && httpsProxy.getPassword() != null) { - result.addAll(Arrays.asList( - "spring.cloud.config.server.git.proxy.https.username=" + httpsProxy.getUsername(), - "spring.cloud.config.server.git.proxy.https.password=" + httpsProxy.getPassword() - )); - } - } - return result.toArray(new String[0]); - } + @Test + public void httpProxy_placeholderUrl() throws Exception { + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .properties(gitProperties("https://myrepo/{placeholder}-repo.git", + HTTP_PROXY, null)) + .run(); + HttpClient httpClient = getHttpClientForUrl( + "https://myrepo/someplaceholdervalue-repo.git"); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString(HTTP_PROXY.getHost())))); - private void makeRequest(HttpClient httpClient, String url) { - RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); - restTemplate.getForObject(url, String.class); - } + makeRequest(httpClient, "http://somehost"); + } - private HttpClient getHttpClientForUrl(String repoUrl) throws IOException { - HttpConnectionFactory connectionFactory = HttpTransport.getConnectionFactory(); - URL url = new URL(repoUrl); - HttpConnection httpConnection = connectionFactory.create(url); - assertThat(httpConnection).isInstanceOf(HttpClientConnection.class); - return (HttpClient) ReflectionTestUtils.getField(httpConnection, "client"); - } + @Test + public void httpProxy_notCalled() throws Exception { + String repoUrl = "https://myrepo/repo.git"; + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .properties(gitProperties(repoUrl, HTTP_PROXY, null)).run(); + HttpClient httpClient = getHttpClientForUrl(repoUrl); + this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), + hasProperty("message", containsString("somehost")))); + + makeRequest(httpClient, "https://somehost"); + } + + @Test + public void httpProxy_fromSystemProperty() throws Exception { + ProxySelector defaultProxySelector = ProxySelector.getDefault(); + try { + ProxySelector.setDefault(new ProxySelector() { + @Override + public List select(URI uri) { + InetSocketAddress address = new InetSocketAddress( + HTTP_PROXY.getHost(), HTTP_PROXY.getPort()); + Proxy proxy = new Proxy(Proxy.Type.HTTP, address); + return Collections.singletonList(proxy); + } + + @Override + public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { + + } + }); + String repoUrl = "https://myrepo/repo.git"; + new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE).properties(new String[] { + "spring.cloud.config.server.git.uri=" + repoUrl }) + .run(); + HttpClient httpClient = getHttpClientForUrl(repoUrl); + this.expectedException.expectCause(allOf( + instanceOf(UnknownHostException.class), + hasProperty("message", containsString(HTTP_PROXY.getHost())))); + + makeRequest(httpClient, "http://somehost"); + } + finally { + ProxySelector.setDefault(defaultProxySelector); + } + } + + private String[] gitProperties(String repoUrl, ProxyHostProperties httpProxy, + ProxyHostProperties httpsProxy) { + List result = new ArrayList<>(); + result.add("spring.cloud.config.server.git.uri=" + repoUrl); + if (httpProxy != null) { + result.addAll(Arrays.asList( + "spring.cloud.config.server.git.proxy.http.host=" + + httpProxy.getHost(), + "spring.cloud.config.server.git.proxy.http.port=" + + httpProxy.getPort())); + if (httpProxy.getUsername() != null && httpProxy.getPassword() != null) { + result.addAll(Arrays.asList( + "spring.cloud.config.server.git.proxy.http.username=" + + httpProxy.getUsername(), + "spring.cloud.config.server.git.proxy.http.password=" + + httpProxy.getPassword())); + } + } + if (httpsProxy != null) { + result.addAll(Arrays.asList( + "spring.cloud.config.server.git.proxy.https.host=" + + httpsProxy.getHost(), + "spring.cloud.config.server.git.proxy.https.port=" + + httpsProxy.getPort())); + if (httpsProxy.getUsername() != null && httpsProxy.getPassword() != null) { + result.addAll(Arrays.asList( + "spring.cloud.config.server.git.proxy.https.username=" + + httpsProxy.getUsername(), + "spring.cloud.config.server.git.proxy.https.password=" + + httpsProxy.getPassword())); + } + } + return result.toArray(new String[0]); + } + + private void makeRequest(HttpClient httpClient, String url) { + RestTemplate restTemplate = new RestTemplate( + new HttpComponentsClientHttpRequestFactory(httpClient)); + restTemplate.getForObject(url, String.class); + } + + private HttpClient getHttpClientForUrl(String repoUrl) throws IOException { + HttpConnectionFactory connectionFactory = HttpTransport.getConnectionFactory(); + URL url = new URL(repoUrl); + HttpConnection httpConnection = connectionFactory.create(url); + assertThat(httpConnection).isInstanceOf(HttpClientConnection.class); + return (HttpClient) ReflectionTestUtils.getField(httpConnection, "client"); + } + + @Configuration + @EnableConfigurationProperties(ConfigServerProperties.class) + @Import({ PropertyPlaceholderAutoConfiguration.class, + EnvironmentRepositoryConfiguration.class }) + protected static class TestConfiguration { + + } - @Configuration - @EnableConfigurationProperties(ConfigServerProperties.class) - @Import({ PropertyPlaceholderAutoConfiguration.class, EnvironmentRepositoryConfiguration.class }) - protected static class TestConfiguration { - } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryTests.java index 6a698f50..662c424d 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.HashMap; @@ -49,25 +50,29 @@ public class CredhubEnvironmentRepositoryTests { @Before public void setUp() { CredHubOperations credhubOperations = Mockito.mock(CredHubOperations.class); - credhubCredentialOperations = Mockito.mock(CredHubCredentialOperations.class); - when(credhubOperations.credentials()).thenReturn(credhubCredentialOperations); + this.credhubCredentialOperations = Mockito + .mock(CredHubCredentialOperations.class); + when(credhubOperations.credentials()) + .thenReturn(this.credhubCredentialOperations); - credhubEnvironmentRepository = new CredhubEnvironmentRepository(credhubOperations); + this.credhubEnvironmentRepository = new CredhubEnvironmentRepository( + credhubOperations); } @Test public void shouldDisplayEmptyPropertiesWhenNoPathFound() { - when(credhubCredentialOperations + when(this.credhubCredentialOperations .findByPath("/my-application/production/mylabel")) - .thenReturn(emptyList()); + .thenReturn(emptyList()); - Environment environment = - credhubEnvironmentRepository.findOne("my-application", "production", "mylabel"); + Environment environment = this.credhubEnvironmentRepository + .findOne("my-application", "production", "mylabel"); assertThat(environment.getLabel()).isEqualTo("mylabel"); assertThat(environment.getProfiles()).containsExactly("production"); assertThat(environment.getName()).isEqualTo("my-application"); - assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("credhub-my-application"); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("credhub-my-application"); assertThat(environment.getPropertySources().get(0).getSource()).isEmpty(); } @@ -75,95 +80,110 @@ public class CredhubEnvironmentRepositoryTests { public void shouldRetrieveDefaultsWhenNoLabelNorProfileProvided() { stubCredentials("/my-application/default/master", "toggles", "key1", "value1"); - Environment environment = - credhubEnvironmentRepository.findOne("my-application", null, null); + Environment environment = this.credhubEnvironmentRepository + .findOne("my-application", null, null); assertThat(environment.getLabel()).isEqualTo("master"); assertThat(environment.getProfiles()).containsExactly("default"); assertThat(environment.getName()).isEqualTo("my-application"); - assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("credhub-my-application"); - assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(singletonMap("key1", "value1")); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("credhub-my-application"); + assertThat(environment.getPropertySources().get(0).getSource()) + .isEqualTo(singletonMap("key1", "value1")); } @Test public void shouldRetrieveGivenProfileAndLabel() { - stubCredentials("/my-application/production/mylabel", "toggles", "key1", "value1"); + stubCredentials("/my-application/production/mylabel", "toggles", "key1", + "value1"); - Environment environment = - credhubEnvironmentRepository.findOne("my-application", "production", "mylabel"); + Environment environment = this.credhubEnvironmentRepository + .findOne("my-application", "production", "mylabel"); assertThat(environment.getLabel()).isEqualTo("mylabel"); assertThat(environment.getProfiles()).containsExactly("production"); assertThat(environment.getName()).isEqualTo("my-application"); - assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("credhub-my-application"); - assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(singletonMap("key1", "value1")); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("credhub-my-application"); + assertThat(environment.getPropertySources().get(0).getSource()) + .isEqualTo(singletonMap("key1", "value1")); } @Test public void shouldRetrieveGivenMultipleProfiles() { - stubCredentials("/my-application/production/mylabel", "toggles", "key1", "value1"); + stubCredentials("/my-application/production/mylabel", "toggles", "key1", + "value1"); stubCredentials("/my-application/cloud/mylabel", "abs", "key2", "value2"); - Environment environment = - credhubEnvironmentRepository.findOne("my-application", "production,cloud", "mylabel"); + Environment environment = this.credhubEnvironmentRepository + .findOne("my-application", "production,cloud", "mylabel"); assertThat(environment.getLabel()).isEqualTo("mylabel"); assertThat(environment.getProfiles()).containsExactly("production", "cloud"); assertThat(environment.getName()).isEqualTo("my-application"); - assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("credhub-my-application"); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("credhub-my-application"); HashMap expectedValues = new HashMap<>(); expectedValues.put("key1", "value1"); expectedValues.put("key2", "value2"); - assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(expectedValues); + assertThat(environment.getPropertySources().get(0).getSource()) + .isEqualTo(expectedValues); } @Test public void shouldMergeWhenMoreThanOneCredentialsFound() { String expectedPath = "/my-application/production/mylabel"; - SimpleCredentialName togglesCredentialName = new SimpleCredentialName(expectedPath + "/toggles"); - SimpleCredentialName absCredentialName = new SimpleCredentialName(expectedPath + "/abs"); - when(credhubCredentialOperations - .findByPath(expectedPath)) - .thenReturn(asList( - new CredentialSummary(togglesCredentialName), + SimpleCredentialName togglesCredentialName = new SimpleCredentialName( + expectedPath + "/toggles"); + SimpleCredentialName absCredentialName = new SimpleCredentialName( + expectedPath + "/abs"); + when(this.credhubCredentialOperations.findByPath(expectedPath)) + .thenReturn(asList(new CredentialSummary(togglesCredentialName), new CredentialSummary(absCredentialName))); JsonCredential credentials = new JsonCredential(); credentials.put("key1", "value1"); - when(credhubCredentialOperations - .getByName(togglesCredentialName, JsonCredential.class)) - .thenReturn(new CredentialDetails<>("id1", togglesCredentialName, CredentialType.JSON, credentials)); + when(this.credhubCredentialOperations.getByName(togglesCredentialName, + JsonCredential.class)) + .thenReturn(new CredentialDetails<>("id1", togglesCredentialName, + CredentialType.JSON, credentials)); JsonCredential otherCredentials = new JsonCredential(); otherCredentials.put("key2", "value2"); - when(credhubCredentialOperations - .getByName(absCredentialName, JsonCredential.class)) - .thenReturn(new CredentialDetails<>("id2", absCredentialName, CredentialType.JSON, otherCredentials)); + when(this.credhubCredentialOperations.getByName(absCredentialName, + JsonCredential.class)) + .thenReturn(new CredentialDetails<>("id2", absCredentialName, + CredentialType.JSON, otherCredentials)); - Environment environment = - credhubEnvironmentRepository.findOne("my-application", "production", "mylabel"); + Environment environment = this.credhubEnvironmentRepository + .findOne("my-application", "production", "mylabel"); assertThat(environment.getLabel()).isEqualTo("mylabel"); assertThat(environment.getProfiles()).containsExactly("production"); assertThat(environment.getName()).isEqualTo("my-application"); - assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("credhub-my-application"); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo("credhub-my-application"); HashMap expectedValues = new HashMap<>(); expectedValues.put("key1", "value1"); expectedValues.put("key2", "value2"); - assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(expectedValues); + assertThat(environment.getPropertySources().get(0).getSource()) + .isEqualTo(expectedValues); } - private void stubCredentials(String expectedPath, String name, String key, String value) { - SimpleCredentialName credentialsName = new SimpleCredentialName(expectedPath + "/" + name); - when(credhubCredentialOperations - .findByPath(expectedPath)) + private void stubCredentials(String expectedPath, String name, String key, + String value) { + SimpleCredentialName credentialsName = new SimpleCredentialName( + expectedPath + "/" + name); + when(this.credhubCredentialOperations.findByPath(expectedPath)) .thenReturn(singletonList(new CredentialSummary(credentialsName))); JsonCredential credentials = new JsonCredential(); credentials.put(key, value); - when(credhubCredentialOperations - .getByName(new SimpleCredentialName(expectedPath + "/" + name), JsonCredential.class)) - .thenReturn(new CredentialDetails<>("id1", credentialsName, CredentialType.JSON, credentials)); + when(this.credhubCredentialOperations.getByName( + new SimpleCredentialName(expectedPath + "/" + name), + JsonCredential.class)) + .thenReturn(new CredentialDetails<>("id1", credentialsName, + CredentialType.JSON, credentials)); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerIntegrationTests.java index 0f3c01bc..83e0623c 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,13 @@ package org.springframework.cloud.config.server.environment; import java.util.HashMap; + import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -50,29 +52,34 @@ public class EnvironmentControllerIntegrationTests { @Autowired private WebApplicationContext context; + private MockMvc mvc; + @Autowired private EnvironmentRepository repository; - + private Environment environment = new Environment("foo", "default"); @Before public void init() { Mockito.reset(this.repository); this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - environment.add(new PropertySource("foo", new HashMap<>())); + this.environment.add(new PropertySource("foo", new HashMap<>())); } @Test public void environmentNoLabel() throws Exception { - Mockito.when(this.repository.findOne("foo", "default", null)).thenReturn(this.environment); - this.mvc.perform(MockMvcRequestBuilders.get("/foo/default")).andExpect(MockMvcResultMatchers.status().isOk()); + Mockito.when(this.repository.findOne("foo", "default", null)) + .thenReturn(this.environment); + this.mvc.perform(MockMvcRequestBuilders.get("/foo/default")) + .andExpect(MockMvcResultMatchers.status().isOk()); Mockito.verify(this.repository).findOne("foo", "default", null); } @Test public void propertiesNoLabel() throws Exception { - Mockito.when(this.repository.findOne("foo", "default", null)).thenReturn(this.environment); + Mockito.when(this.repository.findOne("foo", "default", null)) + .thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo-default.properties")) .andExpect(MockMvcResultMatchers.status().isOk()); Mockito.verify(this.repository).findOne("foo", "default", null); @@ -80,7 +87,8 @@ public class EnvironmentControllerIntegrationTests { @Test public void propertiesLabel() throws Exception { - Mockito.when(this.repository.findOne("foo", "default", "label")).thenReturn(this.environment); + Mockito.when(this.repository.findOne("foo", "default", "label")) + .thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/label/foo-default.properties")) .andExpect(MockMvcResultMatchers.status().isOk()); Mockito.verify(this.repository).findOne("foo", "default", "label"); @@ -99,10 +107,11 @@ public class EnvironmentControllerIntegrationTests { @Test public void propertiesLabelWithSlash() throws Exception { - + Mockito.when(this.repository.findOne("foo", "default", "label/spam")) .thenReturn(this.environment); - this.mvc.perform(MockMvcRequestBuilders.get("/label(_)spam/foo-default.properties")) + this.mvc.perform( + MockMvcRequestBuilders.get("/label(_)spam/foo-default.properties")) .andExpect(MockMvcResultMatchers.status().isOk()); Mockito.verify(this.repository).findOne("foo", "default", "label/spam"); } @@ -133,7 +142,8 @@ public class EnvironmentControllerIntegrationTests { @Test public void environmentWithLabelContainingPeriod() throws Exception { - Mockito.when(this.repository.findOne("foo", "default", "1.0.0")).thenReturn(this.environment); + Mockito.when(this.repository.findOne("foo", "default", "1.0.0")) + .thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/1.0.0")) .andExpect(MockMvcResultMatchers.status().isOk()); } @@ -144,7 +154,8 @@ public class EnvironmentControllerIntegrationTests { .thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/feature(_)puff")) .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("\"propertySources\":"))); + .andExpect(MockMvcResultMatchers.content() + .string(Matchers.containsString("\"propertySources\":"))); } @Test @@ -155,7 +166,8 @@ public class EnvironmentControllerIntegrationTests { .thenReturn(environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo(_)app/default")) .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("\"propertySources\":"))); + .andExpect(MockMvcResultMatchers.content() + .string(Matchers.containsString("\"propertySources\":"))); } @Configuration diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerTests.java index d6c8cbbe..a5421469 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.Collections; @@ -35,14 +36,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -65,7 +59,7 @@ public class EnvironmentControllerTests { @Before public void init() { this.controller = new EnvironmentController(this.repository); - environment.add(new PropertySource("foo", new HashMap<>())); + this.environment.add(new PropertySource("foo", new HashMap<>())); } @After @@ -81,7 +75,7 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("a:\n b:\n c: d\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n c: d\n"); } @Test @@ -94,7 +88,7 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("a:\n b:\n c: e\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n c: e\n"); } @Test @@ -111,28 +105,28 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("A: Z\nS: 3\nY: 0\n", yaml); + assertThat(yaml).isEqualTo("A: Z\nS: 3\nY: 0\n"); } @Test public void placeholdersResolvedInYaml() throws Exception { whenPlaceholders(); String yaml = this.controller.yaml("foo", "bar", true).getBody(); - assertEquals("a:\n b:\n c: bar\nfoo: bar\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n c: bar\nfoo: bar\n"); } @Test public void placeholdersNotResolvedInYaml() throws Exception { whenPlaceholders(); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("a:\n b:\n c: ${foo}\nfoo: bar\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n c: ${foo}\nfoo: bar\n"); } @Test public void placeholdersNotResolvedInYamlFromSystemProperties() throws Exception { whenPlaceholdersSystemProps(); String yaml = this.controller.yaml("foo", "bar", true).getBody(); - assertEquals("a:\n b:\n c: ${foo}\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n c: ${foo}\n"); } @Test @@ -140,7 +134,7 @@ public class EnvironmentControllerTests { throws Exception { whenPlaceholdersSystemProps(); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("a:\n b:\n c: ${foo}\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n c: ${foo}\n"); } @Test @@ -149,7 +143,7 @@ public class EnvironmentControllerTests { whenPlaceholdersSystemPropsWithDefault(); String yaml = this.controller.yaml("foo", "bar", false).getBody(); // If there is a default value we prevent the placeholder being resolved - assertEquals("a:\n b:\n c: ${foo:spam}\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n c: ${foo:spam}\n"); } @Test @@ -158,7 +152,7 @@ public class EnvironmentControllerTests { whenPlaceholdersSystemPropsWithDefault(); String yaml = this.controller.yaml("foo", "bar", true).getBody(); // If there is a default value we do not prevent the placeholder being resolved - assertEquals("a:\n b:\n c: spam\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n c: spam\n"); } @Test @@ -170,7 +164,7 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("a:\n b:\n - c\n - d\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n - c\n - d\n"); } @Test @@ -191,52 +185,59 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", "two")) .thenReturn(this.environment); Environment environment = this.controller.labelled("foo", "bar", "two"); - assertThat(environment, not(nullValue())); - assertThat(environment.getName(), equalTo("foo")); - assertThat(environment.getProfiles(), equalTo(new String[] { "master" })); - assertThat(environment.getLabel(), equalTo("master")); - assertThat(environment.getVersion(), nullValue()); - assertThat(environment.getPropertySources(), hasSize(3)); - assertThat(environment.getPropertySources().get(0).getName(), equalTo("two")); - assertThat(environment.getPropertySources().get(0).getSource().entrySet(), - hasSize(2)); - assertThat(environment.getPropertySources().get(2).getName(), equalTo("one")); - assertThat(environment.getPropertySources().get(2).getSource().entrySet(), - hasSize(3)); + assertThat(environment).isNotNull(); + assertThat(environment.getName()).isEqualTo("foo"); + assertThat(environment.getProfiles()).isEqualTo(new String[] { "master" }); + assertThat(environment.getLabel()).isEqualTo("master"); + assertThat(environment.getVersion()).isNull(); + assertThat(environment.getPropertySources()).hasSize(3); + assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("two"); + assertThat(environment.getPropertySources().get(0).getSource().entrySet()) + .hasSize(2); + assertThat(environment.getPropertySources().get(2).getName()).isEqualTo("one"); + assertThat(environment.getPropertySources().get(2).getSource().entrySet()) + .hasSize(3); } - + @Test public void testNameWithSlash() { - Mockito.when(this.repository.findOne("foo/spam", "bar", "two")).thenReturn(this.environment); + Mockito.when(this.repository.findOne("foo/spam", "bar", "two")) + .thenReturn(this.environment); - Environment returnedEnvironment = this.controller.labelled("foo(_)spam", "bar", "two"); + Environment returnedEnvironment = this.controller.labelled("foo(_)spam", "bar", + "two"); - assertEquals(this.environment.getLabel(), returnedEnvironment.getLabel()); - assertEquals(this.environment.getName(), returnedEnvironment.getName()); + assertThat(returnedEnvironment.getLabel()).isEqualTo(this.environment.getLabel()); + assertThat(returnedEnvironment.getName()).isEqualTo(this.environment.getName()); } - @Test(expected=EnvironmentNotFoundException.class) + + @Test(expected = EnvironmentNotFoundException.class) public void testEnvironmentNotFound() { this.controller.setAcceptEmpty(false); this.controller.labelled("foo", "bar", null); } + @Test public void testwithValidEnvironment() { - Mockito.when(this.repository.findOne("foo", "bar",null)) + Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); Environment environment = this.controller.labelled("foo", "bar", null); - assertThat(environment, not(nullValue())); + assertThat(environment).isNotNull(); } + @Test public void testLabelWithSlash() { - - Mockito.when(this.repository.findOne("foo", "bar", "two/spam")).thenReturn(this.environment); - Environment returnedEnvironment = this.controller.labelled("foo", "bar", "two(_)spam"); + Mockito.when(this.repository.findOne("foo", "bar", "two/spam")) + .thenReturn(this.environment); - assertEquals(this.environment.getLabel(), returnedEnvironment.getLabel()); - assertEquals(this.environment.getName(), returnedEnvironment.getName()); + Environment returnedEnvironment = this.controller.labelled("foo", "bar", + "two(_)spam"); + + assertThat(returnedEnvironment.getLabel()).isEqualTo(this.environment.getLabel()); + assertThat(returnedEnvironment.getName()).isEqualTo(this.environment.getName()); } @Test @@ -259,7 +260,7 @@ public class EnvironmentControllerTests { String yaml = this.controller.yaml("foo", "bar", false).getBody(); // Result will not contain original, extra values from oneMap - assertEquals("a:\n b:\n - f\n - h\n", yaml); + assertThat(yaml).isEqualTo("a:\n b:\n - f\n - h\n"); } @Test @@ -270,7 +271,7 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("blah\n", yaml); + assertThat(yaml).isEqualTo("blah\n"); } @Test @@ -282,7 +283,7 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("- c\n- d\n", yaml); + assertThat(yaml).isEqualTo("- c\n- d\n"); } @Test @@ -294,7 +295,7 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("- a: c\n- a: d\n", yaml); + assertThat(yaml).isEqualTo("- a: c\n- a: d\n"); } @Test @@ -307,9 +308,9 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertTrue("Wrong output: " + yaml, - "a:\n b:\n - d: e\n c: d\n - c: d\n".equals(yaml) - || "a:\n b:\n - c: d\n d: e\n - c: d\n".equals(yaml)); + assertThat("a:\n b:\n - d: e\n c: d\n - c: d\n".equals(yaml) + || "a:\n b:\n - c: d\n d: e\n - c: d\n".equals(yaml)) + .as("Wrong output: " + yaml).isTrue(); } @Test @@ -341,7 +342,7 @@ public class EnvironmentControllerTests { " - - r\n" + " - s\n"; // @formatter:on - assertThat("Wrong output: " + yaml, yaml, is(expected)); + assertThat(yaml).as("Wrong output: " + yaml).isEqualTo(expected); } @Test @@ -356,8 +357,8 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String json = this.controller.jsonProperties("foo", "bar", false).getBody(); - assertThat("Wrong output: " + json, json, is( - "{\"a\":{\"b\":[{\"c\":\"x\",\"d\":[\"xx\",\"yy\"]},{\"c\":\"y\",\"e\":[{\"d\":\"z\"}]}]}}")); + assertThat(json).as("Wrong output: " + json).isEqualTo( + "{\"a\":{\"b\":[{\"c\":\"x\",\"d\":[\"xx\",\"yy\"]},{\"c\":\"y\",\"e\":[{\"d\":\"z\"}]}]}}"); } @Test @@ -369,7 +370,7 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("b:\n- c: d\n- c: d\n", yaml); + assertThat(yaml).isEqualTo("b:\n- c: d\n- c: d\n"); } @Test @@ -381,21 +382,21 @@ public class EnvironmentControllerTests { Mockito.when(this.repository.findOne("foo", "bar", null)) .thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); - assertEquals("x:\n a:\n b:\n - c: d\n - c: d\n", yaml); + assertThat(yaml).isEqualTo("x:\n a:\n b:\n - c: d\n - c: d\n"); } @Test public void placeholdersResolvedInProperties() throws Exception { whenPlaceholders(); String text = this.controller.properties("foo", "bar", true).getBody(); - assertEquals("a.b.c: bar\nfoo: bar", text); + assertThat(text).isEqualTo("a.b.c: bar\nfoo: bar"); } @Test public void placeholdersNotResolvedInProperties() throws Exception { whenPlaceholders(); String text = this.controller.properties("foo", "bar", false).getBody(); - assertEquals("a.b.c: ${foo}\nfoo: bar", text); + assertThat(text).isEqualTo("a.b.c: ${foo}\nfoo: bar"); } @Test @@ -403,7 +404,7 @@ public class EnvironmentControllerTests { throws Exception { whenPlaceholdersSystemProps(); String text = this.controller.properties("foo", "bar", true).getBody(); - assertEquals("a.b.c: ${foo}", text); + assertThat(text).isEqualTo("a.b.c: ${foo}"); } @Test @@ -411,7 +412,7 @@ public class EnvironmentControllerTests { throws Exception { whenPlaceholdersSystemProps(); String text = this.controller.properties("foo", "bar", false).getBody(); - assertEquals("a.b.c: ${foo}", text); + assertThat(text).isEqualTo("a.b.c: ${foo}"); } @Test @@ -419,28 +420,28 @@ public class EnvironmentControllerTests { throws Exception { whenPlaceholdersSystemPropsWithDefault(); String text = this.controller.properties("foo", "bar", false).getBody(); - assertEquals("a.b.c: ${foo:spam}", text); + assertThat(text).isEqualTo("a.b.c: ${foo:spam}"); } @Test public void placeholdersResolvedInJson() throws Exception { whenPlaceholders(); String json = this.controller.jsonProperties("foo", "bar", true).getBody(); - assertEquals("{\"a\":{\"b\":{\"c\":\"bar\"}},\"foo\":\"bar\"}", json); + assertThat(json).isEqualTo("{\"a\":{\"b\":{\"c\":\"bar\"}},\"foo\":\"bar\"}"); } @Test public void placeholdersNotResolvedInJson() throws Exception { whenPlaceholders(); String json = this.controller.jsonProperties("foo", "bar", false).getBody(); - assertEquals("{\"a\":{\"b\":{\"c\":\"${foo}\"}},\"foo\":\"bar\"}", json); + assertThat(json).isEqualTo("{\"a\":{\"b\":{\"c\":\"${foo}\"}},\"foo\":\"bar\"}"); } @Test public void placeholdersNotResolvedInJsonFromSystemProperties() throws Exception { whenPlaceholdersSystemProps(); String json = this.controller.jsonProperties("foo", "bar", true).getBody(); - assertEquals("{\"a\":{\"b\":{\"c\":\"${foo}\"}}}", json); + assertThat(json).isEqualTo("{\"a\":{\"b\":{\"c\":\"${foo}\"}}}"); } @Test @@ -448,7 +449,7 @@ public class EnvironmentControllerTests { throws Exception { whenPlaceholdersSystemProps(); String json = this.controller.jsonProperties("foo", "bar", false).getBody(); - assertEquals("{\"a\":{\"b\":{\"c\":\"${foo}\"}}}", json); + assertThat(json).isEqualTo("{\"a\":{\"b\":{\"c\":\"${foo}\"}}}"); } @Test @@ -457,7 +458,7 @@ public class EnvironmentControllerTests { whenPlaceholdersSystemPropsWithDefault(); String json = this.controller.jsonProperties("foo", "bar", false).getBody(); // If there is a default value we prevent the placeholder being resolved - assertEquals("{\"a\":{\"b\":{\"c\":\"${foo:spam}\"}}}", json); + assertThat(json).isEqualTo("{\"a\":{\"b\":{\"c\":\"${foo:spam}\"}}}"); } @Test @@ -466,7 +467,7 @@ public class EnvironmentControllerTests { whenPlaceholdersSystemPropsWithDefault(); String json = this.controller.jsonProperties("foo", "bar", true).getBody(); // If there is a default value we do not prevent the placeholder being resolved - assertEquals("{\"a\":{\"b\":{\"c\":\"spam\"}}}", json); + assertThat(json).isEqualTo("{\"a\":{\"b\":{\"c\":\"spam\"}}}"); } private void whenPlaceholders() { @@ -512,7 +513,7 @@ public class EnvironmentControllerTests { mvc.perform(MockMvcRequestBuilders.get("/foo/bar/other")) .andExpect(MockMvcResultMatchers.status().isOk()); } - + @Test public void environmentMissing() throws Exception { Mockito.when(this.repository.findOne("foo1", "notfound", null)) diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepositoryTests.java index 6d58f23f..2b34e449 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.config.server.environment; -import static org.junit.Assert.assertEquals; +package org.springframework.cloud.config.server.environment; import java.util.Collections; import java.util.HashMap; @@ -26,9 +25,12 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; + import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.environment.PropertySource; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @author Roy Clarkson @@ -55,9 +57,10 @@ public class EnvironmentEncryptorEnvironmentRepositoryTests { Map map = new HashMap(); map.put("a.b.c", "d"); this.environment.add(new PropertySource("one", map)); - Mockito.when(this.repository.findOne("foo", "bar", "master")).thenReturn(this.environment); - assertEquals("{foo=bar}", this.controller.findOne("foo", "bar", "master") - .getPropertySources().get(0).getSource().toString()); + Mockito.when(this.repository.findOne("foo", "bar", "master")) + .thenReturn(this.environment); + assertThat(this.controller.findOne("foo", "bar", "master").getPropertySources() + .get(0).getSource().toString()).isEqualTo("{foo=bar}"); } @Test @@ -66,9 +69,10 @@ public class EnvironmentEncryptorEnvironmentRepositoryTests { Map map = new HashMap(); map.put("bar", "foo"); this.environment.add(new PropertySource("one", map)); - Mockito.when(this.repository.findOne("foo", "bar", "master")).thenReturn(this.environment); - assertEquals("{foo=${bar}}", this.controller.findOne("foo", "bar", "master") - .getPropertySources().get(0).getSource().toString()); + Mockito.when(this.repository.findOne("foo", "bar", "master")) + .thenReturn(this.environment); + assertThat(this.controller.findOne("foo", "bar", "master").getPropertySources() + .get(0).getSource().toString()).isEqualTo("{foo=${bar}}"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactoryTest.java index dae0f601..f9be434f 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactoryTest.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.environment; import java.lang.reflect.Field; @@ -18,174 +34,205 @@ import static org.assertj.core.api.Assertions.assertThat; public class HttpClientConfigurableHttpConnectionFactoryTest { - private HttpClientConfigurableHttpConnectionFactory connectionFactory; + private HttpClientConfigurableHttpConnectionFactory connectionFactory; - @Before - public void setUp() { - connectionFactory = new HttpClientConfigurableHttpConnectionFactory(); - } + @Before + public void setUp() { + this.connectionFactory = new HttpClientConfigurableHttpConnectionFactory(); + } - @Test - public void noConfigAdded() throws Exception { - HttpConnection actual = connectionFactory.create(new URL("http://localhost/test.git")); + @Test + public void noConfigAdded() throws Exception { + HttpConnection actual = this.connectionFactory + .create(new URL("http://localhost/test.git")); - assertThat(actual).isNotNull(); - } + assertThat(actual).isNotNull(); + } - @Test - public void nullPointerCheckGh1051() throws Exception { - MultipleJGitEnvironmentProperties properties = new MultipleJGitEnvironmentProperties(); - connectionFactory.addConfiguration(properties); - } + @Test + public void nullPointerCheckGh1051() throws Exception { + MultipleJGitEnvironmentProperties properties = new MultipleJGitEnvironmentProperties(); + this.connectionFactory.addConfiguration(properties); + } - @Test - public void matchingUrl() throws Exception { - String url = "http://localhost/test.git"; - MultipleJGitEnvironmentProperties properties = new MultipleJGitEnvironmentProperties(); - properties.setUri(url); - connectionFactory.addConfiguration(properties); + @Test + public void matchingUrl() throws Exception { + String url = "http://localhost/test.git"; + MultipleJGitEnvironmentProperties properties = new MultipleJGitEnvironmentProperties(); + properties.setUri(url); + this.connectionFactory.addConfiguration(properties); - HttpConnection actualConnection = connectionFactory.create(new URL(url)); + HttpConnection actualConnection = this.connectionFactory.create(new URL(url)); - HttpClientBuilder expectedHttpClientBuilder = connectionFactory.httpClientBuildersByUri.values().stream().findFirst().get(); - HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); - assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); - } + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri + .values().stream().findFirst().get(); + HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder( + actualConnection); + assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); + } - @Test - public void longerUrl() throws Exception { - MultipleJGitEnvironmentProperties properties = new MultipleJGitEnvironmentProperties(); - String url = "http://localhost/test.git"; - properties.setUri(url); - connectionFactory.addConfiguration(properties); + @Test + public void longerUrl() throws Exception { + MultipleJGitEnvironmentProperties properties = new MultipleJGitEnvironmentProperties(); + String url = "http://localhost/test.git"; + properties.setUri(url); + this.connectionFactory.addConfiguration(properties); - HttpConnection actualConnection = connectionFactory.create(new URL(url + "/some/path.properties")); + HttpConnection actualConnection = this.connectionFactory + .create(new URL(url + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = connectionFactory.httpClientBuildersByUri.values().stream().findFirst().get(); - HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); - assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); - } + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri + .values().stream().findFirst().get(); + HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder( + actualConnection); + assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); + } - @Test - public void urlWithPlaceholders() throws Exception { - MultipleJGitEnvironmentProperties properties = new MultipleJGitEnvironmentProperties(); - properties.setUri("http://localhost/{placeholder}-test.git"); - connectionFactory.addConfiguration(properties); + @Test + public void urlWithPlaceholders() throws Exception { + MultipleJGitEnvironmentProperties properties = new MultipleJGitEnvironmentProperties(); + properties.setUri("http://localhost/{placeholder}-test.git"); + this.connectionFactory.addConfiguration(properties); - HttpConnection actualConnection = connectionFactory.create(new URL("http://localhost/value-test.git" + "/some/path.properties")); + HttpConnection actualConnection = this.connectionFactory.create( + new URL("http://localhost/value-test.git" + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = connectionFactory.httpClientBuildersByUri.values().stream().findFirst().get(); - HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); - assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); - } + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri + .values().stream().findFirst().get(); + HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder( + actualConnection); + assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); + } - @Test - public void composite_sameHost() throws Exception { - MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); - properties1.setUri("http://localhost/test1.git"); - MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); - properties2.setUri("http://localhost/test2.git"); - connectionFactory.addConfiguration(properties1); - connectionFactory.addConfiguration(properties2); + @Test + public void composite_sameHost() throws Exception { + MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); + properties1.setUri("http://localhost/test1.git"); + MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); + properties2.setUri("http://localhost/test2.git"); + this.connectionFactory.addConfiguration(properties1); + this.connectionFactory.addConfiguration(properties2); - HttpConnection actualConnection = connectionFactory.create(new URL(properties1.getUri())); + HttpConnection actualConnection = this.connectionFactory + .create(new URL(properties1.getUri())); - HttpClientBuilder expectedHttpClientBuilder = connectionFactory.httpClientBuildersByUri.get(properties1.getUri()); - HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); - assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); - } + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri + .get(properties1.getUri()); + HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder( + actualConnection); + assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); + } - @Test - public void composite_differentHost() throws Exception { - MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); - properties1.setUri("http://localhost1/test.git"); - MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); - properties2.setUri("http://localhost2/test.git"); - connectionFactory.addConfiguration(properties1); - connectionFactory.addConfiguration(properties2); + @Test + public void composite_differentHost() throws Exception { + MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); + properties1.setUri("http://localhost1/test.git"); + MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); + properties2.setUri("http://localhost2/test.git"); + this.connectionFactory.addConfiguration(properties1); + this.connectionFactory.addConfiguration(properties2); - HttpConnection actualConnection = connectionFactory.create(new URL(properties1.getUri())); + HttpConnection actualConnection = this.connectionFactory + .create(new URL(properties1.getUri())); - HttpClientBuilder expectedHttpClientBuilder = connectionFactory.httpClientBuildersByUri.get(properties1.getUri()); - HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); - assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); - } + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri + .get(properties1.getUri()); + HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder( + actualConnection); + assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); + } - @Test - public void composite_urlsWithPlaceholders() throws Exception { - MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); - properties1.setUri("http://localhost/path/{placeholder3}/more/test.git"); - MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); - properties2.setUri("http://localhost/{placeholder1}/path/{placeholder2}-test.git"); - connectionFactory.addConfiguration(properties1); - connectionFactory.addConfiguration(properties2); + @Test + public void composite_urlsWithPlaceholders() throws Exception { + MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); + properties1.setUri("http://localhost/path/{placeholder3}/more/test.git"); + MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); + properties2 + .setUri("http://localhost/{placeholder1}/path/{placeholder2}-test.git"); + this.connectionFactory.addConfiguration(properties1); + this.connectionFactory.addConfiguration(properties2); - HttpConnection actualConnection = connectionFactory.create(new URL(properties2.getUri() - .replace("{placeholder1}", "value1") - .replace("{placeholder2}", "value2"))); + HttpConnection actualConnection = this.connectionFactory + .create(new URL(properties2.getUri().replace("{placeholder1}", "value1") + .replace("{placeholder2}", "value2"))); - HttpClientBuilder expectedHttpClientBuilder = connectionFactory.httpClientBuildersByUri.get(properties2.getUri()); - HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); - assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); - } + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri + .get(properties2.getUri()); + HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder( + actualConnection); + assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); + } - @Test - public void composite_urlsWithPlaceholders_identicalTemplatesWontBeResolvedProperly() throws Exception { - MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); - properties1.setUri("http://localhost/{placeholder3}/path/{placeholder4}-test.git"); - MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); - properties2.setUri("http://localhost/{placeholder1}/path/{placeholder2}-test.git"); - connectionFactory.addConfiguration(properties1); - connectionFactory.addConfiguration(properties2); + @Test + public void composite_urlsWithPlaceholders_identicalTemplatesWontBeResolvedProperly() + throws Exception { + MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); + properties1 + .setUri("http://localhost/{placeholder3}/path/{placeholder4}-test.git"); + MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); + properties2 + .setUri("http://localhost/{placeholder1}/path/{placeholder2}-test.git"); + this.connectionFactory.addConfiguration(properties1); + this.connectionFactory.addConfiguration(properties2); - HttpConnection actualConnection = connectionFactory.create(new URL(properties2.getUri() - .replace("{placeholder1}", "value1") - .replace("{placeholder2}", "value2"))); + HttpConnection actualConnection = this.connectionFactory + .create(new URL(properties2.getUri().replace("{placeholder1}", "value1") + .replace("{placeholder2}", "value2"))); - HttpClientBuilder expectedHttpClientBuilder = connectionFactory.httpClientBuildersByUri.get(properties2.getUri()); - HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); - assertThat(actualHttpClientBuilder).isNotSameAs(expectedHttpClientBuilder); - } + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri + .get(properties2.getUri()); + HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder( + actualConnection); + assertThat(actualHttpClientBuilder).isNotSameAs(expectedHttpClientBuilder); + } - @Test - public void composite_longerUrlsWithPlaceholders() throws Exception { - MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); - properties1.setUri("http://localhost/path/{placeholder3}/{placeholder4}-test.git"); - MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); - properties2.setUri("http://localhost/{placeholder1}/path/{placeholder2}-test.git"); - connectionFactory.addConfiguration(properties1); - connectionFactory.addConfiguration(properties2); + @Test + public void composite_longerUrlsWithPlaceholders() throws Exception { + MultipleJGitEnvironmentProperties properties1 = new MultipleJGitEnvironmentProperties(); + properties1 + .setUri("http://localhost/path/{placeholder3}/{placeholder4}-test.git"); + MultipleJGitEnvironmentProperties properties2 = new MultipleJGitEnvironmentProperties(); + properties2 + .setUri("http://localhost/{placeholder1}/path/{placeholder2}-test.git"); + this.connectionFactory.addConfiguration(properties1); + this.connectionFactory.addConfiguration(properties2); - HttpConnection actualConnection = connectionFactory.create(new URL(properties2.getUri() - .replace("{placeholder1}", "value1") - .replace("{placeholder2}", "value2") + "/some/path.properties")); + HttpConnection actualConnection = this.connectionFactory + .create(new URL(properties2.getUri().replace("{placeholder1}", "value1") + .replace("{placeholder2}", "value2") + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = connectionFactory.httpClientBuildersByUri.get(properties2.getUri()); - HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); - assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); - } + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri + .get(properties2.getUri()); + HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder( + actualConnection); + assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); + } - private HttpClient getActualHttpClient(HttpConnection actualConnection) { - Field clientField = ReflectionUtils.findField(actualConnection.getClass(), "client"); - ReflectionUtils.makeAccessible(clientField); - return (HttpClient) ReflectionUtils.getField(clientField, actualConnection); - } + private HttpClient getActualHttpClient(HttpConnection actualConnection) { + Field clientField = ReflectionUtils.findField(actualConnection.getClass(), + "client"); + ReflectionUtils.makeAccessible(clientField); + return (HttpClient) ReflectionUtils.getField(clientField, actualConnection); + } - private HttpClientBuilder getActualHttpClientBuilder(HttpConnection actualConnection) { - HttpClient actualHttpClient = getActualHttpClient(actualConnection); - Field closeablesField = ReflectionUtils.findField(actualHttpClient.getClass(), "closeables"); - ReflectionUtils.makeAccessible(closeablesField); - List closables = (List) ReflectionUtils.getField(closeablesField, actualHttpClient); - return closables.stream() - .map(o -> { - Field builderField = Arrays.stream(o.getClass().getDeclaredFields()).filter(field -> HttpClientBuilder.class.isAssignableFrom(field.getType())).findFirst().orElse(null); - if (builderField != null) { - ReflectionUtils.makeAccessible(builderField); - return ReflectionUtils.getField(builderField, o); - } - return null; - }) - .filter(Objects::nonNull) - .map(HttpClientBuilder.class::cast).findFirst().get(); - } -} \ No newline at end of file + private HttpClientBuilder getActualHttpClientBuilder( + HttpConnection actualConnection) { + HttpClient actualHttpClient = getActualHttpClient(actualConnection); + Field closeablesField = ReflectionUtils.findField(actualHttpClient.getClass(), + "closeables"); + ReflectionUtils.makeAccessible(closeablesField); + List closables = (List) ReflectionUtils.getField(closeablesField, + actualHttpClient); + return closables.stream().map(o -> { + Field builderField = Arrays.stream(o.getClass().getDeclaredFields()).filter( + field -> HttpClientBuilder.class.isAssignableFrom(field.getType())) + .findFirst().orElse(null); + if (builderField != null) { + ReflectionUtils.makeAccessible(builderField); + return ReflectionUtils.getField(builderField, o); + } + return null; + }).filter(Objects::nonNull).map(HttpClientBuilder.class::cast).findFirst().get(); + } + +} diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitConfigServerTestData.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitConfigServerTestData.java index a0b9b175..86cab892 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitConfigServerTestData.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitConfigServerTestData.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,8 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import org.eclipse.jgit.api.Git; @@ -25,104 +30,107 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.util.FileSystemUtils; import org.springframework.util.ResourceUtils; -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; - /** - * Class that holds objects that can be used for testing + * Class that holds objects that can be used for testing. + * * @author Ryan Lynch */ public class JGitConfigServerTestData { - private LocalGit serverGit; - private LocalGit clonedGit; - private JGitEnvironmentRepository repository; - private ConfigurableApplicationContext context; + private LocalGit serverGit; - public static class LocalGit { - private Git git; - private File gitWorkingDirectory; + private LocalGit clonedGit; - public LocalGit(Git git, File gitWorkingDirectory) { - this.git = git; - this.gitWorkingDirectory = gitWorkingDirectory; - } + private JGitEnvironmentRepository repository; - public Git getGit() { - return this.git; - } + private ConfigurableApplicationContext context; - public File getGitWorkingDirectory() { - return this.gitWorkingDirectory; - } - } + public JGitConfigServerTestData(LocalGit serverGit, LocalGit clonedGit, + JGitEnvironmentRepository repository, + ConfigurableApplicationContext context) { + this.serverGit = serverGit; + this.clonedGit = clonedGit; + this.repository = repository; + this.context = context; + } - public JGitConfigServerTestData(LocalGit serverGit, LocalGit clonedGit, - JGitEnvironmentRepository repository, ConfigurableApplicationContext context) { - this.serverGit = serverGit; - this.clonedGit = clonedGit; - this.repository = repository; - this.context = context; - } + public static JGitConfigServerTestData prepareClonedGitRepository(Class... sources) + throws Exception { + return prepareClonedGitRepository(Collections.emptySet(), sources); + } - public LocalGit getServerGit() { - return this.serverGit; - } + public static JGitConfigServerTestData prepareClonedGitRepository( + Collection additionalProperties, Class... sources) throws Exception { + // setup remote repository + String remoteUri = ConfigServerTestUtils.prepareLocalRepo(); + File remoteRepoDir = ResourceUtils.getFile(remoteUri); + Git remoteGit = Git.open(remoteRepoDir.getAbsoluteFile()); + remoteGit.checkout().setName("master").call(); - public LocalGit getClonedGit() { - return this.clonedGit; - } + // setup local repository + File clonedRepoDir = new File("target/repos/cloned"); + if (clonedRepoDir.exists()) { + FileSystemUtils.deleteRecursively(clonedRepoDir); + } + else { + clonedRepoDir.mkdirs(); + } + Git clonedGit = Git.cloneRepository() + .setURI("file://" + remoteRepoDir.getAbsolutePath()) + .setDirectory(clonedRepoDir).setBranch("master").setCloneAllBranches(true) + .call(); - public JGitEnvironmentRepository getRepository() { - return this.repository; - } + // setup our test spring application pointing to the local repo + Collection properties = new ArrayList<>(additionalProperties); + properties.add("spring.cloud.config.server.git.uri:" + "file://" + + clonedRepoDir.getAbsolutePath()); + ConfigurableApplicationContext context = new SpringApplicationBuilder(sources) + .web(WebApplicationType.NONE) + .properties(properties.toArray(new String[0])).run(); + JGitEnvironmentRepository repository = context + .getBean(JGitEnvironmentRepository.class); - public ConfigurableApplicationContext getContext() { - return this.context; - } + return new JGitConfigServerTestData( + new JGitConfigServerTestData.LocalGit(remoteGit, remoteRepoDir), + new JGitConfigServerTestData.LocalGit(clonedGit, clonedRepoDir), + repository, context); + } - public static JGitConfigServerTestData prepareClonedGitRepository(Class... sources) - throws Exception { - return prepareClonedGitRepository(Collections.emptySet(), sources); - } + public LocalGit getServerGit() { + return this.serverGit; + } - public static JGitConfigServerTestData prepareClonedGitRepository(Collection additionalProperties, Class... sources) - throws Exception { - //setup remote repository - String remoteUri = ConfigServerTestUtils.prepareLocalRepo(); - File remoteRepoDir = ResourceUtils.getFile(remoteUri); - Git remoteGit = Git.open(remoteRepoDir.getAbsoluteFile()); - remoteGit.checkout().setName("master").call(); + public LocalGit getClonedGit() { + return this.clonedGit; + } - //setup local repository - File clonedRepoDir = new File("target/repos/cloned"); - if(clonedRepoDir.exists()) { - FileSystemUtils.deleteRecursively(clonedRepoDir); - } else { - clonedRepoDir.mkdirs(); - } - Git clonedGit = Git.cloneRepository() - .setURI( "file://" + remoteRepoDir.getAbsolutePath() ) - .setDirectory( clonedRepoDir ) - .setBranch("master") - .setCloneAllBranches(true) - .call(); + public JGitEnvironmentRepository getRepository() { + return this.repository; + } - //setup our test spring application pointing to the local repo - Collection properties = new ArrayList<>(additionalProperties); - properties.add("spring.cloud.config.server.git.uri:" + "file://" + clonedRepoDir.getAbsolutePath()); - ConfigurableApplicationContext context = new SpringApplicationBuilder(sources).web(WebApplicationType.NONE) - .properties(properties.toArray(new String[0])) - .run(); - JGitEnvironmentRepository repository = context.getBean(JGitEnvironmentRepository.class); + public ConfigurableApplicationContext getContext() { + return this.context; + } - return new JGitConfigServerTestData( - new JGitConfigServerTestData.LocalGit(remoteGit, remoteRepoDir), - new JGitConfigServerTestData.LocalGit(clonedGit, clonedRepoDir), - repository, context); - } + public static class LocalGit { + private Git git; + + private File gitWorkingDirectory; + + public LocalGit(Git git, File gitWorkingDirectory) { + this.git = git; + this.gitWorkingDirectory = gitWorkingDirectory; + } + + public Git getGit() { + return this.git; + } + + public File getGitWorkingDirectory() { + return this.gitWorkingDirectory; + } + + } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryConcurrencyTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryConcurrencyTests.java index 40c5e7ac..9af18560 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryConcurrencyTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryConcurrencyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,13 @@ import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.FetchCommand; import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.*; +import org.eclipse.jgit.api.errors.CheckoutConflictException; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.api.errors.InvalidRefNameException; +import org.eclipse.jgit.api.errors.InvalidRemoteException; +import org.eclipse.jgit.api.errors.RefAlreadyExistsException; +import org.eclipse.jgit.api.errors.RefNotFoundException; +import org.eclipse.jgit.api.errors.TransportException; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.FetchResult; @@ -52,8 +58,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -61,6 +66,8 @@ import static org.junit.Assert.assertEquals; */ public class JGitEnvironmentRepositoryConcurrencyTests { + protected Log logger = LogFactory.getLog(getClass()); + private ConfigurableApplicationContext context; private File basedir = new File("target/config"); @@ -102,28 +109,28 @@ public class JGitEnvironmentRepositoryConcurrencyTests { future.get(); } Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals("bar", environment.getName()); - assertArrayEquals(new String[] { "staging" }, environment.getProfiles()); - assertEquals("master", environment.getLabel()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getName()).isEqualTo("bar"); + assertThat(environment.getProfiles()).isEqualTo(new String[] { "staging" }); + assertThat(environment.getLabel()).isEqualTo("master"); } - protected Log logger = LogFactory.getLog(getClass()); - /** - * Simulates following actions in parallel: - * - Client tries to obtain configuration with specified label - * - Spring Refresh Context Event occurs + * Simulates following actions in parallel: - Client tries to obtain configuration + * with specified label - Spring Refresh Context Event occurs. + * @throws Exception when git related exception happens */ @Test public void concurrentRefreshContextAndGetLabels() throws Exception { // Prepare the repo - final JGitConfigServerTestData testData = JGitConfigServerTestData.prepareClonedGitRepository(TestConfiguration.class); + final JGitConfigServerTestData testData = JGitConfigServerTestData + .prepareClonedGitRepository(TestConfiguration.class); JGitEnvironmentRepository repository = testData.getRepository(); repository.setCloneOnStart(true); repository.setGitFactory(new DelayedGitFactoryMock()); repository.setBasedir(testData.getClonedGit().getGitWorkingDirectory()); - repository.setUri(testData.getServerGit().getGitWorkingDirectory().getAbsolutePath().replace("file://", "")); + repository.setUri(testData.getServerGit().getGitWorkingDirectory() + .getAbsolutePath().replace("file://", "")); final AtomicInteger errorCount = new AtomicInteger(); @@ -131,14 +138,17 @@ public class JGitEnvironmentRepositoryConcurrencyTests { Thread client = new Thread(new Runnable() { @Override public void run() { - logger.info("client start."); + JGitEnvironmentRepositoryConcurrencyTests.this.logger + .info("client start."); try { - Environment environment = testData.getRepository().findOne("bar", "staging", "master"); - } catch (Exception e) { + Environment environment = testData.getRepository().findOne("bar", + "staging", "master"); + } + catch (Exception e) { errorCount.incrementAndGet(); e.printStackTrace(); } - logger.info("client end."); + JGitEnvironmentRepositoryConcurrencyTests.this.logger.info("client end."); } }); @@ -146,10 +156,13 @@ public class JGitEnvironmentRepositoryConcurrencyTests { @Override public void run() { try { - logger.info("refresh start."); + JGitEnvironmentRepositoryConcurrencyTests.this.logger + .info("refresh start."); testData.getRepository().afterPropertiesSet(); - logger.info("refresh end."); - } catch (Exception e) { + JGitEnvironmentRepositoryConcurrencyTests.this.logger + .info("refresh end."); + } + catch (Exception e) { errorCount.incrementAndGet(); e.printStackTrace(); } @@ -162,7 +175,7 @@ public class JGitEnvironmentRepositoryConcurrencyTests { refresh.join(); client.join(); - assertEquals(0, errorCount.get()); + assertThat(errorCount.get()).isEqualTo(0); } @Configuration @@ -170,9 +183,11 @@ public class JGitEnvironmentRepositoryConcurrencyTests { @Import({ PropertyPlaceholderAutoConfiguration.class, EnvironmentRepositoryConfiguration.class }) protected static class TestConfiguration { + } - private static class DelayedGitFactoryMock extends JGitEnvironmentRepository.JGitFactory { + private static class DelayedGitFactoryMock + extends JGitEnvironmentRepository.JGitFactory { @Override public Git getGitByOpen(File file) throws IOException { @@ -184,11 +199,12 @@ public class JGitEnvironmentRepositoryConcurrencyTests { public CloneCommand getCloneCommandByCloneRepository() { return new DelayedCloneCommand(); } + } private static class DelayedGitMock extends Git { - public DelayedGitMock(Repository repo) { + DelayedGitMock(Repository repo) { super(repo); } @@ -201,51 +217,63 @@ public class JGitEnvironmentRepositoryConcurrencyTests { public CheckoutCommand checkout() { return new DelayedCheckoutCommand(getRepository()); } + } private static class DelayedCloneCommand extends CloneCommand { + @Override - public Git call() throws GitAPIException, InvalidRemoteException, TransportException { + public Git call() + throws GitAPIException, InvalidRemoteException, TransportException { try { Thread.sleep(250); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { e.printStackTrace(); } return super.call(); } + } private static class DelayedFetchCommand extends FetchCommand { - public DelayedFetchCommand(Repository repo) { + DelayedFetchCommand(Repository repo) { super(repo); } @Override - public FetchResult call() throws GitAPIException, InvalidRemoteException, TransportException { + public FetchResult call() + throws GitAPIException, InvalidRemoteException, TransportException { try { Thread.sleep(250); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { e.printStackTrace(); } return super.call(); } + } private static class DelayedCheckoutCommand extends CheckoutCommand { - public DelayedCheckoutCommand(Repository repo) { + + DelayedCheckoutCommand(Repository repo) { super(repo); } @Override - public Ref call() throws GitAPIException, RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, CheckoutConflictException { + public Ref call() throws GitAPIException, RefAlreadyExistsException, + RefNotFoundException, InvalidRefNameException, CheckoutConflictException { try { Thread.sleep(250); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { e.printStackTrace(); } return super.call(); } + } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryIntegrationTests.java index 2b0e0497..946dc259 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,6 @@ import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.util.FileUtils; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -58,14 +57,8 @@ import org.springframework.context.annotation.Import; import org.springframework.util.ResourceUtils; import org.springframework.util.StreamUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * @author Dave Syer @@ -97,27 +90,32 @@ public class JGitEnvironmentRepositoryIntegrationTests { @Test public void vanilla() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo(); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .properties("spring.cloud.config.server.git.uri:" + uri).run(); - EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); + EnvironmentRepository repository = this.context + .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals("bar", environment.getName()); - assertArrayEquals(new String[] { "staging" }, environment.getProfiles()); - assertEquals("master", environment.getLabel()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getName()).isEqualTo("bar"); + assertThat(environment.getProfiles()).isEqualTo(new String[] { "staging" }); + assertThat(environment.getLabel()).isEqualTo("master"); } @Test public void pull() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri); - EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); + EnvironmentRepository repository = this.context + .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals("bar", environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("bar"); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); git.checkout().setName("master").call(); StreamUtils.copy("foo: foo", Charset.defaultCharset(), @@ -125,14 +123,16 @@ public class JGitEnvironmentRepositoryIntegrationTests { git.add().addFilepattern("bar.properties").call(); git.commit().setMessage("Updated for pull").call(); environment = repository.findOne("bar", "staging", "master"); - assertEquals("foo", environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("foo"); } /** - * Tests a special use case where the remote repository has been updated - * with a forced push conflicting with the local repo of the Config Server. - * The Config Server has to reset hard on the new reference because a simple - * pull operation could result in a conflicting local repository. + * Tests a special use case where the remote repository has been updated with a forced + * push conflicting with the local repo of the Config Server. The Config Server has to + * reset hard on the new reference because a simple pull operation could result in a + * conflicting local repository. + * @throws Exception when git related exception happens */ @Test public void pullDirtyRepo() throws Exception { @@ -144,124 +144,152 @@ public class JGitEnvironmentRepositoryIntegrationTests { Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); StoredConfig config = git.getRepository().getConfig(); - config.setString("remote", "origin", "url", remote.getDirectory().getAbsolutePath()); - config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); + config.setString("remote", "origin", "url", + remote.getDirectory().getAbsolutePath()); + config.setString("remote", "origin", "fetch", + "+refs/heads/*:refs/remotes/origin/*"); config.save(); // Pushes the raw branch to remote repository. git.push().call(); - String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator().next().getName(); + String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator() + .next().getName(); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri); - JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); + JGitEnvironmentRepository repository = this.context + .getBean(JGitEnvironmentRepository.class); // Fetches the repository for the first time. - SearchPathLocator.Locations locations = repository.getLocations("bar", "test", "raw"); - assertEquals(locations.getVersion(), commitToRevertBeforePull); + SearchPathLocator.Locations locations = repository.getLocations("bar", "test", + "raw"); + assertThat(commitToRevertBeforePull).isEqualTo(locations.getVersion()); // Resets to the original commit. git.reset().setMode(ResetType.HARD).setRef("master").call(); // Generate a conflicting commit who will be forced on the origin. - Path applicationFilePath = Paths.get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml"); + Path applicationFilePath = Paths + .get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml"); - Files.write(applicationFilePath, Arrays.asList("info:", " foo: bar", "raw: false"), StandardCharsets.UTF_8, - StandardOpenOption.TRUNCATE_EXISTING); + Files.write(applicationFilePath, + Arrays.asList("info:", " foo: bar", "raw: false"), + StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); git.add().addFilepattern(".").call(); git.commit().setMessage("Conflicting commit.").call(); git.push().setForce(true).call(); - String conflictingCommit = git.log().setMaxCount(1).call().iterator().next().getName(); + String conflictingCommit = git.log().setMaxCount(1).call().iterator().next() + .getName(); // Reset to the raw branch. git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call(); // Triggers the repository refresh. locations = repository.getLocations("bar", "test", "raw"); - assertEquals(locations.getVersion(), conflictingCommit); + assertThat(conflictingCommit).isEqualTo(locations.getVersion()); - assertTrue("Local repository is not cleaned after retrieving resources.", git.status().call().isClean()); + assertThat(git.status().call().isClean()) + .as("Local repository is not cleaned after retrieving resources.") + .isTrue(); } @Test public void pullMissingRepo() throws Exception { pull(); - JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); - new File(repository.getUri().replaceAll("file:", ""), ".git/index.lock").createNewFile(); + JGitEnvironmentRepository repository = this.context + .getBean(JGitEnvironmentRepository.class); + new File(repository.getUri().replaceAll("file:", ""), ".git/index.lock") + .createNewFile(); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals("foo", environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("foo"); } @Test public void nested() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("another-config-repo"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) // TODO: why didn't .properties() work for me? - .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths=sub"); - EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); + .run("--spring.cloud.config.server.git.uri=" + uri, + "--spring.cloud.config.server.git.searchPaths=sub"); + EnvironmentRepository repository = this.context + .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test public void nestedWithApplicationPlaceholders() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("nested-repo"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) // TODO: why didn't .properties() work for me? .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths={application}"); - EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); + EnvironmentRepository repository = this.context + .getBean(EnvironmentRepository.class); repository.findOne("foo,bar", "staging", "master"); Environment environment = repository.findOne("foo,bar", "staging", "master"); - assertEquals(3, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(3); } @Test public void nestedWithProfilePlaceholders() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("nested-repo"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) // TODO: why didn't .properties() work for me? .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths={profile}"); - EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); + EnvironmentRepository repository = this.context + .getBean(EnvironmentRepository.class); repository.findOne("foo,bar", "staging", "master"); Environment environment = repository.findOne("staging", "foo,bar", "master"); - assertEquals(3, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(3); } @Test public void singleElementArrayIndexSearchPath() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("nested-repo"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths[0]={application}"); JGitEnvironmentRepository repository = this.context .getBean(JGitEnvironmentRepository.class); - assertThat(repository.getSearchPaths(), Matchers.arrayContaining("{application}")); - assertFalse(Arrays.equals(repository.getSearchPaths(), - new JGitEnvironmentRepository(repository.getEnvironment(), new JGitEnvironmentProperties()) - .getSearchPaths())); + assertThat(repository.getSearchPaths()).containsExactly("{application}"); + assertThat( + Arrays.equals(repository.getSearchPaths(), + new JGitEnvironmentRepository(repository.getEnvironment(), + new JGitEnvironmentProperties()).getSearchPaths())) + .isFalse(); } @Test public void defaultLabel() throws Exception { String uri = ConfigServerTestUtils.prepareLocalRepo(); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .properties("spring.cloud.config.server.git.uri:" + uri).run(); - JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); - assertEquals("master", repository.getDefaultLabel()); + JGitEnvironmentRepository repository = this.context + .getBean(JGitEnvironmentRepository.class); + assertThat(repository.getDefaultLabel()).isEqualTo("master"); } @Test(expected = NoSuchLabelException.class) public void invalidLabel() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo(); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .properties("spring.cloud.config.server.git.uri:" + uri).run(); - EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); + EnvironmentRepository repository = this.context + .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "unknownlabel"); } @@ -269,31 +297,34 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void findOne_CloneOnStartTrue_FindOneSuccess() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.cloneOnStart=true"); EnvironmentRepository repository = this.context .getBean(JGitEnvironmentRepository.class); - assertTrue(((JGitEnvironmentRepository) repository).isCloneOnStart()); + assertThat(((JGitEnvironmentRepository) repository).isCloneOnStart()).isTrue(); Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals("bar", environment.getName()); - assertArrayEquals(new String[] { "staging" }, environment.getProfiles()); - assertEquals("master", environment.getLabel()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getName()).isEqualTo("bar"); + assertThat(environment.getProfiles()).isEqualTo(new String[] { "staging" }); + assertThat(environment.getLabel()).isEqualTo("master"); } @Test public void findOne_FileAddedToRepo_FindOneSuccess() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.cloneOnStart=true"); EnvironmentRepository repository = this.context .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals("bar", environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("bar"); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); git.checkout().setName("master").call(); StreamUtils.copy("foo: foo", Charset.defaultCharset(), @@ -301,30 +332,37 @@ public class JGitEnvironmentRepositoryIntegrationTests { git.add().addFilepattern("bar.properties").call(); git.commit().setMessage("Updated for pull").call(); environment = repository.findOne("bar", "staging", "master"); - assertEquals("foo", environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("foo"); } @Test public void findOne_NestedSearchPath_FindOneSuccess() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("another-config-repo"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) // TODO: why didn't .properties() work for me? - .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths=sub", + .run("--spring.cloud.config.server.git.uri=" + uri, + "--spring.cloud.config.server.git.searchPaths=sub", "--spring.cloud.config.server.git.cloneOnStart=true"); - EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); + EnvironmentRepository repository = this.context + .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test(expected = NoSuchLabelException.class) - public void findOne_FindInvalidLabel_IllegalStateExceptionThrown() throws IOException { + public void findOne_FindInvalidLabel_IllegalStateExceptionThrown() + throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo(); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .properties("spring.cloud.config.server.git.uri:" + uri, "--spring.cloud.config.server.git.cloneOnStart=true") .run(); - EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); + EnvironmentRepository repository = this.context + .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "unknownlabel"); } @@ -334,19 +372,22 @@ public class JGitEnvironmentRepositoryIntegrationTests { .prepareClonedGitRepository(TestConfiguration.class); // get our starting versions - String startingLocalVersion = getCommitID(testData.getClonedGit().getGit(), "master"); - String startingRemoteVersion = getCommitID(testData.getServerGit().getGit(), "master"); + String startingLocalVersion = getCommitID(testData.getClonedGit().getGit(), + "master"); + String startingRemoteVersion = getCommitID(testData.getServerGit().getGit(), + "master"); // make sure we get the right version out of the gate - Environment environment = testData.getRepository().findOne("bar", "staging", "master"); + Environment environment = testData.getRepository().findOne("bar", "staging", + "master"); // make sure the environments version is the same as the remote repo // version - assertEquals(environment.getVersion(), startingRemoteVersion); + assertThat(startingRemoteVersion).isEqualTo(environment.getVersion()); // update the remote repo - FileOutputStream out = new FileOutputStream( - new File(testData.getServerGit().getGitWorkingDirectory(), "bar.properties")); + FileOutputStream out = new FileOutputStream(new File( + testData.getServerGit().getGitWorkingDirectory(), "bar.properties")); StreamUtils.copy("foo: foo", Charset.defaultCharset(), out); testData.getServerGit().getGit().add().addFilepattern("bar.properties").call(); testData.getServerGit().getGit().commit().setMessage("Updated for pull").call(); @@ -356,17 +397,19 @@ public class JGitEnvironmentRepositoryIntegrationTests { environment = testData.getRepository().findOne("bar", "staging", "master"); // do some more check outs to get updated version numbers - String updatedLocalVersion = getCommitID(testData.getClonedGit().getGit(), "master"); - String updatedRemoteVersion = getCommitID(testData.getClonedGit().getGit(), "master"); + String updatedLocalVersion = getCommitID(testData.getClonedGit().getGit(), + "master"); + String updatedRemoteVersion = getCommitID(testData.getClonedGit().getGit(), + "master"); // make sure our versions have been updated - assertEquals(updatedRemoteVersion, updatedLocalVersion); - assertNotEquals(updatedRemoteVersion, startingRemoteVersion); - assertNotEquals(updatedLocalVersion, startingLocalVersion); + assertThat(updatedLocalVersion).isEqualTo(updatedRemoteVersion); + assertThat(startingRemoteVersion).isNotEqualTo(updatedRemoteVersion); + assertThat(startingLocalVersion).isNotEqualTo(updatedLocalVersion); // make sure our environment also reflects the updated version // this used to have a bug - assertEquals(environment.getVersion(), updatedRemoteVersion); + assertThat(updatedRemoteVersion).isEqualTo(environment.getVersion()); } @Test @@ -374,24 +417,30 @@ public class JGitEnvironmentRepositoryIntegrationTests { JGitConfigServerTestData testData = JGitConfigServerTestData .prepareClonedGitRepository(TestConfiguration.class); - Environment environment = testData.getRepository().findOne("bar", "staging", "master"); - Object fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "bar"); + Environment environment = testData.getRepository().findOne("bar", "staging", + "master"); + Object fooProperty = ConfigServerTestUtils.getProperty(environment, + "bar.properties", "foo"); + assertThat("bar").isEqualTo(fooProperty); - testData.getServerGit().getGit().branchCreate().setName("testNewRemoteBranch").call(); + testData.getServerGit().getGit().branchCreate().setName("testNewRemoteBranch") + .call(); testData.getServerGit().getGit().checkout().setName("testNewRemoteBranch").call(); // update the remote repo - FileOutputStream out = new FileOutputStream( - new File(testData.getServerGit().getGitWorkingDirectory(), "/bar.properties")); + FileOutputStream out = new FileOutputStream(new File( + testData.getServerGit().getGitWorkingDirectory(), "/bar.properties")); StreamUtils.copy("foo: branchBar", Charset.defaultCharset(), out); testData.getServerGit().getGit().add().addFilepattern("bar.properties").call(); - testData.getServerGit().getGit().commit().setMessage("Updated for branch test").call(); + testData.getServerGit().getGit().commit().setMessage("Updated for branch test") + .call(); - environment = testData.getRepository().findOne("bar", "staging", "testNewRemoteBranch"); - fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "branchBar"); + environment = testData.getRepository().findOne("bar", "staging", + "testNewRemoteBranch"); + fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", + "foo"); + assertThat("branchBar").isEqualTo(fooProperty); } @Test @@ -401,9 +450,11 @@ public class JGitEnvironmentRepositoryIntegrationTests { Git serverGit = testData.getServerGit().getGit(); - Environment environment = testData.getRepository().findOne("bar", "staging", "master"); - Object fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "bar"); + Environment environment = testData.getRepository().findOne("bar", "staging", + "master"); + Object fooProperty = ConfigServerTestUtils.getProperty(environment, + "bar.properties", "foo"); + assertThat("bar").isEqualTo(fooProperty); serverGit.checkout().setName("master").call(); @@ -411,26 +462,31 @@ public class JGitEnvironmentRepositoryIntegrationTests { serverGit.tag().setName("testTag").setMessage("Testing a tag").call(); // update the remote repo - FileOutputStream out = new FileOutputStream( - new File(testData.getServerGit().getGitWorkingDirectory(), "/bar.properties")); + FileOutputStream out = new FileOutputStream(new File( + testData.getServerGit().getGitWorkingDirectory(), "/bar.properties")); StreamUtils.copy("foo: testAfterTag", Charset.defaultCharset(), out); testData.getServerGit().getGit().add().addFilepattern("bar.properties").call(); - testData.getServerGit().getGit().commit().setMessage("Updated for branch test").call(); + testData.getServerGit().getGit().commit().setMessage("Updated for branch test") + .call(); environment = testData.getRepository().findOne("bar", "staging", "master"); - fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "testAfterTag"); + fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", + "foo"); + assertThat("testAfterTag").isEqualTo(fooProperty); environment = testData.getRepository().findOne("bar", "staging", "testTag"); - fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "bar"); + fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", + "foo"); + assertThat("bar").isEqualTo(fooProperty); // now move the tag and test again - serverGit.tag().setName("testTag").setForceUpdate(true).setMessage("Testing a moved tag").call(); + serverGit.tag().setName("testTag").setForceUpdate(true) + .setMessage("Testing a moved tag").call(); environment = testData.getRepository().findOne("bar", "staging", "testTag"); - fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "testAfterTag"); + fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", + "foo"); + assertThat("testAfterTag").isEqualTo(fooProperty); } @@ -440,90 +496,107 @@ public class JGitEnvironmentRepositoryIntegrationTests { .prepareClonedGitRepository(TestConfiguration.class); // get our starting versions - String startingRemoteVersion = getCommitID(testData.getServerGit().getGit(), "master"); + String startingRemoteVersion = getCommitID(testData.getServerGit().getGit(), + "master"); // make sure we get the right version out of the gate - Environment environment = testData.getRepository().findOne("bar", "staging", "master"); - assertEquals(environment.getVersion(), startingRemoteVersion); + Environment environment = testData.getRepository().findOne("bar", "staging", + "master"); + assertThat(startingRemoteVersion).isEqualTo(environment.getVersion()); // update the remote repo - FileOutputStream out = new FileOutputStream( - new File(testData.getServerGit().getGitWorkingDirectory(), "bar.properties")); + FileOutputStream out = new FileOutputStream(new File( + testData.getServerGit().getGitWorkingDirectory(), "bar.properties")); StreamUtils.copy("foo: barNewCommit", Charset.defaultCharset(), out); testData.getServerGit().getGit().add().addFilepattern("bar.properties").call(); testData.getServerGit().getGit().commit().setMessage("Updated for pull").call(); - String updatedRemoteVersion = getCommitID(testData.getServerGit().getGit(), "master"); + String updatedRemoteVersion = getCommitID(testData.getServerGit().getGit(), + "master"); // do a normal request and verify we get the new version environment = testData.getRepository().findOne("bar", "staging", "master"); - assertEquals(environment.getVersion(), updatedRemoteVersion); - Object fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "barNewCommit"); + assertThat(updatedRemoteVersion).isEqualTo(environment.getVersion()); + Object fooProperty = ConfigServerTestUtils.getProperty(environment, + "bar.properties", "foo"); + assertThat("barNewCommit").isEqualTo(fooProperty); // request the prior commit ID and make sure we get it - environment = testData.getRepository().findOne("bar", "staging", startingRemoteVersion); - assertEquals(environment.getVersion(), startingRemoteVersion); - fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "bar"); + environment = testData.getRepository().findOne("bar", "staging", + startingRemoteVersion); + assertThat(startingRemoteVersion).isEqualTo(environment.getVersion()); + fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", + "foo"); + assertThat("bar").isEqualTo(fooProperty); } - + @Test /** - * In this scenario there is set the refresh rate so the remote repository is not fetched for every configuration read. - * - * There is more than one label queried - test and master - but only one such branch exists - master. - * - * There is a new commit to master branch but when client loads new configuration, the "test" label is queried first. + * In this scenario there is set the refresh rate so the remote repository is not + * fetched for every configuration read. + * + * There is more than one label queried - test and master - but only one such branch + * exists - master. + * + * There is a new commit to master branch but when client loads new configuration, the + * "test" label is queried first. */ public void testNewCommitIDWithRefreshRate() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData .prepareClonedGitRepository(TestConfiguration.class); - - // get our starting versions - String startingRemoteVersion = getCommitID(testData.getServerGit().getGit(), "master"); - //Ask test label configuration first + // get our starting versions + String startingRemoteVersion = getCommitID(testData.getServerGit().getGit(), + "master"); + + // Ask test label configuration first try { testData.getRepository().findOne("bar", "staging", "test"); fail("Should have thrown NoSuchLabelException."); - } catch (NoSuchLabelException ex) { + } + catch (NoSuchLabelException ex) { // OK } - + // make sure we get the right version out of the gate - Environment environment = testData.getRepository().findOne("bar", "staging", "master"); - assertEquals(environment.getVersion(), startingRemoteVersion); + Environment environment = testData.getRepository().findOne("bar", "staging", + "master"); + assertThat(startingRemoteVersion).isEqualTo(environment.getVersion()); // update the remote repo - FileOutputStream out = new FileOutputStream( - new File(testData.getServerGit().getGitWorkingDirectory(), "bar.properties")); + FileOutputStream out = new FileOutputStream(new File( + testData.getServerGit().getGitWorkingDirectory(), "bar.properties")); StreamUtils.copy("foo: barNewCommit", Charset.defaultCharset(), out); testData.getServerGit().getGit().add().addFilepattern("bar.properties").call(); testData.getServerGit().getGit().commit().setMessage("Updated for pull").call(); - String updatedRemoteVersion = getCommitID(testData.getServerGit().getGit(), "master"); + String updatedRemoteVersion = getCommitID(testData.getServerGit().getGit(), + "master"); // Set refresh rate to 60 seconds (now it will fetch the remote repo only once) testData.getRepository().setRefreshRate(60); - - //Ask test label configuration first + + // Ask test label configuration first try { testData.getRepository().findOne("bar", "staging", "test"); fail("Should have thrown NoSuchLabelException."); - } catch (NoSuchLabelException ex) { + } + catch (NoSuchLabelException ex) { // OK } - + // do a normal request and verify we get the new version environment = testData.getRepository().findOne("bar", "staging", "master"); - assertEquals(environment.getVersion(), updatedRemoteVersion); - Object fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "barNewCommit"); + assertThat(updatedRemoteVersion).isEqualTo(environment.getVersion()); + Object fooProperty = ConfigServerTestUtils.getProperty(environment, + "bar.properties", "foo"); + assertThat("barNewCommit").isEqualTo(fooProperty); // request the prior commit ID and make sure we get it - environment = testData.getRepository().findOne("bar", "staging", startingRemoteVersion); - assertEquals(environment.getVersion(), startingRemoteVersion); - fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); - assertEquals(fooProperty, "bar"); + environment = testData.getRepository().findOne("bar", "staging", + startingRemoteVersion); + assertThat(startingRemoteVersion).isEqualTo(environment.getVersion()); + fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", + "foo"); + assertThat("bar").isEqualTo(fooProperty); } @Test(expected = NoSuchLabelException.class) @@ -543,85 +616,103 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void passphrase() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("config-repo"); final String passphrase = "thisismypassphrase"; - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.passphrase=" + passphrase); - JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); - assertThat(repository.getPassphrase(), Matchers.containsString(passphrase)); + JGitEnvironmentRepository repository = this.context + .getBean(JGitEnvironmentRepository.class); + assertThat(repository.getPassphrase()).contains(passphrase); } @Test public void strictHostKeyChecking() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("config-repo"); final boolean strictHostKeyChecking = true; - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri, - "--spring.cloud.config.server.git.strict-host-key-checking=" + strictHostKeyChecking); - JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); - assertEquals(repository.isStrictHostKeyChecking(), strictHostKeyChecking); + "--spring.cloud.config.server.git.strict-host-key-checking=" + + strictHostKeyChecking); + JGitEnvironmentRepository repository = this.context + .getBean(JGitEnvironmentRepository.class); + assertThat(strictHostKeyChecking).isEqualTo(repository.isStrictHostKeyChecking()); } @Test public void shouldSetTransportConfigCallback() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo(); - this.context = new SpringApplicationBuilder(TestConfigurationWithTransportConfigCallback.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + uri).run(); + this.context = new SpringApplicationBuilder( + TestConfigurationWithTransportConfigCallback.class) + .web(WebApplicationType.NONE) + .properties("spring.cloud.config.server.git.uri:" + uri).run(); - JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); - assertNotNull(repository.getTransportConfigCallback()); + JGitEnvironmentRepository repository = this.context + .getBean(JGitEnvironmentRepository.class); + assertThat(repository.getTransportConfigCallback()).isNotNull(); } @Test - public void testShouldReturnEnvironmentFromLocalBranchInCaseRemoteDeleted() throws Exception { + public void testShouldReturnEnvironmentFromLocalBranchInCaseRemoteDeleted() + throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData .prepareClonedGitRepository(TestConfiguration.class); String branchToDelete = "branchToDelete"; testData.getServerGit().getGit().branchCreate().setName(branchToDelete).call(); - Environment environment = testData.getRepository().findOne("bar", "staging", "branchToDelete"); - assertNotNull(environment); + Environment environment = testData.getRepository().findOne("bar", "staging", + "branchToDelete"); + assertThat(environment).isNotNull(); - testData.getServerGit().getGit().branchDelete().setBranchNames(branchToDelete).call(); + testData.getServerGit().getGit().branchDelete().setBranchNames(branchToDelete) + .call(); testData.getRepository().findOne("bar", "staging", "branchToDelete"); - assertNotNull(environment); + assertThat(environment).isNotNull(); } @Test(expected = NoSuchLabelException.class) public void testShouldFailIfRemoteBranchWasDeleted() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(Collections.singleton("spring.cloud.config.server.git.deleteUntrackedBranches=true"), + .prepareClonedGitRepository(Collections.singleton( + "spring.cloud.config.server.git.deleteUntrackedBranches=true"), TestConfiguration.class); String branchToDelete = "branchToDelete"; testData.getServerGit().getGit().branchCreate().setName(branchToDelete).call(); - //checkout and simulate regular flow - Environment environment = testData.getRepository().findOne("bar", "staging", "branchToDelete"); - assertNotNull(environment); + // checkout and simulate regular flow + Environment environment = testData.getRepository().findOne("bar", "staging", + "branchToDelete"); + assertThat(environment).isNotNull(); - //remove branch - testData.getServerGit().getGit().branchDelete().setBranchNames(branchToDelete).call(); + // remove branch + testData.getServerGit().getGit().branchDelete().setBranchNames(branchToDelete) + .call(); - //test + // test testData.getRepository().findOne("bar", "staging", "branchToDelete"); } @Configuration @EnableConfigurationProperties(ConfigServerProperties.class) - @Import({ PropertyPlaceholderAutoConfiguration.class, EnvironmentRepositoryConfiguration.class }) + @Import({ PropertyPlaceholderAutoConfiguration.class, + EnvironmentRepositoryConfiguration.class }) protected static class TestConfiguration { + } @Configuration @EnableConfigurationProperties(ConfigServerProperties.class) - @Import({ PropertyPlaceholderAutoConfiguration.class, EnvironmentRepositoryConfiguration.class }) + @Import({ PropertyPlaceholderAutoConfiguration.class, + EnvironmentRepositoryConfiguration.class }) protected static class TestConfigurationWithTransportConfigCallback { @Bean public TransportConfigCallback transportConfigCallback() { return Mockito.mock(TransportConfigCallback.class); } + } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositorySslTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositorySslTests.java index cb744124..e7634a2c 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositorySslTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositorySslTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,6 +58,14 @@ public class JGitEnvironmentRepositorySslTests { server.stop(); } + private static String[] configServerProperties(String... extraProperties) { + List properties = new ArrayList<>(Arrays.asList(extraProperties)); + properties.add("spring.cloud.config.server.git.uri=" + server.getSecureUri()); + properties.add("spring.cloud.config.server.git.username=agitter"); + properties.add("spring.cloud.config.server.git.password=letmein"); + return properties.toArray(new String[0]); + } + @Test(expected = CertificateException.class) public void selfSignedCertIsRejected() throws Throwable { ConfigurableApplicationContext context = new SpringApplicationBuilder( @@ -73,8 +81,9 @@ public class JGitEnvironmentRepositorySslTests { catch (Throwable e) { while (e.getCause() != null) { e = e.getCause(); - if (e instanceof CertificateException) + if (e instanceof CertificateException) { break; + } } throw e; } @@ -93,18 +102,12 @@ public class JGitEnvironmentRepositorySslTests { repository.findOne("bar", "staging", "master"); } - private static String[] configServerProperties(String... extraProperties) { - List properties = new ArrayList<>(Arrays.asList(extraProperties)); - properties.add("spring.cloud.config.server.git.uri=" + server.getSecureUri()); - properties.add("spring.cloud.config.server.git.username=agitter"); - properties.add("spring.cloud.config.server.git.password=letmein"); - return properties.toArray(new String[0]); - } - @Configuration @EnableConfigurationProperties(ConfigServerProperties.class) @Import({ PropertyPlaceholderAutoConfiguration.class, EnvironmentRepositoryConfiguration.class }) static class TestConfiguration { + } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryTests.java index b6db6999..6b4a639b 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,6 +63,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; + import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.server.support.AwsCodeCommitCredentialProvider; import org.springframework.cloud.config.server.support.GitSkipSslValidationCredentialsProvider; @@ -71,11 +72,7 @@ import org.springframework.cloud.config.server.test.ConfigServerTestUtils; import org.springframework.core.env.StandardEnvironment; import static junit.framework.TestCase.assertTrue; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; @@ -92,21 +89,22 @@ import static org.mockito.Mockito.when; */ public class JGitEnvironmentRepositoryTests { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + RefDatabase database = Mockito.mock(RefDatabase.class); + private StandardEnvironment environment = new StandardEnvironment(); + private JGitEnvironmentRepository repository; private File basedir = new File("target/config"); - - RefDatabase database = Mockito.mock(RefDatabase.class); - - @Rule - public final ExpectedException exception = ExpectedException.none(); - @Before public void init() throws Exception { String uri = ConfigServerTestUtils.prepareLocalRepo(); - this.repository = new JGitEnvironmentRepository(this.environment, new JGitEnvironmentProperties()); + this.repository = new JGitEnvironmentRepository(this.environment, + new JGitEnvironmentProperties()); this.repository.setUri(uri); if (this.basedir.exists()) { FileUtils.delete(this.basedir, FileUtils.RECURSIVE | FileUtils.RETRY); @@ -117,8 +115,9 @@ public class JGitEnvironmentRepositoryTests { public void vanilla() { this.repository.findOne("bar", "staging", "master"); Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -129,9 +128,9 @@ public class JGitEnvironmentRepositoryTests { this.repository.setSearchPaths(new String[] { "sub" }); this.repository.findOne("bar", "staging", "master"); Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/sub/application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/sub/application.yml"); assertVersion(environment); } @@ -142,16 +141,17 @@ public class JGitEnvironmentRepositoryTests { this.repository.setSearchPaths(new String[] { "{application}" }); this.repository.findOne("sub", "staging", "master"); Environment environment = this.repository.findOne("sub", "staging", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/sub/application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/sub/application.yml"); assertVersion(environment); } private void assertVersion(Environment environment) { String version = environment.getVersion(); - assertNotNull("version was null", version); - assertTrue("version length was wrong", version.length() >= 40 && version.length() <= 64); + assertThat(version).as("version was null").isNotNull(); + assertTrue("version length was wrong", + version.length() >= 40 && version.length() <= 64); } @Test @@ -161,9 +161,9 @@ public class JGitEnvironmentRepositoryTests { this.repository.setSearchPaths(new String[] { "sub*" }); this.repository.findOne("bar", "staging", "master"); Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/sub/application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/sub/application.yml"); assertVersion(environment); } @@ -171,8 +171,9 @@ public class JGitEnvironmentRepositoryTests { public void branch() { this.repository.setBasedir(this.basedir); Environment environment = this.repository.findOne("bar", "staging", "raw"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -180,8 +181,9 @@ public class JGitEnvironmentRepositoryTests { public void tag() { this.repository.setBasedir(this.basedir); Environment environment = this.repository.findOne("bar", "staging", "foo"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -190,45 +192,48 @@ public class JGitEnvironmentRepositoryTests { this.repository.setBasedir(this.basedir); this.repository.findOne("bar", "staging", "master"); Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @Test public void basedirExists() throws Exception { - assertTrue(this.basedir.mkdirs()); - assertTrue(new File(this.basedir, ".nothing").createNewFile()); + assertThat(this.basedir.mkdirs()).isTrue(); + assertThat(new File(this.basedir, ".nothing").createNewFile()).isTrue(); this.repository.setBasedir(this.basedir); this.repository.findOne("bar", "staging", "master"); Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @Test public void uriWithHostOnly() throws Exception { this.repository.setUri("git://localhost"); - assertEquals("git://localhost/", this.repository.getUri()); + assertThat(this.repository.getUri()).isEqualTo("git://localhost/"); } @Test public void uriWithHostAndPath() throws Exception { this.repository.setUri("git://localhost/foo/"); - assertEquals("git://localhost/foo", this.repository.getUri()); + assertThat(this.repository.getUri()).isEqualTo("git://localhost/foo"); } @Test - public void afterPropertiesSet_CloneOnStartTrue_CloneAndFetchCalled() throws Exception { + public void afterPropertiesSet_CloneOnStartTrue_CloneAndFetchCalled() + throws Exception { Git mockGit = mock(Git.class); CloneCommand mockCloneCommand = mock(CloneCommand.class); when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand); when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("http://somegitserver/somegitrepo"); envRepository.setCloneOnStart(true); @@ -237,15 +242,16 @@ public class JGitEnvironmentRepositoryTests { } @Test - public void afterPropertiesSet_CloneOnStartFalse_CloneAndFetchNotCalled() throws Exception { + public void afterPropertiesSet_CloneOnStartFalse_CloneAndFetchNotCalled() + throws Exception { Git mockGit = mock(Git.class); CloneCommand mockCloneCommand = mock(CloneCommand.class); when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand); when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("http://somegitserver/somegitrepo"); envRepository.afterPropertiesSet(); @@ -254,15 +260,16 @@ public class JGitEnvironmentRepositoryTests { } @Test - public void afterPropertiesSet_CloneOnStartTrueWithFileURL_CloneAndFetchNotCalled() throws Exception { + public void afterPropertiesSet_CloneOnStartTrueWithFileURL_CloneAndFetchNotCalled() + throws Exception { Git mockGit = mock(Git.class); CloneCommand mockCloneCommand = mock(CloneCommand.class); when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand); when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("file://somefilesystem/somegitrepo"); envRepository.setCloneOnStart(true); @@ -282,7 +289,8 @@ public class JGitEnvironmentRepositoryTests { when(git.status()).thenReturn(statusCommand); when(git.getRepository()).thenReturn(repository); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(false); @@ -292,7 +300,7 @@ public class JGitEnvironmentRepositoryTests { boolean shouldPull = repo.shouldPull(git); - assertThat("shouldPull was false", shouldPull, is(true)); + assertThat(shouldPull).as("shouldPull was false").isTrue(); } @Test @@ -306,7 +314,8 @@ public class JGitEnvironmentRepositoryTests { when(git.status()).thenReturn(statusCommand); when(git.getRepository()).thenReturn(repository); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(false); @@ -315,7 +324,7 @@ public class JGitEnvironmentRepositoryTests { boolean shouldPull = repo.shouldPull(git); - assertThat("shouldPull was true", shouldPull, is(false)); + assertThat(shouldPull).as("shouldPull was true").isFalse(); } @Test @@ -329,7 +338,8 @@ public class JGitEnvironmentRepositoryTests { when(git.status()).thenReturn(statusCommand); when(git.getRepository()).thenReturn(repository); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true); @@ -338,7 +348,7 @@ public class JGitEnvironmentRepositoryTests { boolean shouldPull = repo.shouldPull(git); - assertThat("shouldPull was false", shouldPull, is(true)); + assertThat(shouldPull).as("shouldPull was false").isTrue(); } @Test @@ -352,26 +362,28 @@ public class JGitEnvironmentRepositoryTests { when(git.status()).thenReturn(statusCommand); when(git.getRepository()).thenReturn(repository); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true); JGitEnvironmentProperties properties = new JGitEnvironmentProperties(); properties.setRefreshRate(2); - JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, properties); + JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, + properties); repo.setLastRefresh(System.currentTimeMillis() - 5000); boolean shouldPull = repo.shouldPull(git); - assertThat("shouldPull was false", shouldPull, is(true)); + assertThat(shouldPull).as("shouldPull was false").isTrue(); repo.setRefreshRate(30); shouldPull = repo.shouldPull(git); - assertThat("shouldPull was true", shouldPull, is(false)); + assertThat(shouldPull).as("shouldPull was true").isFalse(); } @Test @@ -389,20 +401,24 @@ public class JGitEnvironmentRepositoryTests { when(fetchCommand.call()).thenReturn(fetchResult); when(git.fetch()).thenReturn(fetchCommand); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true); JGitEnvironmentProperties properties = new JGitEnvironmentProperties(); properties.setRefreshRate(1000); - JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, properties); + JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, + properties); repo.setLastRefresh(0); repo.fetch(git, "master"); long timeDiff = System.currentTimeMillis() - repo.getLastRefresh(); - assertThat("time difference ("+timeDiff+") was longer than 1 second", timeDiff < 1000L, is(true)); + assertThat(timeDiff < 1000L) + .as("time difference (" + timeDiff + ") was longer than 1 second") + .isTrue(); } @Test @@ -423,7 +439,8 @@ public class JGitEnvironmentRepositoryTests { when(git.getRepository()).thenReturn(repository); StoredConfig storedConfig = mock(StoredConfig.class); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true); @@ -431,13 +448,14 @@ public class JGitEnvironmentRepositoryTests { FetchCommand fetchCommand = mock(FetchCommand.class); when(git.fetch()).thenReturn(fetchCommand); when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand); - when(fetchCommand.call()).thenThrow(new InvalidRemoteException("invalid mock remote")); // here - // is - // our - // exception - // we - // are - // testing + when(fetchCommand.call()) + .thenThrow(new InvalidRemoteException("invalid mock remote")); // here + // is + // our + // exception + // we + // are + // testing // refresh()->checkout CheckoutCommand checkoutCommand = mock(CheckoutCommand.class); @@ -465,13 +483,14 @@ public class JGitEnvironmentRepositoryTests { // refresh()->return // git.getRepository().findRef("HEAD").getObjectId().getName(); Ref headRef = mock(Ref.class); - when(database.getRef(anyString())).thenReturn(headRef); + when(this.database.getRef(anyString())).thenReturn(headRef); ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 }); when(headRef.getObjectId()).thenReturn(newObjectId); - SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", null); - assertEquals(locations.getVersion(), newObjectId.getName()); + SearchPathLocator.Locations locations = this.repository.getLocations("bar", + "staging", null); + assertThat(newObjectId.getName()).isEqualTo(locations.getVersion()); verify(git, times(0)).branchDelete(); } @@ -490,7 +509,7 @@ public class JGitEnvironmentRepositoryTests { @Override public RefDatabase getRefDatabase() { - return database; + return JGitEnvironmentRepositoryTests.this.database; } @Override @@ -521,14 +540,14 @@ public class JGitEnvironmentRepositoryTests { } @Test - public void testMergeException() throws Exception { + public void testMergeException() throws Exception { Git git = mock(Git.class); CloneCommand cloneCommand = mock(CloneCommand.class); MockGitFactory factory = new MockGitFactory(git, cloneCommand); this.repository.setGitFactory(factory); - //refresh()->shouldPull + // refresh()->shouldPull StatusCommand statusCommand = mock(StatusCommand.class); Status status = mock(Status.class); when(git.status()).thenReturn(statusCommand); @@ -536,21 +555,23 @@ public class JGitEnvironmentRepositoryTests { when(git.getRepository()).thenReturn(repository); StoredConfig storedConfig = mock(StoredConfig.class); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true); - //refresh()->fetch + // refresh()->fetch FetchCommand fetchCommand = mock(FetchCommand.class); FetchResult fetchResult = mock(FetchResult.class); when(git.fetch()).thenReturn(fetchCommand); when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand); when(fetchCommand.call()).thenReturn(fetchResult); - when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.emptyList()); + when(fetchResult.getTrackingRefUpdates()) + .thenReturn(Collections.emptyList()); - //refresh()->checkout + // refresh()->checkout CheckoutCommand checkoutCommand = mock(CheckoutCommand.class); - //refresh()->checkout->containsBranch + // refresh()->checkout->containsBranch ListBranchCommand listBranchCommand = mock(ListBranchCommand.class); when(git.checkout()).thenReturn(checkoutCommand); when(git.branchList()).thenReturn(listBranchCommand); @@ -560,35 +581,38 @@ public class JGitEnvironmentRepositoryTests { when(ref.getName()).thenReturn("/master"); when(listBranchCommand.call()).thenReturn(refs); - //refresh()->merge + // refresh()->merge MergeCommand mergeCommand = mock(MergeCommand.class); when(git.merge()).thenReturn(mergeCommand); - when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing + when(mergeCommand.call()).thenThrow(new NotMergedException()); // here is our + // exception we + // are testing - //refresh()->return git.getRepository().findRef("HEAD").getObjectId().getName(); + // refresh()->return git.getRepository().findRef("HEAD").getObjectId().getName(); Ref headRef = mock(Ref.class); - when(database.getRef(anyString())).thenReturn(headRef); + when(this.database.getRef(anyString())).thenReturn(headRef); - ObjectId newObjectId = ObjectId.fromRaw(new int[]{1,2,3,4,5}); + ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 }); when(headRef.getObjectId()).thenReturn(newObjectId); - SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master"); - assertEquals(locations.getVersion(),newObjectId.getName()); + SearchPathLocator.Locations locations = this.repository.getLocations("bar", + "staging", "master"); + assertThat(newObjectId.getName()).isEqualTo(locations.getVersion()); verify(git, times(0)).branchDelete(); - } - + } + @Test public void testRefreshWithoutFetch() throws Exception { Git git = mock(Git.class); - + CloneCommand cloneCommand = mock(CloneCommand.class); when(cloneCommand.setURI(anyString())).thenReturn(cloneCommand); when(cloneCommand.setDirectory(any(File.class))).thenReturn(cloneCommand); when(cloneCommand.call()).thenReturn(git); - + MockGitFactory factory = new MockGitFactory(git, cloneCommand); - + StatusCommand statusCommand = mock(StatusCommand.class); CheckoutCommand checkoutCommand = mock(CheckoutCommand.class); Status status = mock(Status.class); @@ -605,9 +629,11 @@ public class JGitEnvironmentRepositoryTests { when(git.getRepository()).thenReturn(repository); when(git.checkout()).thenReturn(checkoutCommand); when(git.fetch()).thenReturn(fetchCommand); - when(git.merge()).thenReturn(mock(MergeCommand.class, Mockito.RETURNS_DEEP_STUBS)); + when(git.merge()) + .thenReturn(mock(MergeCommand.class, Mockito.RETURNS_DEEP_STUBS)); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(checkoutCommand.call()).thenReturn(ref); when(listBranchCommand.call()).thenReturn(Arrays.asList(branch1Ref)); @@ -615,17 +641,19 @@ public class JGitEnvironmentRepositoryTests { when(branch1Ref.getName()).thenReturn("origin/master"); when(status.isClean()).thenReturn(true); - JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, new JGitEnvironmentProperties()); + JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, + new JGitEnvironmentProperties()); repo.setGitFactory(factory); repo.setUri("http://somegitserver/somegitrepo"); repo.setBasedir(this.basedir); - // Set the refresh rate to 2 seconds and last update before 100ms. There should be no remote repo fetch. + // Set the refresh rate to 2 seconds and last update before 100ms. There should be + // no remote repo fetch. repo.setLastRefresh(System.currentTimeMillis() - 100); repo.setRefreshRate(2); repo.refresh("master"); - + // Verify no fetch but merge only. verify(git, times(0)).fetch(); verify(git).merge(); @@ -647,7 +675,8 @@ public class JGitEnvironmentRepositoryTests { when(git.getRepository()).thenReturn(repository); StoredConfig storedConfig = mock(StoredConfig.class); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true).thenReturn(false); @@ -657,7 +686,8 @@ public class JGitEnvironmentRepositoryTests { when(git.fetch()).thenReturn(fetchCommand); when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand); when(fetchCommand.call()).thenReturn(fetchResult); - when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.emptyList()); + when(fetchResult.getTrackingRefUpdates()) + .thenReturn(Collections.emptyList()); // refresh()->checkout CheckoutCommand checkoutCommand = mock(CheckoutCommand.class); @@ -690,13 +720,14 @@ public class JGitEnvironmentRepositoryTests { // refresh()->return // git.getRepository().findRef("HEAD").getObjectId().getName(); Ref headRef = mock(Ref.class); - when(database.getRef(anyString())).thenReturn(headRef); + when(this.database.getRef(anyString())).thenReturn(headRef); ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 }); when(headRef.getObjectId()).thenReturn(newObjectId); - SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master"); - assertEquals(locations.getVersion(), newObjectId.getName()); + SearchPathLocator.Locations locations = this.repository.getLocations("bar", + "staging", "master"); + assertThat(newObjectId.getName()).isEqualTo(locations.getVersion()); verify(git, times(0)).branchDelete(); } @@ -708,21 +739,24 @@ public class JGitEnvironmentRepositoryTests { when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand); when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand); - when(mockCloneCommand.call()).thenThrow(new TransportException("failed to clone")); + when(mockCloneCommand.call()) + .thenThrow(new TransportException("failed to clone")); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("http://somegitserver/somegitrepo"); envRepository.setBasedir(this.basedir); try { envRepository.findOne("bar", "staging", "master"); - } catch (Exception ex) { + } + catch (Exception ex) { // expected - ignore } - assertFalse("baseDir should be deleted when clone fails", this.basedir.listFiles().length>0); + assertThat(this.basedir.listFiles().length > 0) + .as("baseDir should be deleted when clone fails").isFalse(); } @Test @@ -730,8 +764,8 @@ public class JGitEnvironmentRepositoryTests { Git mockGit = mock(Git.class); MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("git+ssh://git@somegitserver/somegitrepo"); envRepository.setBasedir(new File("./mybasedir")); @@ -742,18 +776,19 @@ public class JGitEnvironmentRepositoryTests { envRepository.setCloneOnStart(true); envRepository.afterPropertiesSet(); - assertTrue(mockCloneCommand.getCredentialsProvider() instanceof UsernamePasswordCredentialsProvider); + assertTrue(mockCloneCommand + .getCredentialsProvider() instanceof UsernamePasswordCredentialsProvider); CredentialsProvider provider = mockCloneCommand.getCredentialsProvider(); CredentialItem.Username usernameCredential = new CredentialItem.Username(); CredentialItem.Password passwordCredential = new CredentialItem.Password(); - assertTrue(provider.supports(usernameCredential)); - assertTrue(provider.supports(passwordCredential)); + assertThat(provider.supports(usernameCredential)).isTrue(); + assertThat(provider.supports(passwordCredential)).isTrue(); provider.get(new URIish(), usernameCredential); - assertEquals(usernameCredential.getValue(), username); + assertThat(username).isEqualTo(usernameCredential.getValue()); provider.get(new URIish(), passwordCredential); - assertEquals(String.valueOf(passwordCredential.getValue()), password); + assertThat(password).isEqualTo(String.valueOf(passwordCredential.getValue())); } @Test @@ -762,8 +797,8 @@ public class JGitEnvironmentRepositoryTests { Git mockGit = mock(Git.class); MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("git+ssh://git@somegitserver/somegitrepo"); envRepository.setBasedir(new File("./mybasedir")); @@ -771,28 +806,29 @@ public class JGitEnvironmentRepositoryTests { envRepository.setCloneOnStart(true); envRepository.afterPropertiesSet(); - assertTrue(mockCloneCommand.hasPassphraseCredentialsProvider()); + assertThat(mockCloneCommand.hasPassphraseCredentialsProvider()).isTrue(); CredentialsProvider provider = mockCloneCommand.getCredentialsProvider(); - assertFalse(provider.isInteractive()); + assertThat(provider.isInteractive()).isFalse(); - CredentialItem.StringType stringCredential = new CredentialItem.StringType(PassphraseCredentialsProvider.PROMPT, - true); + CredentialItem.StringType stringCredential = new CredentialItem.StringType( + PassphraseCredentialsProvider.PROMPT, true); - assertTrue(provider.supports(stringCredential)); + assertThat(provider.supports(stringCredential)).isTrue(); provider.get(new URIish(), stringCredential); - assertEquals(stringCredential.getValue(), passphrase); + assertThat(passphrase).isEqualTo(stringCredential.getValue()); } @Test - public void gitCredentialsProviderFactoryCreatesPassphraseProvider() throws Exception { + public void gitCredentialsProviderFactoryCreatesPassphraseProvider() + throws Exception { final String passphrase = "mypassphrase"; final String gitUri = "git+ssh://git@somegitserver/somegitrepo"; Git mockGit = mock(Git.class); MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri(gitUri); envRepository.setBasedir(new File("./mybasedir")); @@ -800,29 +836,30 @@ public class JGitEnvironmentRepositoryTests { envRepository.setCloneOnStart(true); envRepository.afterPropertiesSet(); - assertTrue(mockCloneCommand.hasPassphraseCredentialsProvider()); + assertThat(mockCloneCommand.hasPassphraseCredentialsProvider()).isTrue(); CredentialsProvider provider = mockCloneCommand.getCredentialsProvider(); - assertFalse(provider.isInteractive()); + assertThat(provider.isInteractive()).isFalse(); - CredentialItem.StringType stringCredential = new CredentialItem.StringType(PassphraseCredentialsProvider.PROMPT, - true); + CredentialItem.StringType stringCredential = new CredentialItem.StringType( + PassphraseCredentialsProvider.PROMPT, true); - assertTrue(provider.supports(stringCredential)); + assertThat(provider.supports(stringCredential)).isTrue(); provider.get(new URIish(), stringCredential); - assertEquals(stringCredential.getValue(), passphrase); + assertThat(passphrase).isEqualTo(stringCredential.getValue()); } @Test - public void gitCredentialsProviderFactoryCreatesUsernamePasswordProvider() throws Exception { + public void gitCredentialsProviderFactoryCreatesUsernamePasswordProvider() + throws Exception { Git mockGit = mock(Git.class); MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit); final String username = "someuser"; final String password = "mypassword"; - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("git+ssh://git@somegitserver/somegitrepo"); envRepository.setBasedir(new File("./mybasedir")); @@ -831,34 +868,37 @@ public class JGitEnvironmentRepositoryTests { envRepository.setCloneOnStart(true); envRepository.afterPropertiesSet(); - assertTrue(mockCloneCommand.getCredentialsProvider() instanceof UsernamePasswordCredentialsProvider); + assertTrue(mockCloneCommand + .getCredentialsProvider() instanceof UsernamePasswordCredentialsProvider); CredentialsProvider provider = mockCloneCommand.getCredentialsProvider(); CredentialItem.Username usernameCredential = new CredentialItem.Username(); CredentialItem.Password passwordCredential = new CredentialItem.Password(); - assertTrue(provider.supports(usernameCredential)); - assertTrue(provider.supports(passwordCredential)); + assertThat(provider.supports(usernameCredential)).isTrue(); + assertThat(provider.supports(passwordCredential)).isTrue(); provider.get(new URIish(), usernameCredential); - assertEquals(usernameCredential.getValue(), username); + assertThat(username).isEqualTo(usernameCredential.getValue()); provider.get(new URIish(), passwordCredential); - assertEquals(String.valueOf(passwordCredential.getValue()), password); + assertThat(password).isEqualTo(String.valueOf(passwordCredential.getValue())); } @Test - public void gitCredentialsProviderFactoryCreatesAwsCodeCommitProvider() throws Exception { + public void gitCredentialsProviderFactoryCreatesAwsCodeCommitProvider() + throws Exception { Git mockGit = mock(Git.class); MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit); final String awsUri = "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/test"; - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri(awsUri); envRepository.setCloneOnStart(true); envRepository.afterPropertiesSet(); - assertTrue(mockCloneCommand.getCredentialsProvider() instanceof AwsCodeCommitCredentialProvider); + assertTrue(mockCloneCommand + .getCredentialsProvider() instanceof AwsCodeCommitCredentialProvider); } @Test @@ -882,24 +922,24 @@ public class JGitEnvironmentRepositoryTests { CredentialsProvider provider = mockCloneCommand.getCredentialsProvider(); - assertTrue(provider instanceof GitSkipSslValidationCredentialsProvider); + assertThat(provider instanceof GitSkipSslValidationCredentialsProvider).isTrue(); CredentialItem.Username usernameCredential = new CredentialItem.Username(); CredentialItem.Password passwordCredential = new CredentialItem.Password(); - assertTrue(provider.supports(usernameCredential)); - assertTrue(provider.supports(passwordCredential)); + assertThat(provider.supports(usernameCredential)).isTrue(); + assertThat(provider.supports(passwordCredential)).isTrue(); provider.get(new URIish(), usernameCredential); - assertEquals(usernameCredential.getValue(), username); + assertThat(username).isEqualTo(usernameCredential.getValue()); provider.get(new URIish(), passwordCredential); - assertEquals(String.valueOf(passwordCredential.getValue()), password); + assertThat(password).isEqualTo(String.valueOf(passwordCredential.getValue())); } @Test public void shouldPrintStacktraceIfDebugEnabled() throws Exception { final Log mockLogger = mock(Log.class); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()) { + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()) { @Override public void afterPropertiesSet() throws Exception { this.logger = mockLogger; @@ -914,7 +954,8 @@ public class JGitEnvironmentRepositoryTests { verify(mockLogger).debug(eq("Stacktrace for: "), any(RuntimeException.class)); int numberOfInvocations = mockingDetails(mockLogger).getInvocations().size(); - assertEquals("should call isDebugEnabled warn and debug", 3, numberOfInvocations); + assertThat(numberOfInvocations).as("should call isDebugEnabled warn and debug") + .isEqualTo(3); } @Test @@ -929,8 +970,8 @@ public class JGitEnvironmentRepositoryTests { when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand); TransportConfigCallback configCallback = mock(TransportConfigCallback.class); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("http://somegitserver/somegitrepo"); envRepository.setTransportConfigCallback(configCallback); @@ -951,9 +992,10 @@ public class JGitEnvironmentRepositoryTests { when(mockGit.fetch()).thenReturn(fetchCommand); when(fetchCommand.call()).thenReturn(mock(FetchResult.class)); - JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, - new JGitEnvironmentProperties()); - envRepository.setGitFactory(new MockGitFactory(mockGit, mock(CloneCommand.class))); + JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository( + this.environment, new JGitEnvironmentProperties()); + envRepository + .setGitFactory(new MockGitFactory(mockGit, mock(CloneCommand.class))); envRepository.setUri("http://somegitserver/somegitrepo"); envRepository.setDeleteUntrackedBranches(true); @@ -979,7 +1021,8 @@ public class JGitEnvironmentRepositoryTests { when(git.getRepository()).thenReturn(repository); StoredConfig storedConfig = mock(StoredConfig.class); when(repository.getConfig()).thenReturn(storedConfig); - when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); + when(storedConfig.getString("remote", "origin", "url")) + .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true); @@ -988,7 +1031,8 @@ public class JGitEnvironmentRepositoryTests { FetchResult fetchResult = mock(FetchResult.class); TrackingRefUpdate trackingRefUpdate = mock(TrackingRefUpdate.class); - Collection trackingRefUpdates = Collections.singletonList(trackingRefUpdate); + Collection trackingRefUpdates = Collections + .singletonList(trackingRefUpdate); when(git.fetch()).thenReturn(fetchCommand); when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand); @@ -999,19 +1043,21 @@ public class JGitEnvironmentRepositoryTests { ReceiveCommand receiveCommand = mock(ReceiveCommand.class); when(trackingRefUpdate.asReceiveCommand()).thenReturn(receiveCommand); when(receiveCommand.getType()).thenReturn(ReceiveCommand.Type.DELETE); - when(trackingRefUpdate.getLocalName()).thenReturn("refs/remotes/origin/feature/deletedBranchFromOrigin"); + when(trackingRefUpdate.getLocalName()) + .thenReturn("refs/remotes/origin/feature/deletedBranchFromOrigin"); DeleteBranchCommand deleteBranchCommand = mock(DeleteBranchCommand.class); when(git.branchDelete()).thenReturn(deleteBranchCommand); - when(deleteBranchCommand.setBranchNames(eq("feature/deletedBranchFromOrigin"))).thenReturn(deleteBranchCommand); + when(deleteBranchCommand.setBranchNames(eq("feature/deletedBranchFromOrigin"))) + .thenReturn(deleteBranchCommand); when(deleteBranchCommand.setForce(true)).thenReturn(deleteBranchCommand); - when(deleteBranchCommand.call()).thenThrow(new NotMergedException());// here - // is - // our - // exception - // we - // are - // testing + when(deleteBranchCommand.call()).thenThrow(new NotMergedException()); // here + // is + // our + // exception + // we + // are + // testing // refresh()->checkout CheckoutCommand checkoutCommand = mock(CheckoutCommand.class); @@ -1037,13 +1083,14 @@ public class JGitEnvironmentRepositoryTests { // refresh()->return // git.getRepository().findRef("HEAD").getObjectId().getName(); Ref headRef = mock(Ref.class); - when(database.getRef(anyString())).thenReturn(headRef); + when(this.database.getRef(anyString())).thenReturn(headRef); - ObjectId newObjectId = ObjectId.fromRaw(new int[]{1, 2, 3, 4, 5}); + ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 }); when(headRef.getObjectId()).thenReturn(newObjectId); - SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master"); - assertEquals(locations.getVersion(), newObjectId.getName()); + SearchPathLocator.Locations locations = this.repository.getLocations("bar", + "staging", "master"); + assertThat(newObjectId.getName()).isEqualTo(locations.getVersion()); verify(deleteBranchCommand).setBranchNames(eq("feature/deletedBranchFromOrigin")); verify(deleteBranchCommand).setForce(true); @@ -1051,32 +1098,35 @@ public class JGitEnvironmentRepositoryTests { } class MockCloneCommand extends CloneCommand { + private Git mockGit; - public MockCloneCommand(Git mockGit) { + MockCloneCommand(Git mockGit) { this.mockGit = mockGit; } @Override public Git call() throws GitAPIException, InvalidRemoteException { - return mockGit; + return this.mockGit; } public boolean hasPassphraseCredentialsProvider() { - return credentialsProvider instanceof PassphraseCredentialsProvider; + return this.credentialsProvider instanceof PassphraseCredentialsProvider; } public CredentialsProvider getCredentialsProvider() { - return credentialsProvider; + return this.credentialsProvider; } + } class MockGitFactory extends JGitEnvironmentRepository.JGitFactory { private Git mockGit; + private CloneCommand mockCloneCommand; - public MockGitFactory(Git mockGit, CloneCommand mockCloneCommand) { + MockGitFactory(Git mockGit, CloneCommand mockCloneCommand) { this.mockGit = mockGit; this.mockCloneCommand = mockCloneCommand; } @@ -1090,5 +1140,7 @@ public class JGitEnvironmentRepositoryTests { public CloneCommand getCloneCommandByCloneRepository() { return this.mockCloneCommand; } + } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java index 201818db..4c3b8536 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,8 @@ public class JdbcEnvironmentRepositoryTests { @Test public void basicProperties() { - Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(dataSource), new JdbcEnvironmentProperties()) - .findOne("foo", "bar", ""); + Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), + new JdbcEnvironmentProperties()).findOne("foo", "bar", ""); assertThat(env.getName()).isEqualTo("foo"); assertThat(env.getProfiles()).isEqualTo(new String[] { "default", "bar" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -66,8 +66,8 @@ public class JdbcEnvironmentRepositoryTests { @Test public void defaults() { - Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(dataSource), new JdbcEnvironmentProperties()) - .findOne("application", "", ""); + Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), + new JdbcEnvironmentProperties()).findOne("application", "", ""); assertThat(env.getName()).isEqualTo("application"); assertThat(env.getProfiles()).isEqualTo(new String[] { "default" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -77,6 +77,7 @@ public class JdbcEnvironmentRepositoryTests { @Configuration protected static class ApplicationConfiguration { + } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.java index fb5c88fd..203d4a3c 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.HashMap; @@ -28,9 +29,7 @@ import org.springframework.cloud.config.server.environment.SearchPathLocator.Loc import org.springframework.cloud.config.server.test.ConfigServerTestUtils; import org.springframework.core.env.StandardEnvironment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -39,8 +38,9 @@ import static org.junit.Assert.assertTrue; public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { private StandardEnvironment environment = new StandardEnvironment(); - private MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository(this.environment, - new MultipleJGitEnvironmentProperties()); + + private MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository( + this.environment, new MultipleJGitEnvironmentProperties()); @Before public void init() throws Exception { @@ -73,9 +73,9 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { @Test public void defaultRepo() { Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -83,10 +83,10 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { public void missingRepo() { Environment environment = this.repository.findOne("missing-config-repo", "staging", "master"); - assertEquals("Wrong property sources: " + environment, 1, - environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()) + .as("Wrong property sources: " + environment).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/application.yml"); assertVersion(environment); } @@ -94,11 +94,10 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { public void mappingRepo() { Environment environment = this.repository.findOne("test1-config-repo", "staging", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals( - getUri("*").replace("{application}", "test1-config-repo") - + "/application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(getUri("*").replace("{application}", "test1-config-repo") + + "/application.yml"); assertVersion(environment); } @@ -106,11 +105,10 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { public void otherMappingRepo() { Environment environment = this.repository.findOne("test2-config-repo", "staging", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals( - getUri("*").replace("{application}", "test2-config-repo") - + "/application.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(getUri("*").replace("{application}", "test2-config-repo") + + "/application.properties"); assertVersion(environment); } @@ -120,15 +118,15 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { this.repository.setSearchPaths("{profile}"); Locations locations = this.repository.getLocations("foo", "dev,one,two", "master"); - assertEquals(3, locations.getLocations().length); - assertEquals("classpath:/test/dev/", locations.getLocations()[0]); + assertThat(locations.getLocations().length).isEqualTo(3); + assertThat(locations.getLocations()[0]).isEqualTo("classpath:/test/dev/"); } private void assertVersion(Environment environment) { String version = environment.getVersion(); - assertNotNull("version was null", version); - assertTrue("version length was wrong", - version.length() >= 40 && version.length() <= 64); + assertThat(version).as("version was null").isNotNull(); + assertThat(version.length() >= 40 && version.length() <= 64) + .as("version length was wrong").isTrue(); } private String getUri(String pattern) { @@ -147,4 +145,5 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { return uri; } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentLabelPlaceholderRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentLabelPlaceholderRepositoryTests.java index 759cda18..ab83d384 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentLabelPlaceholderRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentLabelPlaceholderRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,8 +12,8 @@ * WITHOUT 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.springframework.cloud.config.server.environment; import org.junit.Before; @@ -23,9 +23,7 @@ import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.server.test.ConfigServerTestUtils; import org.springframework.core.env.StandardEnvironment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb @@ -35,21 +33,25 @@ import static org.junit.Assert.assertTrue; public class MultipleJGitEnvironmentLabelPlaceholderRepositoryTests { private StandardEnvironment environment = new StandardEnvironment(); - private MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository(this.environment, - new MultipleJGitEnvironmentProperties()); + + private MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository( + this.environment, new MultipleJGitEnvironmentProperties()); + private String defaultUri; @Before public void init() throws Exception { - this.defaultUri = ConfigServerTestUtils.prepareLocalRepo("master-labeltest-config-repo"); - this.repository.setUri(defaultUri.replace("master-", "{label}-")); + this.defaultUri = ConfigServerTestUtils + .prepareLocalRepo("master-labeltest-config-repo"); + this.repository.setUri(this.defaultUri.replace("master-", "{label}-")); } + @Test public void defaultRepo() { Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals(this.defaultUri + "application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.defaultUri + "application.yml"); assertVersion(environment); } @@ -57,27 +59,27 @@ public class MultipleJGitEnvironmentLabelPlaceholderRepositoryTests { public void missingRepo() { Environment environment = this.repository.findOne("missing-config-repo", "staging", "master"); - assertEquals("Wrong property sources: " + environment, 1, - environment.getPropertySources().size()); - assertEquals(this.defaultUri + "application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()) + .as("Wrong property sources: " + environment).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.defaultUri + "application.yml"); assertVersion(environment); } @Test public void defaultLabelRepo() { Environment environment = this.repository.findOne("bar", "staging", null); - assertEquals(1, environment.getPropertySources().size()); - assertEquals(this.defaultUri + "application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.defaultUri + "application.yml"); assertVersion(environment); } private void assertVersion(Environment environment) { String version = environment.getVersion(); - assertNotNull("version was null", version); - assertTrue("version length was wrong", - version.length() >= 40 && version.length() <= 64); + assertThat(version).as("version was null").isNotNull(); + assertThat(version.length() >= 40 && version.length() <= 64) + .as("version length was wrong").isTrue(); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.java index 8d1a527b..6f5a9b66 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.File; @@ -30,12 +31,7 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.StringUtils; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -44,8 +40,9 @@ import static org.junit.Assert.assertTrue; public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { private StandardEnvironment environment = new StandardEnvironment(); - private MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository(this.environment, - new MultipleJGitEnvironmentProperties()); + + private MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository( + this.environment, new MultipleJGitEnvironmentProperties()); @Before public void init() throws Exception { @@ -80,9 +77,9 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { @Test public void defaultRepo() { Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -90,24 +87,23 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { public void mappingRepo() { Environment environment = this.repository.findOne("application", "test1-config-repo", "master"); - assertEquals(1, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); String uri = getUri("*").replace("{profile}", "test1-config-repo"); - assertEquals(uri + "/application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(uri + "/application.yml"); assertVersion(environment); - assertThat(StringUtils.cleanPath(getRepository(uri).getBasedir().toString()), - containsString("target/repos")); + assertThat(StringUtils.cleanPath(getRepository(uri).getBasedir().toString())) + .contains("target/repos"); } @Test public void otherMappingRepo() { Environment environment = this.repository.findOne("application", "test2-config-repo", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals( - getUri("*").replace("{profile}", "test2-config-repo") - + "/application.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(getUri("*").replace("{profile}", "test2-config-repo") + + "/application.properties"); assertVersion(environment); } @@ -115,52 +111,49 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { public void locationsTwoProfiles() throws Exception { Locations locations = this.repository.getLocations("application", "test1-config-repo,test2-config-repo", "master"); - assertEquals(1, locations.getLocations().length); - assertEquals( - new File(getUri("*").replace("{profile}", "test2-config-repo") - .replace("file:", "")).getCanonicalPath(), - new File(locations.getLocations()[0].replace("file:", "")) - .getCanonicalPath()); + assertThat(locations.getLocations().length).isEqualTo(1); + assertThat(new File(locations.getLocations()[0].replace("file:", "")) + .getCanonicalPath()).isEqualTo( + new File(getUri("*").replace("{profile}", "test2-config-repo") + .replace("file:", "")).getCanonicalPath()); } @Test public void locationsMissingProfile() throws Exception { Locations locations = this.repository.getLocations("application", "not-there,another-not-there", "master"); - assertEquals(1, locations.getLocations().length); - assertEquals( - new File(this.repository.getUri().replace("file:", "")) - .getCanonicalPath(), - new File(locations.getLocations()[0].replace("file:", "")) - .getCanonicalPath()); + assertThat(locations.getLocations().length).isEqualTo(1); + assertThat(new File(locations.getLocations()[0].replace("file:", "")) + .getCanonicalPath()) + .isEqualTo(new File(this.repository.getUri().replace("file:", "")) + .getCanonicalPath()); } @Test public void twoMappingRepos() { Environment environment = this.repository.findOne("application", "test1-config-repo,test2-config-repo,missing-config-repo", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals( - getUri("*").replace("{profile}", "test2-config-repo") - + "/application.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(getUri("*").replace("{profile}", "test2-config-repo") + + "/application.properties"); assertVersion(environment); - assertArrayEquals(environment.getProfiles(), new String[] { "test1-config-repo", - "test2-config-repo", "missing-config-repo" }); + assertThat(new String[] { "test1-config-repo", "test2-config-repo", + "missing-config-repo" }).isEqualTo(environment.getProfiles()); } @SuppressWarnings("unchecked") private JGitEnvironmentRepository getRepository(String uri) { Map repos = (Map) ReflectionTestUtils - .getField(repository, "placeholders"); + .getField(this.repository, "placeholders"); return repos.get(uri); } private void assertVersion(Environment environment) { String version = environment.getVersion(); - assertNotNull("version was null", version); - assertTrue("version length was wrong", - version.length() >= 40 && version.length() <= 64); + assertThat(version).as("version was null").isNotNull(); + assertThat(version.length() >= 40 && version.length() <= 64) + .as("version length was wrong").isTrue(); } private String getUri(String pattern) { @@ -179,4 +172,5 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { return uri; } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryIntegrationTests.java index 7768f7ac..560b8167 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.cloud.config.server.environment; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; - import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; @@ -45,6 +42,9 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.containsString; + /** * @author Andy Chan (iceycake) * @author Dave Syer @@ -52,13 +52,13 @@ import org.springframework.context.annotation.Import; */ public class MultipleJGitEnvironmentRepositoryIntegrationTests { + @Rule + public ExpectedException expected = ExpectedException.none(); + private ConfigurableApplicationContext context; private File basedir = new File("target/config"); - @Rule - public ExpectedException expected = ExpectedException.none(); - @Before public void init() throws Exception { if (this.basedir.exists()) { @@ -84,7 +84,7 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test @@ -103,7 +103,7 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { .getBean(EnvironmentRepository.class); repository.findOne("test1-svc", "staging", "master"); Environment environment = repository.findOne("test1-svc", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test @@ -115,15 +115,17 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern", "*test1*"); repoMapping.put("spring.cloud.config.server.git.repos[test1].uri", test1RepoUri); repoMapping.put("spring.cloud.config.server.git.refresh-rate", "30"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) .properties(repoMapping).run(); EnvironmentRepository repository = this.context .getBean(EnvironmentRepository.class); repository.findOne("test1-svc", "staging", "master"); Environment environment = repository.findOne("test1-svc", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(((MultipleJGitEnvironmentRepository) repository).getRepos().get("test1").getRefreshRate(), 30); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(30).isEqualTo(((MultipleJGitEnvironmentRepository) repository) + .getRepos().get("test1").getRefreshRate()); } @Test @@ -143,7 +145,7 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { .getBean(EnvironmentRepository.class); repository.findOne("test1-svc", "staging", "master"); Environment environment = repository.findOne("test1-svc", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test @@ -164,7 +166,7 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { repository.findOne("test1-svc", "staging", "master"); Environment environment = repository.findOne("test1-svc", "staging,cloud", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test @@ -189,9 +191,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { repository.findOne("test1-svc", "staging", "master"); Environment environment = repository.findOne("test1-svc", "cloud,staging", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); environment = repository.findOne("test1-svc", "staging,cloud", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test @@ -200,7 +202,8 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { String test1RepoUri = ConfigServerTestUtils.prepareLocalRepo("test1-config-repo"); Map repoMapping = new LinkedHashMap(); - repoMapping.put("spring.cloud.config.server.git.repos.test1-svc.uri", test1RepoUri); + repoMapping.put("spring.cloud.config.server.git.repos.test1-svc.uri", + test1RepoUri); this.context = new SpringApplicationBuilder(TestConfiguration.class) .web(WebApplicationType.NONE) .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) @@ -209,15 +212,16 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { .getBean(EnvironmentRepository.class); repository.findOne("test1-svc", "staging", "master"); Environment environment = repository.findOne("test1-svc", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test public void nonWritableBasedir() throws IOException { String defaultRepoUri = ConfigServerTestUtils.prepareLocalRepo("config-repo"); - expected.expectCause(ThrowableMessageMatcher + this.expected.expectCause(ThrowableMessageMatcher .hasMessage(containsString("Cannot write parent"))); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + this.context = new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE) .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri, "spring.cloud.config.server.git.basedir:/tmp") .run(); @@ -234,9 +238,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { "spring.cloud.config.server.git.uri:" + defaultRepoUri) .run(); - MultipleJGitEnvironmentProperties properties = this.context.getBean(MultipleJGitEnvironmentProperties.class); - Assertions.assertThat(properties.getRepos()).hasSize(1) - .containsOnlyKeys("admin"); + MultipleJGitEnvironmentProperties properties = this.context + .getBean(MultipleJGitEnvironmentProperties.class); + Assertions.assertThat(properties.getRepos()).hasSize(1).containsOnlyKeys("admin"); } @Configuration @@ -244,6 +248,7 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { @Import({ PropertyPlaceholderAutoConfiguration.class, EnvironmentRepositoryConfiguration.class }) protected static class TestConfiguration { + } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryTests.java index e243340c..35335b22 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.File; @@ -34,12 +35,6 @@ import org.springframework.cloud.config.server.test.ConfigServerTestUtils; import org.springframework.core.env.StandardEnvironment; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -56,8 +51,8 @@ public class MultipleJGitEnvironmentRepositoryTests { public ExpectedException exception = ExpectedException.none(); private StandardEnvironment environment = new StandardEnvironment(); - private MultipleJGitEnvironmentRepository repository; + private MultipleJGitEnvironmentRepository repository; @Before public void init() throws Exception { @@ -91,17 +86,17 @@ public class MultipleJGitEnvironmentRepositoryTests { @Test public void defaultRepo() { Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } private void assertVersion(Environment environment) { String version = environment.getVersion(); - assertNotNull("version was null", version); - assertTrue("version length was wrong", - version.length() >= 40 && version.length() <= 64); + assertThat(version).as("version was null").isNotNull(); + assertThat(version.length() >= 40 && version.length() <= 64) + .as("version length was wrong").isTrue(); } @Test @@ -111,27 +106,27 @@ public class MultipleJGitEnvironmentRepositoryTests { this.repository.setSearchPaths(new String[] { "sub" }); this.repository.findOne("bar", "staging", "master"); Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/sub/application.yml", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/sub/application.yml"); assertVersion(environment); } @Test public void defaultRepoBranch() { Environment environment = this.repository.findOne("bar", "staging", "raw"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @Test public void defaultRepoTag() { Environment environment = this.repository.findOne("bar", "staging", "foo"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -139,27 +134,27 @@ public class MultipleJGitEnvironmentRepositoryTests { public void defaultRepoTwice() { this.repository.findOne("bar", "staging", "master"); Environment environment = this.repository.findOne("bar", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @Test public void defaultRepoBasedir() { - repository.setBasedir(new File("target/testBase")); - assertThat(repository.getBasedir().toString(), containsString("target/testBase")); - assertThat(repository.getRepos().get("test1").getBasedir().toString(), - containsString("/test1")); + this.repository.setBasedir(new File("target/testBase")); + assertThat(this.repository.getBasedir().toString()).contains("target/testBase"); + assertThat(this.repository.getRepos().get("test1").getBasedir().toString()) + .contains("/test1"); } @Test public void mappingRepo() { Environment environment = this.repository.findOne("test1-svc", "staging", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(getUri("*test1*") + "/test1-svc.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(getUri("*test1*") + "/test1-svc.properties"); assertVersion(environment); } @@ -167,20 +162,20 @@ public class MultipleJGitEnvironmentRepositoryTests { public void defaultLabel() { this.repository.setDefaultLabel("raw"); Environment environment = this.repository.findOne("bar", "staging", null); - assertEquals("raw", environment.getLabel()); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(this.repository.getUri() + "/bar.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getLabel()).isEqualTo("raw"); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @Test public void mappingRepoWithDefaultLabel() { Environment environment = this.repository.findOne("test1-svc", "staging", null); - assertEquals("master", environment.getLabel()); - assertEquals(2, environment.getPropertySources().size()); - assertEquals(getUri("*test1*") + "/test1-svc.properties", - environment.getPropertySources().get(0).getName()); + assertThat(environment.getLabel()).isEqualTo("master"); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName()) + .isEqualTo(getUri("*test1*") + "/test1-svc.properties"); assertVersion(environment); } @@ -189,9 +184,11 @@ public class MultipleJGitEnvironmentRepositoryTests { TransportConfigCallback mockCallback1 = mock(TransportConfigCallback.class); TransportConfigCallback mockCallback2 = mock(TransportConfigCallback.class); - PatternMatchingJGitEnvironmentRepository repo1 = createRepository("test1", "*test1*", "test1Uri"); + PatternMatchingJGitEnvironmentRepository repo1 = createRepository("test1", + "*test1*", "test1Uri"); - PatternMatchingJGitEnvironmentRepository repo2 = createRepository("test2", "*test2*", "test2Uri"); + PatternMatchingJGitEnvironmentRepository repo2 = createRepository("test2", + "*test2*", "test2Uri"); repo2.setTransportConfigCallback(mockCallback2); Map repos = new HashMap<>(); @@ -202,8 +199,8 @@ public class MultipleJGitEnvironmentRepositoryTests { this.repository.setTransportConfigCallback(mockCallback1); this.repository.afterPropertiesSet(); - assertEquals(repo1.getTransportConfigCallback(), mockCallback1); - assertEquals(repo2.getTransportConfigCallback(), mockCallback2); + assertThat(mockCallback1).isEqualTo(repo1.getTransportConfigCallback()); + assertThat(mockCallback2).isEqualTo(repo2.getTransportConfigCallback()); } @Test @@ -232,22 +229,24 @@ public class MultipleJGitEnvironmentRepositoryTests { this.repository.setPassphrase(multiRepoPassphrase); this.repository.afterPropertiesSet(); - assertEquals("Repo1 has its own username which should not be overwritten", - repo1.getUsername(), repo1Username); - assertEquals("Repo1 has its own password which should not be overwritten", - repo1.getPassword(), repo1Password); - assertEquals( - "Repo1 did not specify a passphrase so this should have been copied from the multi repo", - repo1.getPassphrase(), multiRepoPassphrase); - assertEquals( - "Repo2 did not specify a username so this should have been copied from the multi repo", - repo2.getUsername(), multiRepoUsername); - assertEquals( - "Repo2 did not specify a username so this should have been copied from the multi repo", - repo2.getPassword(), multiRepoPassword); - assertEquals( - "Repo2 has its own passphrase which should not have been overwritten", - repo2.getPassphrase(), repo2Passphrase); + assertThat(repo1Username) + .as("Repo1 has its own username which should not be overwritten") + .isEqualTo(repo1.getUsername()); + assertThat(repo1Password) + .as("Repo1 has its own password which should not be overwritten") + .isEqualTo(repo1.getPassword()); + assertThat(multiRepoPassphrase).as( + "Repo1 did not specify a passphrase so this should have been copied from the multi repo") + .isEqualTo(repo1.getPassphrase()); + assertThat(multiRepoUsername).as( + "Repo2 did not specify a username so this should have been copied from the multi repo") + .isEqualTo(repo2.getUsername()); + assertThat(multiRepoPassword).as( + "Repo2 did not specify a username so this should have been copied from the multi repo") + .isEqualTo(repo2.getPassword()); + assertThat(repo2Passphrase) + .as("Repo2 has its own passphrase which should not have been overwritten") + .isEqualTo(repo2.getPassphrase()); } @Test @@ -268,21 +267,21 @@ public class MultipleJGitEnvironmentRepositoryTests { this.repository.setRepos(repos); this.repository.setSkipSslValidation(false); this.repository.afterPropertiesSet(); - assertFalse( - "If skip SSL validation is false at multi-repo level, then per-repo settings take priority", - repo1.isSkipSslValidation()); - assertTrue( - "If skip SSL validation is false at multi-repo level, then per-repo settings take priority", - repo2.isSkipSslValidation()); + assertThat(repo1.isSkipSslValidation()).as( + "If skip SSL validation is false at multi-repo level, then per-repo settings take priority") + .isFalse(); + assertThat(repo2.isSkipSslValidation()).as( + "If skip SSL validation is false at multi-repo level, then per-repo settings take priority") + .isTrue(); this.repository.setSkipSslValidation(true); this.repository.afterPropertiesSet(); - assertTrue( - "If explicitly set to skip SSL validation at the multi-repo level, then apply same setting to sub-repos", - repo1.isSkipSslValidation()); - assertTrue( - "If explicitly set to skip SSL validation at the multi-repo level, then apply same setting to sub-repos", - repo2.isSkipSslValidation()); + assertThat(repo1.isSkipSslValidation()).as( + "If explicitly set to skip SSL validation at the multi-repo level, then apply same setting to sub-repos") + .isTrue(); + assertThat(repo2.isSkipSslValidation()).as( + "If explicitly set to skip SSL validation at the multi-repo level, then apply same setting to sub-repos") + .isTrue(); } @Test @@ -302,7 +301,8 @@ public class MultipleJGitEnvironmentRepositoryTests { @Test // test for gh-700 - public void exceptionThrownIfBasedirDoesnotExistAndCannotBeCreated() throws Exception { + public void exceptionThrownIfBasedirDoesnotExistAndCannotBeCreated() + throws Exception { File basedir = mock(File.class); File absoluteBasedir = mock(File.class); when(basedir.getAbsoluteFile()).thenReturn(absoluteBasedir); @@ -334,4 +334,5 @@ public class MultipleJGitEnvironmentRepositoryTests { return uri; } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryFactoryTest.java index 3c7ce758..f0a5e1ab 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.junit.Test; + import org.springframework.cloud.config.server.config.ConfigServerProperties; import org.springframework.core.env.StandardEnvironment; -import static org.junit.Assert.assertEquals; - +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter @@ -31,21 +32,25 @@ public class NativeEnvironmentRepositoryFactoryTest { public void testDefaultLabel() { ConfigServerProperties props = new ConfigServerProperties(); props.setDefaultLabel("mylabel"); - NativeEnvironmentRepositoryFactory factory = new NativeEnvironmentRepositoryFactory(new StandardEnvironment(), props); + NativeEnvironmentRepositoryFactory factory = new NativeEnvironmentRepositoryFactory( + new StandardEnvironment(), props); NativeEnvironmentProperties environmentProperties = new NativeEnvironmentProperties(); NativeEnvironmentRepository repo = factory.build(environmentProperties); - assertEquals("mylabel", repo.getDefaultLabel()); + assertThat(repo.getDefaultLabel()).isEqualTo("mylabel"); - factory = new NativeEnvironmentRepositoryFactory(new StandardEnvironment(), props); + factory = new NativeEnvironmentRepositoryFactory(new StandardEnvironment(), + props); environmentProperties = new NativeEnvironmentProperties(); environmentProperties.setDefaultLabel("mynewlabel"); repo = factory.build(environmentProperties); - assertEquals("mylabel", repo.getDefaultLabel()); + assertThat(repo.getDefaultLabel()).isEqualTo("mylabel"); - factory = new NativeEnvironmentRepositoryFactory(new StandardEnvironment(), new ConfigServerProperties()); + factory = new NativeEnvironmentRepositoryFactory(new StandardEnvironment(), + new ConfigServerProperties()); environmentProperties = new NativeEnvironmentProperties(); environmentProperties.setDefaultLabel("mynewlabel"); repo = factory.build(environmentProperties); - assertEquals("mynewlabel", repo.getDefaultLabel()); + assertThat(repo.getDefaultLabel()).isEqualTo("mynewlabel"); } -} \ No newline at end of file + +} diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryTests.java index 4c88fc73..bd05a713 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.junit.Before; @@ -24,8 +25,7 @@ import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.server.environment.SearchPathLocator.Locations; import org.springframework.context.ConfigurableApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -42,7 +42,8 @@ public class NativeEnvironmentRepositoryTests { ConfigurableApplicationContext context = new SpringApplicationBuilder( NativeEnvironmentRepositoryTests.class).web(WebApplicationType.NONE) .run(); - this.repository = new NativeEnvironmentRepository(context.getEnvironment(), new NativeEnvironmentProperties()); + this.repository = new NativeEnvironmentRepository(context.getEnvironment(), + new NativeEnvironmentProperties()); this.repository.setVersion("myversion"); this.repository.setDefaultLabel(null); context.close(); @@ -52,103 +53,108 @@ public class NativeEnvironmentRepositoryTests { public void emptySearchLocations() { this.repository.setSearchLocations((String[]) null); Environment environment = this.repository.findOne("foo", "development", "master"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test public void vanilla() { Environment environment = this.repository.findOne("foo", "development", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals("version was wrong", "myversion", environment.getVersion()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getVersion()).as("version was wrong") + .isEqualTo("myversion"); } @Test public void ignoresExistingProfile() { System.setProperty("spring.profiles.active", "cloud"); Environment environment = this.repository.findOne("foo", "main", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals("version was wrong", "myversion", environment.getVersion()); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getVersion()).as("version was wrong") + .isEqualTo("myversion"); } @Test public void prefixed() { this.repository.setSearchLocations("classpath:/test"); Environment environment = this.repository.findOne("foo", "development", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals("version was wrong", "myversion", environment.getVersion()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getVersion()).as("version was wrong") + .isEqualTo("myversion"); } @Test public void prefixedWithFile() { this.repository.setSearchLocations("file:./src/test/resources/test"); Environment environment = this.repository.findOne("foo", "development", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals("version was wrong", "myversion", environment.getVersion()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getVersion()).as("version was wrong") + .isEqualTo("myversion"); } @Test public void labelled() { this.repository.setSearchLocations("classpath:/test"); Environment environment = this.repository.findOne("foo", "development", "dev"); - assertEquals(3, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(3); // position 1 because it has higher precedence than anything except the // foo-development.properties - assertEquals("dev_bar", - environment.getPropertySources().get(1).getSource().get("foo")); - assertEquals("version was wrong", "myversion", environment.getVersion()); + assertThat(environment.getPropertySources().get(1).getSource().get("foo")) + .isEqualTo("dev_bar"); + assertThat(environment.getVersion()).as("version was wrong") + .isEqualTo("myversion"); } @Test public void placeholdersLabel() { this.repository.setSearchLocations("classpath:/test/{label}/"); Environment environment = this.repository.findOne("foo", "development", "dev"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals("dev_bar", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("dev_bar"); } @Test public void placeholdersProfile() { this.repository.setSearchLocations("classpath:/test/{profile}/"); Environment environment = this.repository.findOne("foo", "dev", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals("dev_bar", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("dev_bar"); } @Test public void placeholdersProfiles() { this.repository.setSearchLocations("classpath:/test/{profile}/"); Environment environment = this.repository.findOne("foo", "dev,mysql", "master"); - assertEquals(2, environment.getPropertySources().size()); - assertEquals("mysql", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("mysql"); } @Test public void placeholdersApplicationAndProfile() { this.repository.setSearchLocations("classpath:/test/{profile}/{application}/"); Environment environment = this.repository.findOne("app", "dev", "master"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals("app", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("app"); } @Test public void locationPlaceholdersApplication() { this.repository.setSearchLocations("classpath:/test/{application}"); Locations locations = this.repository.getLocations("foo", "dev", "master"); - assertEquals(1, locations.getLocations().length); - assertEquals("classpath:/test/foo/", locations.getLocations()[0]); + assertThat(locations.getLocations().length).isEqualTo(1); + assertThat(locations.getLocations()[0]).isEqualTo("classpath:/test/foo/"); } @Test public void locationPlaceholdersMultipleApplication() { this.repository.setSearchLocations("classpath:/test/{application}"); Locations locations = this.repository.getLocations("foo,bar", "dev", "master"); - assertEquals(2, locations.getLocations().length); - assertEquals("classpath:/test/foo/", locations.getLocations()[0]); - assertEquals("classpath:/test/bar/", locations.getLocations()[1]); + assertThat(locations.getLocations().length).isEqualTo(2); + assertThat(locations.getLocations()[0]).isEqualTo("classpath:/test/foo/"); + assertThat(locations.getLocations()[1]).isEqualTo("classpath:/test/bar/"); } @Test @@ -156,35 +162,35 @@ public class NativeEnvironmentRepositoryTests { this.repository.setSearchLocations("classpath:/test/{profile}"); Locations locations = this.repository.getLocations("foo", "dev,one,two", "master"); - assertEquals(3, locations.getLocations().length); - assertEquals("classpath:/test/dev/", locations.getLocations()[0]); + assertThat(locations.getLocations().length).isEqualTo(3); + assertThat(locations.getLocations()[0]).isEqualTo("classpath:/test/dev/"); } @Test public void placeholdersNoTrailingSlash() { this.repository.setSearchLocations("classpath:/test/{label}"); Environment environment = this.repository.findOne("foo", "development", "dev"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals("dev_bar", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("dev_bar"); } @Test public void locationAddLabelLocations() { this.repository.setSearchLocations("classpath:/test/dev/"); Environment environment = this.repository.findOne("foo", "development", "ignore"); - assertEquals(2, environment.getPropertySources().size()); - assertNotEquals("dev_bar", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isNotEqualTo("dev_bar"); } @Test public void tryToStartReactive() { this.repository.setSearchLocations("classpath:/test/reactive/"); Environment environment = this.repository.findOne("foo", "master", "default"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals("reactive", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("reactive"); } @Test @@ -192,9 +198,9 @@ public class NativeEnvironmentRepositoryTests { this.repository.setSearchLocations("classpath:/test/dev/"); this.repository.setAddLabelLocations(false); Environment environment = this.repository.findOne("foo", "development", "ignore"); - assertEquals(1, environment.getPropertySources().size()); - assertEquals("dev_bar", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("dev_bar"); } @Test @@ -202,14 +208,14 @@ public class NativeEnvironmentRepositoryTests { this.repository.setSearchLocations("classpath:/test/{profile}", "classpath:/test/dev"); Locations locations = this.repository.getLocations("foo", "dev", null); - assertEquals(1, locations.getLocations().length); + assertThat(locations.getLocations().length).isEqualTo(1); } @Test public void testDefaultLabel() { this.repository.setDefaultLabel("test"); - assertEquals("test_bar", this.repository.findOne("foo", "default", null) - .getPropertySources().get(0).getSource().get("foo")); + assertThat(this.repository.findOne("foo", "default", null).getPropertySources() + .get(0).getSource().get("foo")).isEqualTo("test_bar"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryIntegrationTests.java index b3165066..3596caf3 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,7 @@ import org.springframework.context.annotation.Import; import org.springframework.util.FileSystemUtils; import org.springframework.util.StreamUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Prankl @@ -85,7 +84,7 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "trunk"); Environment environment = repository.findOne("bar", "staging", "trunk"); - assertEquals(2, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(2); } @Test @@ -99,12 +98,12 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "trunk"); Environment environment = repository.findOne("bar", "staging", "trunk"); - assertEquals("bar", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("bar"); updateRepoForUpdate(uri); environment = repository.findOne("bar", "staging", "trunk"); - assertEquals("foo", - environment.getPropertySources().get(0).getSource().get("foo")); + assertThat(environment.getPropertySources().get(0).getSource().get("foo")) + .isEqualTo("foo"); } private void updateRepoForUpdate(String uri) @@ -135,7 +134,7 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { .run("--spring.cloud.config.server.svn.uri=" + uri); SvnKitEnvironmentRepository repository = this.context .getBean(SvnKitEnvironmentRepository.class); - assertEquals("trunk", repository.getDefaultLabel()); + assertThat(repository.getDefaultLabel()).isEqualTo("trunk"); } @Test(expected = NoSuchLabelException.class) @@ -149,7 +148,7 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { .getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "unknownlabel"); Environment environment = repository.findOne("bar", "staging", "unknownlabel"); - assertEquals(0, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(0); } @Test @@ -162,9 +161,9 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { EnvironmentRepository repository = this.context .getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "demobranch"); - assertTrue(environment.getPropertySources().get(0).getName() - .contains("bar.properties")); - assertEquals(1, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().get(0).getName() + .contains("bar.properties")).isTrue(); + assertThat(environment.getPropertySources().size()).isEqualTo(1); } @Configuration @@ -172,6 +171,7 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { @Import({ PropertyPlaceholderAutoConfiguration.class, EnvironmentRepositoryConfiguration.class }) protected static class TestConfiguration { + } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryTests.java index 0580666b..5e0597cd 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.StandardEnvironment; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Michael Prankl @@ -42,16 +40,19 @@ import static org.junit.Assert.assertTrue; public class SVNKitEnvironmentRepositoryTests { private static final String REPOSITORY_NAME = "svn-config-repo"; + private StandardEnvironment environment = new StandardEnvironment(); - private SvnKitEnvironmentRepository repository = new SvnKitEnvironmentRepository(this.environment, - new SvnKitEnvironmentProperties()); + + private SvnKitEnvironmentRepository repository = new SvnKitEnvironmentRepository( + this.environment, new SvnKitEnvironmentProperties()); private File basedir = new File("target/config"); @Before public void init() throws Exception { - String uri = ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/" - + REPOSITORY_NAME, "target/repos/" + REPOSITORY_NAME); + String uri = ConfigServerTestUtils.prepareLocalSvnRepo( + "src/test/resources/" + REPOSITORY_NAME, + "target/repos/" + REPOSITORY_NAME); this.repository.setUri(uri); if (this.basedir.exists()) { FileUtils.delete(this.basedir, FileUtils.RECURSIVE | FileUtils.RETRY); @@ -61,22 +62,22 @@ public class SVNKitEnvironmentRepositoryTests { @Test public void vanilla() { Environment environment = this.findOne(); - assertEquals(2, environment.getPropertySources().size()); - assertTrue(environment.getPropertySources().get(0).getName() - .contains("bar.properties")); - assertTrue(environment.getPropertySources().get(1).getName() - .contains("application.yml")); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName() + .contains("bar.properties")).isTrue(); + assertThat(environment.getPropertySources().get(1).getName() + .contains("application.yml")).isTrue(); } @Test public void basedir() { this.repository.setBasedir(this.basedir); Environment environment = this.findOne(); - assertEquals(2, environment.getPropertySources().size()); - assertTrue(environment.getPropertySources().get(0).getName() - .contains("bar.properties")); - assertTrue(environment.getPropertySources().get(1).getName() - .contains("application.yml")); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName() + .contains("bar.properties")).isTrue(); + assertThat(environment.getPropertySources().get(1).getName() + .contains("application.yml")).isTrue(); } @Test @@ -89,54 +90,53 @@ public class SVNKitEnvironmentRepositoryTests { this.repository.setBasedir(basedirWithSpace); Environment environment = this.findOne(); - assertEquals(2, environment.getPropertySources().size()); - assertTrue(environment.getPropertySources().get(0).getName() - .contains("bar.properties")); - assertTrue(environment.getPropertySources().get(1).getName() - .contains("application.yml")); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName() + .contains("bar.properties")).isTrue(); + assertThat(environment.getPropertySources().get(1).getName() + .contains("application.yml")).isTrue(); } @Test public void branch() { Environment environment = this.repository.findOne("bar", "staging", "branches/demobranch"); - assertEquals(1, environment.getPropertySources().size()); - assertTrue(environment.getPropertySources().get(0).getName() - .contains("bar.properties")); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName() + .contains("bar.properties")).isTrue(); } @Test public void branch_no_folder() { - Environment environment = this.repository.findOne("bar", "staging", - "demobranch"); - assertEquals(1, environment.getPropertySources().size()); - assertTrue(environment.getPropertySources().get(0).getName() - .contains("bar.properties")); + Environment environment = this.repository.findOne("bar", "staging", "demobranch"); + assertThat(environment.getPropertySources().size()).isEqualTo(1); + assertThat(environment.getPropertySources().get(0).getName() + .contains("bar.properties")).isTrue(); } @Test public void vanilla_with_update() { this.findOne(); Environment environment = this.findOne(); - assertEquals(2, environment.getPropertySources().size()); - assertTrue(environment.getPropertySources().get(0).getName() - .contains("bar.properties")); - assertTrue(environment.getPropertySources().get(1).getName() - .contains("application.yml")); + assertThat(environment.getPropertySources().size()).isEqualTo(2); + assertThat(environment.getPropertySources().get(0).getName() + .contains("bar.properties")).isTrue(); + assertThat(environment.getPropertySources().get(1).getName() + .contains("application.yml")).isTrue(); } @Test(expected = NoSuchLabelException.class) public void invalidLabel() { Environment environment = this.repository.findOne("bar", "staging", "unknownlabel"); - assertEquals(0, environment.getPropertySources().size()); + assertThat(environment.getPropertySources().size()).isEqualTo(0); } @Test public void vanilla_with_update_after_repo_delete() throws IOException { this.vanilla_with_update(); ConfigServerTestUtils.deleteLocalRepo(REPOSITORY_NAME); - assertThat(new File(basedir, REPOSITORY_NAME)).doesNotExist(); + assertThat(new File(this.basedir, REPOSITORY_NAME)).doesNotExist(); this.vanilla(); } @@ -151,15 +151,16 @@ public class SVNKitEnvironmentRepositoryTests { public static void main(String[] args) throws Exception { File basedir = new File("target/config"); - String uri = ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/" - + REPOSITORY_NAME, "target/repos/" + REPOSITORY_NAME); + String uri = ConfigServerTestUtils.prepareLocalSvnRepo( + "src/test/resources/" + REPOSITORY_NAME, + "target/repos/" + REPOSITORY_NAME); if (basedir.exists()) { FileUtils.delete(basedir, FileUtils.RECURSIVE | FileUtils.RETRY); } - new SpringApplicationBuilder(TestApplication.class) - .profiles("subversion") + new SpringApplicationBuilder(TestApplication.class).profiles("subversion") .properties("server.port=8888", - "spring.cloud.config.server.svn.uri:" + uri).run(args); + "spring.cloud.config.server.svn.uri:" + uri) + .run(args); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java index 5842de0f..b91adf82 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.util.Optional; + import javax.net.ssl.SSLHandshakeException; import javax.servlet.http.HttpServletRequest; @@ -39,71 +41,72 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** - * author Dylan Roberts + * @author Dylan Roberts */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = VaultEnvironmentRepositoryIntegrationTests.TestApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "server.ssl.key-store=classpath:ssl-test.jks", - "server.ssl.key-store-password=password", - "server.ssl.key-password=password", - "server.key-alias=ssl-test"}) +@SpringBootTest(classes = VaultEnvironmentRepositoryIntegrationTests.TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "server.ssl.key-store=classpath:ssl-test.jks", + "server.ssl.key-store-password=password", "server.ssl.key-password=password", + "server.key-alias=ssl-test" }) public class VaultEnvironmentRepositoryIntegrationTests { - @LocalServerPort - private String localServerPort; + @Rule + public ExpectedException expectedException = ExpectedException.none(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @LocalServerPort + private String localServerPort; - @Test - public void withSslValidation() throws Exception { - VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory = - new VaultEnvironmentRepositoryFactory(withRequest(), new EnvironmentWatch.Default(), - Optional.of(new HttpClientVaultRestTemplateFactory())); - VaultEnvironmentRepository vaultEnvironmentRepository = - vaultEnvironmentRepositoryFactory.build(withEnvironmentProperties(false)); - expectedException.expectCause(instanceOf(SSLHandshakeException.class)); + @Test + public void withSslValidation() throws Exception { + VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory = new VaultEnvironmentRepositoryFactory( + withRequest(), new EnvironmentWatch.Default(), + Optional.of(new HttpClientVaultRestTemplateFactory())); + VaultEnvironmentRepository vaultEnvironmentRepository = vaultEnvironmentRepositoryFactory + .build(withEnvironmentProperties(false)); + this.expectedException.expectCause(instanceOf(SSLHandshakeException.class)); - vaultEnvironmentRepository.findOne("application", "profile", "label"); - } + vaultEnvironmentRepository.findOne("application", "profile", "label"); + } - @Test - public void skipSslValidation() throws Exception { - VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory = - new VaultEnvironmentRepositoryFactory(withRequest(), new EnvironmentWatch.Default(), - Optional.of(new HttpClientVaultRestTemplateFactory())); - VaultEnvironmentRepository vaultEnvironmentRepository = - vaultEnvironmentRepositoryFactory.build(withEnvironmentProperties(true)); + @Test + public void skipSslValidation() throws Exception { + VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory = new VaultEnvironmentRepositoryFactory( + withRequest(), new EnvironmentWatch.Default(), + Optional.of(new HttpClientVaultRestTemplateFactory())); + VaultEnvironmentRepository vaultEnvironmentRepository = vaultEnvironmentRepositoryFactory + .build(withEnvironmentProperties(true)); - Environment actual = vaultEnvironmentRepository.findOne("application", "profile", "label"); + Environment actual = vaultEnvironmentRepository.findOne("application", "profile", + "label"); - assertThat(actual).isNotNull(); - } + assertThat(actual).isNotNull(); + } - private VaultEnvironmentProperties withEnvironmentProperties(boolean skipSslValidation) { - VaultEnvironmentProperties environmentProperties = new VaultEnvironmentProperties(); - environmentProperties.setPort(Integer.decode(localServerPort)); - environmentProperties.setScheme("https"); - environmentProperties.setSkipSslValidation(skipSslValidation); - return environmentProperties; - } + private VaultEnvironmentProperties withEnvironmentProperties( + boolean skipSslValidation) { + VaultEnvironmentProperties environmentProperties = new VaultEnvironmentProperties(); + environmentProperties.setPort(Integer.decode(this.localServerPort)); + environmentProperties.setScheme("https"); + environmentProperties.setSkipSslValidation(skipSslValidation); + return environmentProperties; + } - private ObjectProvider withRequest() { - HttpServletRequest request = mock(HttpServletRequest.class); - when(request.getHeader("X-Config-Token")).thenReturn("configToken"); - ObjectProvider requestProvider = mock(ObjectProvider.class); - when(requestProvider.getIfAvailable()).thenReturn(request); - return requestProvider; - } + private ObjectProvider withRequest() { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getHeader("X-Config-Token")).thenReturn("configToken"); + ObjectProvider requestProvider = mock(ObjectProvider.class); + when(requestProvider.getIfAvailable()).thenReturn(request); + return requestProvider; + } - @SpringBootConfiguration - @EnableAutoConfiguration - public static class TestApplication { + @SpringBootConfiguration + @EnableAutoConfiguration + public static class TestApplication { + + public static void main(String[] args) { + SpringApplication.run(TestApplication.class, args); + } + + } - public static void main(String[] args) { - SpringApplication.run(TestApplication.class, args); - } - } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java index f5c75a14..1136c076 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; + import org.springframework.beans.factory.ObjectProvider; import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.server.environment.VaultKvAccessStrategy.VaultResponse; @@ -28,12 +35,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.client.RestTemplate; -import javax.servlet.http.HttpServletRequest; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -47,12 +50,12 @@ import static org.mockito.Mockito.when; */ public class VaultEnvironmentRepositoryTests { - private ObjectMapper objectMapper; + private ObjectMapper objectMapper; - @Before + @Before public void init() { - objectMapper = new ObjectMapper(); - } + this.objectMapper = new ObjectMapper(); + } @SuppressWarnings("unchecked") private ObjectProvider mockProvide(HttpServletRequest request) { @@ -87,22 +90,27 @@ public class VaultEnvironmentRepositoryTests { eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), eq("application"))).thenReturn(appResp); - VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockProvide(configRequest), - new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties()); + VaultEnvironmentRepository repo = new VaultEnvironmentRepository( + mockProvide(configRequest), new EnvironmentWatch.Default(), rest, + new VaultEnvironmentProperties()); Environment e = repo.findOne("myapp", null, null); - assertEquals("Name should be the same as the application argument", "myapp", e.getName()); - assertEquals("Properties for specified application and default application with key 'application' should be returned", - 2, e.getPropertySources().size()); + assertThat(e.getName()).as("Name should be the same as the application argument") + .isEqualTo("myapp"); + assertThat(e.getPropertySources().size()).as( + "Properties for specified application and default application with key 'application' should be returned") + .isEqualTo(2); Map firstResult = new HashMap(); firstResult.put("foo", "bar"); - assertEquals("Properties for specified application should be returned in priority position", - firstResult, e.getPropertySources().get(0).getSource()); + assertThat(e.getPropertySources().get(0).getSource()).as( + "Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); Map secondResult = new HashMap(); secondResult.put("def-foo", "def-bar"); - assertEquals("Properties for default application with key 'application' should be returned in second position", - secondResult, e.getPropertySources().get(1).getSource()); + assertThat(e.getPropertySources().get(1).getSource()).as( + "Properties for default application with key 'application' should be returned in second position") + .isEqualTo(secondResult); } @Test @@ -134,22 +142,27 @@ public class VaultEnvironmentRepositoryTests { VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); properties.setBackend("foo/bar/secret"); - VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockProvide(configRequest), - new EnvironmentWatch.Default(), rest, properties); + VaultEnvironmentRepository repo = new VaultEnvironmentRepository( + mockProvide(configRequest), new EnvironmentWatch.Default(), rest, + properties); Environment e = repo.findOne("myapp", null, null); - assertEquals("Name should be the same as the application argument", "myapp", e.getName()); - assertEquals("Properties for specified application and default application with key 'application' should be returned", - 2, e.getPropertySources().size()); + assertThat(e.getName()).as("Name should be the same as the application argument") + .isEqualTo("myapp"); + assertThat(e.getPropertySources().size()).as( + "Properties for specified application and default application with key 'application' should be returned") + .isEqualTo(2); Map firstResult = new HashMap(); firstResult.put("foo", "bar"); - assertEquals("Properties for specified application should be returned in priority position", - firstResult, e.getPropertySources().get(0).getSource()); + assertThat(e.getPropertySources().get(0).getSource()).as( + "Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); Map secondResult = new HashMap(); secondResult.put("def-foo", "def-bar"); - assertEquals("Properties for default application with key 'application' should be returned in second position", - secondResult, e.getPropertySources().get(1).getSource()); + assertThat(e.getPropertySources().get(1).getSource()).as( + "Properties for default application with key 'application' should be returned in second position") + .isEqualTo(secondResult); } @Test @@ -177,24 +190,29 @@ public class VaultEnvironmentRepositoryTests { eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), eq("mydefaultkey"))).thenReturn(myDefaultKeyResp); - VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockProvide(configRequest), - new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties()); + VaultEnvironmentRepository repo = new VaultEnvironmentRepository( + mockProvide(configRequest), new EnvironmentWatch.Default(), rest, + new VaultEnvironmentProperties()); repo.setDefaultKey("mydefaultkey"); Environment e = repo.findOne("myapp", null, null); - assertEquals("Name should be the same as the application argument", "myapp", e.getName()); - assertEquals("Properties for specified application and default application with key 'mydefaultkey' should be returned", - 2, e.getPropertySources().size()); + assertThat(e.getName()).as("Name should be the same as the application argument") + .isEqualTo("myapp"); + assertThat(e.getPropertySources().size()).as( + "Properties for specified application and default application with key 'mydefaultkey' should be returned") + .isEqualTo(2); Map firstResult = new HashMap(); firstResult.put("foo", "bar"); - assertEquals("Properties for specified application should be returned in priority position", - firstResult, e.getPropertySources().get(0).getSource()); + assertThat(e.getPropertySources().get(0).getSource()).as( + "Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); Map secondResult = new HashMap(); secondResult.put("def-foo", "def-bar"); - assertEquals("Properties for default application with key 'mydefaultkey' should be returned in second position", - secondResult, e.getPropertySources().get(1).getSource()); + assertThat(e.getPropertySources().get(1).getSource()).as( + "Properties for default application with key 'mydefaultkey' should be returned in second position") + .isEqualTo(secondResult); } @Test @@ -222,20 +240,23 @@ public class VaultEnvironmentRepositoryTests { eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), eq("application"))).thenReturn(appResp); - VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockProvide(configRequest), - new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties()); + VaultEnvironmentRepository repo = new VaultEnvironmentRepository( + mockProvide(configRequest), new EnvironmentWatch.Default(), rest, + new VaultEnvironmentProperties()); repo.setDefaultKey("myapp"); Environment e = repo.findOne("myapp", null, null); - assertEquals("Name should be the same as the application argument", - "myapp", e.getName()); - assertEquals("Only properties for specified application should be returned", - 1, e.getPropertySources().size()); + assertThat(e.getName()).as("Name should be the same as the application argument") + .isEqualTo("myapp"); + assertThat(e.getPropertySources().size()) + .as("Only properties for specified application should be returned") + .isEqualTo(1); Map result = new HashMap(); result.put("foo", "bar"); - assertEquals("Properties should be returned for specified application", - result, e.getPropertySources().get(0).getSource()); + assertThat(e.getPropertySources().get(0).getSource()) + .as("Properties should be returned for specified application") + .isEqualTo(result); } @Test(expected = IllegalArgumentException.class) @@ -251,8 +272,9 @@ public class VaultEnvironmentRepositoryTests { when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); - VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockProvide(configRequest), - new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties()); + VaultEnvironmentRepository repo = new VaultEnvironmentRepository( + mockProvide(configRequest), new EnvironmentWatch.Default(), rest, + new VaultEnvironmentProperties()); repo.findOne("myapp", null, null); } @@ -268,51 +290,59 @@ public class VaultEnvironmentRepositoryTests { repo.findOne("myapp", null, null); } - @Test - @SuppressWarnings("unchecked") - public void testVaultVersioning() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); + @Test + @SuppressWarnings("unchecked") + public void testVaultVersioning() { + MockHttpServletRequest configRequest = new MockHttpServletRequest(); + configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); - RestTemplate rest = mock(RestTemplate.class); + RestTemplate rest = mock(RestTemplate.class); - ResponseEntity myAppResp = mock(ResponseEntity.class); - when(myAppResp.getStatusCode()).thenReturn(HttpStatus.OK); - VaultResponse myAppVaultResp = getVaultResponse("{\"data\": {\"data\": {\"foo\": \"bar\"}}}"); - when(myAppResp.getBody()).thenReturn(myAppVaultResp); - when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/data/{key}"), - eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), - eq("myapp"))).thenReturn(myAppResp); + ResponseEntity myAppResp = mock(ResponseEntity.class); + when(myAppResp.getStatusCode()).thenReturn(HttpStatus.OK); + VaultResponse myAppVaultResp = getVaultResponse( + "{\"data\": {\"data\": {\"foo\": \"bar\"}}}"); + when(myAppResp.getBody()).thenReturn(myAppVaultResp); + when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/data/{key}"), + eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), + eq("myapp"))).thenReturn(myAppResp); - ResponseEntity appResp = mock(ResponseEntity.class); - when(appResp.getStatusCode()).thenReturn(HttpStatus.OK); - VaultResponse appVaultResp = getVaultResponse("{\"data\": {\"data\": {\"def-foo\":\"def-bar\"}}}"); - when(appResp.getBody()).thenReturn(appVaultResp); - when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/data/{key}"), - eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), - eq("application"))).thenReturn(appResp); + ResponseEntity appResp = mock(ResponseEntity.class); + when(appResp.getStatusCode()).thenReturn(HttpStatus.OK); + VaultResponse appVaultResp = getVaultResponse( + "{\"data\": {\"data\": {\"def-foo\":\"def-bar\"}}}"); + when(appResp.getBody()).thenReturn(appVaultResp); + when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/data/{key}"), + eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), + eq("application"))).thenReturn(appResp); - final VaultEnvironmentProperties vaultEnvironmentProperties = new VaultEnvironmentProperties(); - vaultEnvironmentProperties.setKvVersion(2); - VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockProvide(configRequest), - new EnvironmentWatch.Default(), rest, vaultEnvironmentProperties); + final VaultEnvironmentProperties vaultEnvironmentProperties = new VaultEnvironmentProperties(); + vaultEnvironmentProperties.setKvVersion(2); + VaultEnvironmentRepository repo = new VaultEnvironmentRepository( + mockProvide(configRequest), new EnvironmentWatch.Default(), rest, + vaultEnvironmentProperties); - Environment e = repo.findOne("myapp", null, null); - assertEquals("Name should be the same as the application argument", "myapp", e.getName()); - assertEquals("Properties for specified application and default application with key 'application' should be returned", - 2, e.getPropertySources().size()); - Map firstResult = new HashMap(); - firstResult.put("foo", "bar"); - assertEquals("Properties for specified application should be returned in priority position", - firstResult, e.getPropertySources().get(0).getSource()); - } + Environment e = repo.findOne("myapp", null, null); + assertThat(e.getName()).as("Name should be the same as the application argument") + .isEqualTo("myapp"); + assertThat(e.getPropertySources().size()).as( + "Properties for specified application and default application with key 'application' should be returned") + .isEqualTo(2); + Map firstResult = new HashMap(); + firstResult.put("foo", "bar"); + assertThat(e.getPropertySources().get(0).getSource()).as( + "Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); + } + + private VaultResponse getVaultResponse(String json) { + try { + return this.objectMapper.readValue(json, VaultResponse.class); + } + catch (Exception e) { + fail(e.getMessage()); + } + return null; + } - private VaultResponse getVaultResponse(String json) { - try { - return objectMapper.readValue(json, VaultResponse.class); - } catch (Exception e) { - fail(e.getMessage()); - } - return null; - } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactoryTest.java index faa64605..fc558e62 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import org.junit.Test; @@ -20,7 +21,7 @@ import org.junit.Test; import org.springframework.cloud.config.server.environment.VaultKvAccessStrategyFactory.V1VaultKvAccessStrategy; import org.springframework.cloud.config.server.environment.VaultKvAccessStrategyFactory.V2VaultKvAccessStrategy; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Haroun Pacquee @@ -31,18 +32,19 @@ public class VaultKvAccessStrategyFactoryTest { public void testGetV1Strategy() { VaultKvAccessStrategy vaultKvAccessStrategy = VaultKvAccessStrategyFactory .forVersion(null, "foo", 1); - assertTrue(vaultKvAccessStrategy instanceof V1VaultKvAccessStrategy); + assertThat(vaultKvAccessStrategy instanceof V1VaultKvAccessStrategy).isTrue(); } @Test public void testGetV2Strategy() { VaultKvAccessStrategy vaultKvAccessStrategy = VaultKvAccessStrategyFactory .forVersion(null, "foo", 2); - assertTrue(vaultKvAccessStrategy instanceof V2VaultKvAccessStrategy); + assertThat(vaultKvAccessStrategy instanceof V2VaultKvAccessStrategy).isTrue(); } @Test(expected = IllegalArgumentException.class) public void testGetUnsupportedStrategy() { VaultKvAccessStrategyFactory.forVersion(null, "foo", 0); } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyTest.java index 93e73411..f27796f0 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.environment; import java.io.IOException; @@ -23,64 +24,64 @@ import org.junit.Test; import org.springframework.cloud.config.server.environment.VaultKvAccessStrategy.VaultResponse; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Haroun Pacquee */ public class VaultKvAccessStrategyTest { + private static final String FOO_BAR = "{\"foo\":\"bar\"}"; + private ObjectMapper objectMapper = new ObjectMapper(); - private static final String FOO_BAR = "{\"foo\":\"bar\"}"; + private static VaultKvAccessStrategySupport getStrategy(int version) { + return (VaultKvAccessStrategySupport) VaultKvAccessStrategyFactory + .forVersion(null, "foo", version); + } @Test public void testV1ExtractFromBody() { String json = "{\"data\": {\"foo\": \"bar\"}}"; String s = getStrategy(1).extractDataFromBody(getVaultResponse(json)); - assertThat(s, is(FOO_BAR)); + assertThat(s).isEqualTo(FOO_BAR); } @Test public void testV1ExtractFromBodyNoData() { String json = "{}"; String s = getStrategy(1).extractDataFromBody(getVaultResponse(json)); - assertNull(s); + assertThat(s).isNull(); } @Test public void testV2ExtractFromBody() { String json = "{\"data\": {\"data\": {\"foo\": \"bar\"}}}"; String s = getStrategy(2).extractDataFromBody(getVaultResponse(json)); - assertThat(s, is(FOO_BAR)); + assertThat(s).isEqualTo(FOO_BAR); } @Test public void testV2ExtractFromBodyEmptyNestedData() { String json = "{\"data\": {}}"; String s = getStrategy(2).extractDataFromBody(getVaultResponse(json)); - assertNull(s); + assertThat(s).isNull(); } @Test public void testV2ExtractFromBodyNoData() { String json = "{}"; String s = getStrategy(2).extractDataFromBody(getVaultResponse(json)); - assertNull(s); + assertThat(s).isNull(); } private VaultResponse getVaultResponse(String json) { try { - return objectMapper.readValue(json, VaultResponse.class); + return this.objectMapper.readValue(json, VaultResponse.class); } catch (IOException e) { throw new UndeclaredThrowableException(e); } } - private static VaultKvAccessStrategySupport getStrategy(int version) { - return (VaultKvAccessStrategySupport) VaultKvAccessStrategyFactory - .forVersion(null, "foo", version); - } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/GenericResourceRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/GenericResourceRepositoryTests.java index 07889637..481d75ec 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/GenericResourceRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/GenericResourceRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import org.springframework.cloud.config.server.environment.NativeEnvironmentRepo import org.springframework.cloud.config.server.environment.NativeEnvironmentRepositoryTests; import org.springframework.context.ConfigurableApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -36,7 +36,9 @@ import static org.junit.Assert.assertNotNull; public class GenericResourceRepositoryTests { private GenericResourceRepository repository; + private ConfigurableApplicationContext context; + private NativeEnvironmentRepository nativeRepository; @After @@ -49,34 +51,38 @@ public class GenericResourceRepositoryTests { @Before public void init() { this.context = new SpringApplicationBuilder( - NativeEnvironmentRepositoryTests.class).web(WebApplicationType.NONE).run(); - this.nativeRepository = new NativeEnvironmentRepository(this.context.getEnvironment(), - new NativeEnvironmentProperties()); - this.repository = new GenericResourceRepository( - this.nativeRepository); + NativeEnvironmentRepositoryTests.class).web(WebApplicationType.NONE) + .run(); + this.nativeRepository = new NativeEnvironmentRepository( + this.context.getEnvironment(), new NativeEnvironmentProperties()); + this.repository = new GenericResourceRepository(this.nativeRepository); this.repository.setResourceLoader(this.context); this.context.close(); } @Test public void locateResource() { - assertNotNull(this.repository.findOne("blah", "default", "master", "foo.properties")); + assertThat(this.repository.findOne("blah", "default", "master", "foo.properties")) + .isNotNull(); } @Test public void locateProfiledResource() { - assertNotNull(this.repository.findOne("blah", "local", "master", "foo.txt")); + assertThat(this.repository.findOne("blah", "local", "master", "foo.txt")) + .isNotNull(); } @Test public void locateProfiledResourceWithPlaceholder() { this.nativeRepository.setSearchLocations("classpath:/test/{profile}"); - assertNotNull(this.repository.findOne("blah", "local", "master", "foo.txt")); + assertThat(this.repository.findOne("blah", "local", "master", "foo.txt")) + .isNotNull(); } - @Test(expected=NoSuchResourceException.class) + @Test(expected = NoSuchResourceException.class) public void locateMissingResource() { - assertNotNull(this.repository.findOne("blah", "default", "master", "foo.txt")); + assertThat(this.repository.findOne("blah", "default", "master", "foo.txt")) + .isNotNull(); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerIntegrationTests.java index 9a5b9df3..cc3f0ee5 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.config.server.resource; import org.junit.Before; @@ -52,9 +53,12 @@ public class ResourceControllerIntegrationTests { @Autowired private WebApplicationContext context; + private MockMvc mvc; + @Autowired private EnvironmentRepository repository; + @Autowired private ResourceRepository resources; diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerTests.java index e2a8e02f..7353a100 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,9 +28,7 @@ import org.springframework.cloud.config.server.environment.NativeEnvironmentRepo import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -39,8 +37,11 @@ import static org.junit.Assert.assertTrue; public class ResourceControllerTests { private ResourceController controller; + private GenericResourceRepository repository; + private ConfigurableApplicationContext context; + private NativeEnvironmentRepository environmentRepository; @After @@ -53,9 +54,10 @@ public class ResourceControllerTests { @Before public void init() { this.context = new SpringApplicationBuilder( - NativeEnvironmentRepositoryTests.class).web(WebApplicationType.NONE).run(); - this.environmentRepository = new NativeEnvironmentRepository(this.context.getEnvironment(), - new NativeEnvironmentProperties()); + NativeEnvironmentRepositoryTests.class).web(WebApplicationType.NONE) + .run(); + this.environmentRepository = new NativeEnvironmentRepository( + this.context.getEnvironment(), new NativeEnvironmentProperties()); this.repository = new GenericResourceRepository(this.environmentRepository); this.repository.setResourceLoader(this.context); this.controller = new ResourceController(this.repository, @@ -66,64 +68,79 @@ public class ResourceControllerTests { @Test public void templateReplacement() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); - String resource = this.controller.retrieve("foo", "bar", "dev", "template.json", true); - assertTrue("Wrong content: " + resource, resource.matches("\\{\\s*\"foo\": \"dev_bar\"\\s*\\}")); + String resource = this.controller.retrieve("foo", "bar", "dev", "template.json", + true); + assertThat(replaceNewLines(resource)) + .matches("\\{\\s*\"foo\": \"dev_bar\"\\s*\\}") + .as("Wrong content: " + resource); } - + @Test public void templateReplacementNotForResolvePlaceholdersFalse() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); - String resource = this.controller.retrieve("foo", "bar", "dev", "template.json", false); - assertTrue("Wrong content: " + resource, resource.matches("\\{\\s*\"foo\": \"\\$\\{foo\\}\"\\s*\\}")); + String resource = this.controller.retrieve("foo", "bar", "dev", "template.json", + false); + assertThat(replaceNewLines(resource)) + .matches("\\{\\s*\"foo\": \"\\$\\{foo\\}\"\\s*\\}") + .as("Wrong content: " + resource); } @Test public void templateReplacementNotForBinary() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); - String resource = new String(this.controller.binary("foo", "bar", "dev", "template.json")); - assertTrue("Wrong content: " + resource, resource.matches("\\{\\s*\"foo\": \"\\$\\{foo\\}\"\\s*\\}")); + String resource = new String( + this.controller.binary("foo", "bar", "dev", "template.json")); + assertThat(replaceNewLines(resource)) + .matches("\\{\\s*\"foo\": \"\\$\\{foo\\}\"\\s*\\}") + .as("Wrong content: " + resource); } @Test public void escapedPlaceholder() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); - String resource = this.controller.retrieve("foo", "bar", "dev", "placeholder.txt", true); - assertEquals("foo: ${foo}", resource); + String resource = this.controller.retrieve("foo", "bar", "dev", "placeholder.txt", + true); + assertThat(resource).isEqualToIgnoringNewLines("foo: ${foo}"); } @Test public void applicationAndLabelPlaceholdersWithoutSlash() throws Exception { - this.environmentRepository.setSearchLocations("classpath:/test/{application}/{label}"); + this.environmentRepository + .setSearchLocations("classpath:/test/{application}/{label}"); String resource = this.controller.retrieve("dev", "bar", "spam", "foo.txt", true); - assertEquals("foo: dev_bar/spam", resource); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void applicationPlaceholderWithSlash() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test/{application}"); - String resource = this.controller.retrieve("dev(_)spam", "bar", "", "foo.txt", true); - assertEquals("foo: dev_bar/spam", resource); + String resource = this.controller.retrieve("dev(_)spam", "bar", "", "foo.txt", + true); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void applicationPlaceholderWithSlashNullLabel() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test/{application}"); - String resource = this.controller.retrieve("dev(_)spam", "bar", null, "foo.txt", true); - assertEquals("foo: dev_bar/spam", resource); + String resource = this.controller.retrieve("dev(_)spam", "bar", null, "foo.txt", + true); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void labelPlaceholderWithSlash() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test/{label}"); - String resource = this.controller.retrieve("dev", "bar", "dev(_)spam", "foo.txt", true); - assertEquals("foo: dev_bar/spam", resource); + String resource = this.controller.retrieve("dev", "bar", "dev(_)spam", "foo.txt", + true); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void profilePlaceholderNullLabel() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test/{profile}"); - String resource = this.controller.retrieve("bar", "dev", null, "spam/foo.txt", true); - assertEquals("foo: dev_bar/spam", resource); + String resource = this.controller.retrieve("bar", "dev", null, "spam/foo.txt", + true); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test @@ -133,22 +150,24 @@ public class ResourceControllerTests { this.controller.retrieve(null, "foo", "bar", "spam/foo.txt", true); } catch (Exception e) { - assertNotNull(e); + assertThat(e).isNotNull(); } } @Test public void labelWithSlash() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); - String resource = this.controller.retrieve("foo", "bar", "dev(_)spam", "foo.txt", true); - assertEquals("foo: dev_bar/spam", resource); + String resource = this.controller.retrieve("foo", "bar", "dev(_)spam", "foo.txt", + true); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void resourceWithSlash() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); - String resource = this.controller.retrieve("foo", "bar", "dev", "spam/foo.txt", true); - assertEquals("foo: dev_bar/spam", resource); + String resource = this.controller.retrieve("foo", "bar", "dev", "spam/foo.txt", + true); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test @@ -157,7 +176,7 @@ public class ResourceControllerTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo/bar/dev/" + "spam/foo.txt"); String resource = this.controller.retrieve("foo", "bar", "dev", request, true); - assertEquals("foo: dev_bar/spam", resource); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test @@ -167,21 +186,23 @@ public class ResourceControllerTests { request.setServletPath("/spring"); request.setRequestURI("/foo/bar/dev/" + "spam/foo.txt"); String resource = this.controller.retrieve("foo", "bar", "dev", request, true); - assertEquals("foo: dev_bar/spam", resource); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void labelWithSlashForResolvePlaceholdersFalse() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); - String resource = this.controller.retrieve("foo", "bar", "dev(_)spam", "foo.txt", false); - assertEquals("foo: dev_bar/spam", resource); + String resource = this.controller.retrieve("foo", "bar", "dev(_)spam", "foo.txt", + false); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void resourceWithSlashForResolvePlaceholdersFalse() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); - String resource = this.controller.retrieve("foo", "bar", "dev", "spam/foo.txt", false); - assertEquals("foo: dev_bar/spam", resource); + String resource = this.controller.retrieve("foo", "bar", "dev", "spam/foo.txt", + false); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test @@ -190,42 +211,43 @@ public class ResourceControllerTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo/bar/dev/" + "spam/foo.txt"); String resource = this.controller.retrieve("foo", "bar", "dev", request, false); - assertEquals("foo: dev_bar/spam", resource); + assertThat(resource).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } - + @Test public void applicationAndLabelPlaceholdersWithoutSlashForBinary() throws Exception { - this.environmentRepository.setSearchLocations("classpath:/test/{application}/{label}"); + this.environmentRepository + .setSearchLocations("classpath:/test/{application}/{label}"); byte[] resource = this.controller.binary("dev", "bar", "spam", "foo.txt"); - assertEquals("foo: dev_bar/spam", new String(resource)); + assertThat(new String(resource)).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void applicationPlaceholderWithSlashForBinary() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test/{application}"); byte[] resource = this.controller.binary("dev(_)spam", "bar", "", "foo.txt"); - assertEquals("foo: dev_bar/spam", new String(resource)); + assertThat(new String(resource)).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void applicationPlaceholderWithSlashForBinaryNullLabel() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test/{application}"); byte[] resource = this.controller.binary("dev(_)spam", "bar", null, "foo.txt"); - assertEquals("foo: dev_bar/spam", new String(resource)); + assertThat(new String(resource)).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void labelPlaceholderWithSlashForBinary() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test/{label}"); byte[] resource = this.controller.binary("dev", "bar", "dev(_)spam", "foo.txt"); - assertEquals("foo: dev_bar/spam", new String(resource)); + assertThat(new String(resource)).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void profilePlaceholderForBinaryNullLabel() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test/{profile}"); byte[] resource = this.controller.binary("bar", "dev", null, "spam/foo.txt"); - assertEquals("foo: dev_bar/spam", new String(resource)); + assertThat(new String(resource)).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test @@ -235,7 +257,7 @@ public class ResourceControllerTests { this.controller.binary(null, "foo", "bar", "spam/foo.txt"); } catch (Exception e) { - assertNotNull(e); + assertThat(e).isNotNull(); } } @@ -243,14 +265,14 @@ public class ResourceControllerTests { public void labelWithSlashForBinary() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); byte[] resource = this.controller.binary("foo", "bar", "dev(_)spam", "foo.txt"); - assertEquals("foo: dev_bar/spam", new String(resource)); + assertThat(new String(resource)).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test public void resourceWithSlashForBinary() throws Exception { this.environmentRepository.setSearchLocations("classpath:/test"); byte[] resource = this.controller.binary("foo", "bar", "dev", "spam/foo.txt"); - assertEquals("foo: dev_bar/spam", new String(resource)); + assertThat(new String(resource)).isEqualToIgnoringNewLines("foo: dev_bar/spam"); } @Test @@ -258,8 +280,12 @@ public class ResourceControllerTests { this.environmentRepository.setSearchLocations("classpath:/test"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo/bar/dev/" + "spam/foo.txt"); - byte[] resource = this.controller.binary("foo", "bar", "dev", request ); - assertEquals("foo: dev_bar/spam", new String(resource)); + byte[] resource = this.controller.binary("foo", "bar", "dev", request); + assertThat(new String(resource)).isEqualToIgnoringNewLines("foo: dev_bar/spam"); + } + + private String replaceNewLines(String text) { + return text.replace("\n", "").replace("\t", ""); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactoryTest.java index 0a00e1d5..f4b94a80 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 - 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import com.jcraft.jsch.HostKeyRepository; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import org.eclipse.jgit.transport.OpenSshConfig.Host; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; @@ -38,32 +37,60 @@ import org.springframework.cloud.config.server.environment.JGitEnvironmentProper import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; /** - * Unit tests for property based SSH config processor + * Unit tests for property based SSH config processor. + * * @author William Tran * @author Ollie Hughes */ @RunWith(MockitoJUnitRunner.class) public class PropertyBasedSshSessionFactoryTest { - private static final String HOST_KEY = "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMzCa0AcNbahUFjFYJHIilhJOhKFHuDOOuY+/HqV9kALftitwNYo6dQ+tC9IK5JVZCZfqKfDWVMxspcPDf9eMoE="; + private static final String HOST_KEY = "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAAB" + + "BBMzCa0AcNbahUFjFYJHIilhJOhKFHuDOOuY+/HqV9kALftitwNYo6dQ+tC9IK5JVZCZfqKfDWVMxspcPDf9eMoE="; + private static final String HOST_KEY_ALGORITHM = "ecdsa-sha2-nistp256"; + private static final String PRIVATE_KEY = getResourceAsString("/ssh/key"); + private PropertyBasedSshSessionFactory factory; + @Mock private Host hc; + @Mock private Session session; + @Mock private JSch jSch; + @Mock private HostKeyRepository hostKeyRepository; - + + public static String getResourceAsString(String path) { + try { + Resource resource = new ClassPathResource(path); + try (BufferedReader br = new BufferedReader( + new InputStreamReader(resource.getInputStream()))) { + StringBuilder builder = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + builder.append(line).append('\n'); + } + return builder.toString(); + } + } + catch (IOException e) { + throw new IllegalStateException(e); + } + } + @Test public void strictHostKeyCheckingIsOptional() { JGitEnvironmentProperties sshKey = new JGitEnvironmentProperties(); @@ -71,12 +98,12 @@ public class PropertyBasedSshSessionFactoryTest { sshKey.setPrivateKey(PRIVATE_KEY); setupSessionFactory(sshKey); - factory.configure(hc, session); - - verify(session).setConfig("StrictHostKeyChecking", "no"); - verifyNoMoreInteractions(session); + this.factory.configure(this.hc, this.session); + + verify(this.session).setConfig("StrictHostKeyChecking", "no"); + verifyNoMoreInteractions(this.session); } - + @Test public void strictHostKeyCheckingIsUsed() { JGitEnvironmentProperties sshKey = new JGitEnvironmentProperties(); @@ -85,12 +112,12 @@ public class PropertyBasedSshSessionFactoryTest { sshKey.setPrivateKey(PRIVATE_KEY); setupSessionFactory(sshKey); - factory.configure(hc, session); - - verify(session).setConfig("StrictHostKeyChecking", "yes"); - verifyNoMoreInteractions(session); + this.factory.configure(this.hc, this.session); + + verify(this.session).setConfig("StrictHostKeyChecking", "yes"); + verifyNoMoreInteractions(this.session); } - + @Test public void hostKeyAlgorithmIsSpecified() { JGitEnvironmentProperties sshKey = new JGitEnvironmentProperties(); @@ -100,12 +127,12 @@ public class PropertyBasedSshSessionFactoryTest { sshKey.setPrivateKey(PRIVATE_KEY); setupSessionFactory(sshKey); - factory.configure(hc, session); - verify(session).setConfig("server_host_key", HOST_KEY_ALGORITHM); - verify(session).setConfig("StrictHostKeyChecking", "yes"); - verifyNoMoreInteractions(session); + this.factory.configure(this.hc, this.session); + verify(this.session).setConfig("server_host_key", HOST_KEY_ALGORITHM); + verify(this.session).setConfig("StrictHostKeyChecking", "yes"); + verifyNoMoreInteractions(this.session); } - + @Test public void privateKeyIsUsed() throws Exception { JGitEnvironmentProperties sshKey = new JGitEnvironmentProperties(); @@ -113,8 +140,10 @@ public class PropertyBasedSshSessionFactoryTest { sshKey.setPrivateKey(PRIVATE_KEY); setupSessionFactory(sshKey); - factory.createSession(hc, null, SshUriPropertyProcessor.getHostname(sshKey.getUri()), 22, null); - verify(jSch).addIdentity("gitlab.example.local", PRIVATE_KEY.getBytes(), null, null); + this.factory.createSession(this.hc, null, + SshUriPropertyProcessor.getHostname(sshKey.getUri()), 22, null); + verify(this.jSch).addIdentity("gitlab.example.local", PRIVATE_KEY.getBytes(), + null, null); } @Test @@ -125,12 +154,13 @@ public class PropertyBasedSshSessionFactoryTest { sshKey.setPrivateKey(PRIVATE_KEY); setupSessionFactory(sshKey); - factory.createSession(hc, null, SshUriPropertyProcessor.getHostname(sshKey.getUri()), 22, null); + this.factory.createSession(this.hc, null, + SshUriPropertyProcessor.getHostname(sshKey.getUri()), 22, null); ArgumentCaptor captor = ArgumentCaptor.forClass(HostKey.class); - verify(hostKeyRepository).add(captor.capture(), isNull()); + verify(this.hostKeyRepository).add(captor.capture(), isNull()); HostKey hostKey = captor.getValue(); - Assert.assertEquals("gitlab.example.local", hostKey.getHost()); - Assert.assertEquals(HOST_KEY, hostKey.getKey()); + assertThat(hostKey.getHost()).isEqualTo("gitlab.example.local"); + assertThat(hostKey.getKey()).isEqualTo(HOST_KEY); } @Test @@ -141,10 +171,11 @@ public class PropertyBasedSshSessionFactoryTest { sshKey.setPreferredAuthentications("password,keyboard-interactive"); setupSessionFactory(sshKey); - factory.configure(hc, session); - verify(session).setConfig("PreferredAuthentications", "password,keyboard-interactive"); - verify(session).setConfig("StrictHostKeyChecking", "no"); - verifyNoMoreInteractions(session); + this.factory.configure(this.hc, this.session); + verify(this.session).setConfig("PreferredAuthentications", + "password,keyboard-interactive"); + verify(this.session).setConfig("StrictHostKeyChecking", "no"); + verifyNoMoreInteractions(this.session); } @Test @@ -155,34 +186,22 @@ public class PropertyBasedSshSessionFactoryTest { sshKey.setKnownHostsFile("/ssh/known_hosts"); setupSessionFactory(sshKey); - factory.createSession(hc, null, SshUriPropertyProcessor.getHostname(sshKey.getUri()), 22, null); + this.factory.createSession(this.hc, null, + SshUriPropertyProcessor.getHostname(sshKey.getUri()), 22, null); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); - verify(jSch).setKnownHosts(captor.capture()); - Assert.assertEquals("/ssh/known_hosts", captor.getValue()); + verify(this.jSch).setKnownHosts(captor.capture()); + assertThat(captor.getValue()).isEqualTo("/ssh/known_hosts"); } private void setupSessionFactory(JGitEnvironmentProperties sshKey) { Map sshKeysByHostname = new HashMap<>(); - sshKeysByHostname.put(SshUriPropertyProcessor.getHostname(sshKey.getUri()), sshKey); - factory = new PropertyBasedSshSessionFactory(sshKeysByHostname, jSch) ; - when(hc.getHostName()).thenReturn(SshUriPropertyProcessor.getHostname(sshKey.getUri())); - when(jSch.getHostKeyRepository()).thenReturn(hostKeyRepository); + sshKeysByHostname.put(SshUriPropertyProcessor.getHostname(sshKey.getUri()), + sshKey); + this.factory = new PropertyBasedSshSessionFactory(sshKeysByHostname, this.jSch); + when(this.hc.getHostName()) + .thenReturn(SshUriPropertyProcessor.getHostname(sshKey.getUri())); + when(this.jSch.getHostKeyRepository()).thenReturn(this.hostKeyRepository); } - public static String getResourceAsString(String path) { - try { - Resource resource = new ClassPathResource(path); - try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()))) { - StringBuilder builder = new StringBuilder(); - String line; - while ((line = br.readLine()) != null) { - builder.append(line).append('\n'); - } - return builder.toString(); - } - } catch (IOException e) { - throw new IllegalStateException(e); - } - } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshPropertyValidatorTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshPropertyValidatorTest.java index 921067aa..24e1706d 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshPropertyValidatorTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshPropertyValidatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 - 2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.config.server.ssh; import java.util.Set; + import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; @@ -27,11 +28,10 @@ import org.junit.Test; import org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentProperties; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; +import static org.assertj.core.api.Assertions.assertThat; /** - * Unit tests for property based SSH config validators + * Unit tests for property based SSH config validators. * * @author Ollie Hughes */ @@ -39,35 +39,41 @@ public class SshPropertyValidatorTest { private static final String SSH_URI = "git@gitserver.com:team/repo1.git"; - private static final String VALID_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" + - "MIIEpAIBAAKCAQEAoqyz6YaYMTr7L8GLPSQpAQXaM04gRx4CCsGK2kfLQdw4BlqI\n" + - "yyxp38YcuZG9cUDBAxby+K2TKmwHaC1R61QTwbPuCRdIPrDwRz+FLoegm3iDLCmn\n" + - "uP6rjZDneYsqfU1KSdrOwIbCnONfDdvYL/vnZC/o8DDMlk5Orw2SfHkT3pq0o8km\n" + - "ayBwN4Sf3bpyWTY0oZcmNeSCCoIdE59k8Pa7/t9bwY9caLj05C3DEsjucc7Ei/Eq\n" + - "TOyGyobtXwaya5CqKLUHes74Poz1aEP/yVFdUud91uezd8ZK1P1t5/ZKA3R6aHir\n" + - "+diDJ2/GQ2tD511FW46yw+EtBUJTO6ADVv4UnQIDAQABAoIBAF+5qwEfX82QfKFk\n" + - "jfADqFFexUDtl1biFKeJrpC2MKhn01wByH9uejrhFKQqW8UaKroLthyZ34DWIyGt\n" + - "lDnHGv0gSVF2LuAdNLdobJGt49e4+c9yD61vxzm97Eh8mRs08SM2q/VlF35E2fmI\n" + - "xdWusUImYzd8L9e+6tRd8zZl9UhG5vR5XIstKqxC6S0g79aAt0hasE4Gw1FKOf2V\n" + - "4mlL15atjQSKCPdOicuyc4zpjAtU1A9AfF51iG8oOUuJebPW8tCftfOQxaeGFgMG\n" + - "7M9aai1KzXR6M5IBAKEv31yBvz/SHTneP7oZXNLeC1GIR420PKybmeZdNK8BbEAu\n" + - "3reKgm0CgYEA03Sx8JoF5UBsIvFPpP1fjSlTgKryM5EJR6KQtj5e4YfyxccJepN8\n" + - "q4MrqDfNKleG/a1acEtDMhBNovU7Usp2QIP7zpAeioHBOhmE5WSieZGc3icOGWWq\n" + - "mRkdulSONruqWKv76ZoluxftekE03bDhZDNlcCgmrslEKB/ufHd2oc8CgYEAxPFa\n" + - "lKOdSeiYFV5CtvO8Ro8em6rGpSsVz4qkPxbeBqUDCb9KXHhq6YrhRxOIfQJKfT7M\n" + - "ZFCn8ArJXKgOGu+KsvwIErFHF9g2jJMG4DOUTpkQgi2yveihFxcmz/AltyVXgrnv\n" + - "ZWQbAerH77pdKKhNivLGgEv72GYawdYjYNjemdMCgYA2kEMmMahZyrDcp2YEzfit\n" + - "BT/t0K6kzcUWPgWXcSqsiZcEn+J7RbmCzFskkhmX1nQX23adyV3yejB+X0dKisHO\n" + - "zf/ZAmlPFkJVCqa3RquCMSfIT02dEhXeYZPBM/Zqeyxuqxpa4hLgX0FBLbhFiFHw\n" + - "uC5xrXql2XuD2xF//peXEwKBgQC+pa28Cg7vRxxCQzduB9CQtWc55j3aEjVQ7bNF\n" + - "54sS/5ZLT0Ra8677WZfuyDfuW9NkHvCZg4Ku2qJG8eCFrrGjxlrCTZ62tHVJ6+JS\n" + - "E1xUIdRbUIWhVZrr0VufG6hG/P0T7Y6Tpi6G0pKtvMkF3LcD9TS3adboix8H2ZXx\n" + - "4L7MRQKBgQC0OO3qqNXOjIVYWOoqXLybOY/Wqu9lxCAgGyCYaMcstnBI7W0MZTBr\n" + - "/syluvGsaFc1sE7MMGOOzKi1tF4YvDmSnzA/R1nmaPguuD9fOA+w7Pwkv5vLvuJq\n" + - "2U7EeNwxq1I1L3Ag6E7wH4BHLHd4TKaZR6agFkn8oomz71yZPGjuZQ==\n" + - "-----END RSA PRIVATE KEY-----"; + private static final String VALID_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" + + "MIIEpAIBAAKCAQEAoqyz6YaYMTr7L8GLPSQpAQXaM04gRx4CCsGK2kfLQdw4BlqI\n" + + "yyxp38YcuZG9cUDBAxby+K2TKmwHaC1R61QTwbPuCRdIPrDwRz+FLoegm3iDLCmn\n" + + "uP6rjZDneYsqfU1KSdrOwIbCnONfDdvYL/vnZC/o8DDMlk5Orw2SfHkT3pq0o8km\n" + + "ayBwN4Sf3bpyWTY0oZcmNeSCCoIdE59k8Pa7/t9bwY9caLj05C3DEsjucc7Ei/Eq\n" + + "TOyGyobtXwaya5CqKLUHes74Poz1aEP/yVFdUud91uezd8ZK1P1t5/ZKA3R6aHir\n" + + "+diDJ2/GQ2tD511FW46yw+EtBUJTO6ADVv4UnQIDAQABAoIBAF+5qwEfX82QfKFk\n" + + "jfADqFFexUDtl1biFKeJrpC2MKhn01wByH9uejrhFKQqW8UaKroLthyZ34DWIyGt\n" + + "lDnHGv0gSVF2LuAdNLdobJGt49e4+c9yD61vxzm97Eh8mRs08SM2q/VlF35E2fmI\n" + + "xdWusUImYzd8L9e+6tRd8zZl9UhG5vR5XIstKqxC6S0g79aAt0hasE4Gw1FKOf2V\n" + + "4mlL15atjQSKCPdOicuyc4zpjAtU1A9AfF51iG8oOUuJebPW8tCftfOQxaeGFgMG\n" + + "7M9aai1KzXR6M5IBAKEv31yBvz/SHTneP7oZXNLeC1GIR420PKybmeZdNK8BbEAu\n" + + "3reKgm0CgYEA03Sx8JoF5UBsIvFPpP1fjSlTgKryM5EJR6KQtj5e4YfyxccJepN8\n" + + "q4MrqDfNKleG/a1acEtDMhBNovU7Usp2QIP7zpAeioHBOhmE5WSieZGc3icOGWWq\n" + + "mRkdulSONruqWKv76ZoluxftekE03bDhZDNlcCgmrslEKB/ufHd2oc8CgYEAxPFa\n" + + "lKOdSeiYFV5CtvO8Ro8em6rGpSsVz4qkPxbeBqUDCb9KXHhq6YrhRxOIfQJKfT7M\n" + + "ZFCn8ArJXKgOGu+KsvwIErFHF9g2jJMG4DOUTpkQgi2yveihFxcmz/AltyVXgrnv\n" + + "ZWQbAerH77pdKKhNivLGgEv72GYawdYjYNjemdMCgYA2kEMmMahZyrDcp2YEzfit\n" + + "BT/t0K6kzcUWPgWXcSqsiZcEn+J7RbmCzFskkhmX1nQX23adyV3yejB+X0dKisHO\n" + + "zf/ZAmlPFkJVCqa3RquCMSfIT02dEhXeYZPBM/Zqeyxuqxpa4hLgX0FBLbhFiFHw\n" + + "uC5xrXql2XuD2xF//peXEwKBgQC+pa28Cg7vRxxCQzduB9CQtWc55j3aEjVQ7bNF\n" + + "54sS/5ZLT0Ra8677WZfuyDfuW9NkHvCZg4Ku2qJG8eCFrrGjxlrCTZ62tHVJ6+JS\n" + + "E1xUIdRbUIWhVZrr0VufG6hG/P0T7Y6Tpi6G0pKtvMkF3LcD9TS3adboix8H2ZXx\n" + + "4L7MRQKBgQC0OO3qqNXOjIVYWOoqXLybOY/Wqu9lxCAgGyCYaMcstnBI7W0MZTBr\n" + + "/syluvGsaFc1sE7MMGOOzKi1tF4YvDmSnzA/R1nmaPguuD9fOA+w7Pwkv5vLvuJq\n" + + "2U7EeNwxq1I1L3Ag6E7wH4BHLHd4TKaZR6agFkn8oomz71yZPGjuZQ==\n" + + "-----END RSA PRIVATE KEY-----"; + + private static final String VALID_HOST_KEY = "AAAAB3NzaC1yc2EAAAADAQABAAABAQDg6/W" + + "/5cbk/npvzpae7ZEa54F4rkwh2V3NiuqVZ5hWr+8O4/6SmrS7yBvRHAFeAJNb0LOCjE/7tjd1" + + "fqUx+QU1ATCtwkOhuwG8Ubzkx23mMZlrwEvx7XEfBoLN7Lw9fXjWDtTTgFB1AxCQ2pGGiNG0Q" + + "CwyA4HViDHVU+ibwkRlzuDJG0tnp5Qpo3DXkHwFNdqWNfVrIZ6q2xbyeoJjKjnR215T0ehmuWF" + + "mKqG+uMNe/LQ6IOiK0F5+gr7rgPxNLAYYqyhraAnBeHn5gapsSzYJmFpoAHWvN7OUwHcJ88D9qUkKi4VKxYiuK69u3z825Xj" + + "2cLTfj9JiHCfV8cTo9GL"; - private static final String VALID_HOST_KEY = "AAAAB3NzaC1yc2EAAAADAQABAAABAQDg6/W/5cbk/npvzpae7ZEa54F4rkwh2V3NiuqVZ5hWr+8O4/6SmrS7yBvRHAFeAJNb0LOCjE/7tjd1fqUx+QU1ATCtwkOhuwG8Ubzkx23mMZlrwEvx7XEfBoLN7Lw9fXjWDtTTgFB1AxCQ2pGGiNG0QCwyA4HViDHVU+ibwkRlzuDJG0tnp5Qpo3DXkHwFNdqWNfVrIZ6q2xbyeoJjKjnR215T0ehmuWFmKqG+uMNe/LQ6IOiK0F5+gr7rgPxNLAYYqyhraAnBeHn5gapsSzYJmFpoAHWvN7OUwHcJ88D9qUkKi4VKxYiuK69u3z825Xj2cLTfj9JiHCfV8cTo9GL"; private static Validator validator; @BeforeClass @@ -85,8 +91,9 @@ public class SshPropertyValidatorTest { validSettings.setHostKey(VALID_HOST_KEY); validSettings.setHostKeyAlgorithm("ssh-rsa"); - Set> constraintViolations = validator.validate(validSettings); - assertThat(constraintViolations, hasSize(0)); + Set> constraintViolations = validator + .validate(validSettings); + assertThat(constraintViolations).hasSize(0); } @Test @@ -96,8 +103,9 @@ public class SshPropertyValidatorTest { invalidKey.setIgnoreLocalSshSettings(true); invalidKey.setPrivateKey("invalid_key"); - Set> constraintViolations = validator.validate(invalidKey); - assertThat(constraintViolations, hasSize(1)); + Set> constraintViolations = validator + .validate(invalidKey); + assertThat(constraintViolations).hasSize(1); } @Test @@ -106,8 +114,9 @@ public class SshPropertyValidatorTest { missingKey.setUri(SSH_URI); missingKey.setIgnoreLocalSshSettings(true); - Set> constraintViolations = validator.validate(missingKey); - assertThat(constraintViolations, hasSize(1)); + Set> constraintViolations = validator + .validate(missingKey); + assertThat(constraintViolations).hasSize(1); } @Test @@ -118,8 +127,9 @@ public class SshPropertyValidatorTest { missingAlgo.setPrivateKey(VALID_PRIVATE_KEY); missingAlgo.setHostKey("some_host"); - Set> constraintViolations = validator.validate(missingAlgo); - assertThat(constraintViolations, hasSize(1)); + Set> constraintViolations = validator + .validate(missingAlgo); + assertThat(constraintViolations).hasSize(1); } @Test @@ -130,8 +140,9 @@ public class SshPropertyValidatorTest { missingHostKey.setPrivateKey(VALID_PRIVATE_KEY); missingHostKey.setHostKeyAlgorithm("ssh-rsa"); - Set> constraintViolations = validator.validate(missingHostKey); - assertThat(constraintViolations, hasSize(1)); + Set> constraintViolations = validator + .validate(missingHostKey); + assertThat(constraintViolations).hasSize(1); } @Test @@ -143,8 +154,9 @@ public class SshPropertyValidatorTest { unsupportedAlgo.setHostKey("some_host_key"); unsupportedAlgo.setHostKeyAlgorithm("unsupported"); - Set> constraintViolations = validator.validate(unsupportedAlgo); - assertThat(constraintViolations, hasSize(1)); + Set> constraintViolations = validator + .validate(unsupportedAlgo); + assertThat(constraintViolations).hasSize(1); } @Test @@ -154,8 +166,9 @@ public class SshPropertyValidatorTest { useLocal.setIgnoreLocalSshSettings(false); useLocal.setPrivateKey("invalid_key"); - Set> constraintViolations = validator.validate(useLocal); - assertThat(constraintViolations, hasSize(0)); + Set> constraintViolations = validator + .validate(useLocal); + assertThat(constraintViolations).hasSize(0); } @@ -166,29 +179,32 @@ public class SshPropertyValidatorTest { httpsUri.setIgnoreLocalSshSettings(true); httpsUri.setPrivateKey("invalid_key"); - Set> constraintViolations = validator.validate(httpsUri); - assertThat(constraintViolations, hasSize(0)); + Set> constraintViolations = validator + .validate(httpsUri); + assertThat(constraintViolations).hasSize(0); } @Test public void preferredAuthenticationsIsValidated() throws Exception { MultipleJGitEnvironmentProperties sshUriProperties = new MultipleJGitEnvironmentProperties(); - assertThat(validator.validate(sshUriProperties), hasSize(0)); + assertThat(validator.validate(sshUriProperties)).hasSize(0); - sshUriProperties.setPreferredAuthentications("keyboard-interactive, public-key ,kerberos"); - assertThat(validator.validate(sshUriProperties), hasSize(0)); + sshUriProperties.setPreferredAuthentications( + "keyboard-interactive, public-key ,kerberos"); + assertThat(validator.validate(sshUriProperties)).hasSize(0); sshUriProperties.setPreferredAuthentications(",,"); - assertThat(validator.validate(sshUriProperties), hasSize(1)); + assertThat(validator.validate(sshUriProperties)).hasSize(1); } @Test public void knowHostsFileIsValidated() throws Exception { MultipleJGitEnvironmentProperties sshUriProperties = new MultipleJGitEnvironmentProperties(); - assertThat(validator.validate(sshUriProperties), hasSize(0)); + assertThat(validator.validate(sshUriProperties)).hasSize(0); sshUriProperties.setKnownHostsFile("non-existing.file"); - assertThat(validator.validate(sshUriProperties), hasSize(1)); + assertThat(validator.validate(sshUriProperties)).hasSize(1); } -} \ No newline at end of file + +} diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessorTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessorTest.java index c1cb8e22..6e724d26 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessorTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 - 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,6 @@ package org.springframework.cloud.config.server.ssh; - import java.util.Map; import org.eclipse.jgit.transport.SshSessionFactory; @@ -26,30 +25,36 @@ import org.junit.Test; import org.springframework.cloud.config.server.environment.JGitEnvironmentProperties; import org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentProperties; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** - * Unit tests for property based SSH config processor + * Unit tests for property based SSH config processor. + * * @author William Tran * @author Ollie Hughes */ public class SshUriPropertyProcessorTest { private static final String PRIVATE_KEY1 = "privateKey"; + private static final String HOST_KEY1 = "hostKey"; + private static final String ALGO1 = "ssh-rsa"; + private static final String URI1 = "ollie@gitlab1.test.local:project/my-repo"; + private static final String HOST1 = "gitlab1.test.local"; + private static final String PRIVATE_KEY2 = "privateKey2"; + private static final String URI2 = "ssh://git@gitlab2.test.local/wtran/my-repo"; + private static final String HOST2 = "gitlab2.test.local"; + private static final String PRIVATE_KEY3 = "privateKey3"; + private static final String URI3 = "git+ssh://git@gitlab3.test.local/wtran/my-repo"; + private static final String HOST3 = "gitlab3.test.local"; @After @@ -59,10 +64,12 @@ public class SshUriPropertyProcessorTest { @Test public void testSingleSshUriProperties() { - SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor(mainRepoPropertiesFixture()); - Map sshKeysByHostname = sshUriPropertyProcessor.getSshKeysByHostname(); + SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor( + mainRepoPropertiesFixture()); + Map sshKeysByHostname = sshUriPropertyProcessor + .getSshKeysByHostname(); - assertThat(sshKeysByHostname.values(), hasSize(1)); + assertThat(sshKeysByHostname.values()).hasSize(1); JGitEnvironmentProperties sshKey = sshKeysByHostname.get(HOST1); assertMainRepo(sshKey); @@ -71,55 +78,62 @@ public class SshUriPropertyProcessorTest { @Test public void testMultipleSshUriPropertiess() { MultipleJGitEnvironmentProperties sshUriProperties = mainRepoPropertiesFixture(); - MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties nestedSshUriProperties1 = - new MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties(); + MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties nestedSshUriProperties1; + nestedSshUriProperties1 = new MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties(); nestedSshUriProperties1.setUri(URI2); nestedSshUriProperties1.setPrivateKey(PRIVATE_KEY2); - MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties nestedSshUriProperties2 = - new MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties(); + MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties nestedSshUriProperties2; + nestedSshUriProperties2 = new MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties(); nestedSshUriProperties2.setUri(URI3); nestedSshUriProperties2.setPrivateKey(PRIVATE_KEY3); addRepoProperties(sshUriProperties, nestedSshUriProperties1, "repo2"); addRepoProperties(sshUriProperties, nestedSshUriProperties2, "repo3"); - SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor(sshUriProperties); + SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor( + sshUriProperties); - Map sshKeysByHostname = sshUriPropertyProcessor.getSshKeysByHostname(); + Map sshKeysByHostname = sshUriPropertyProcessor + .getSshKeysByHostname(); - assertThat(sshKeysByHostname.values(), hasSize(3)); + assertThat(sshKeysByHostname.values()).hasSize(3); JGitEnvironmentProperties sshKey1 = sshKeysByHostname.get(HOST1); assertMainRepo(sshKey1); JGitEnvironmentProperties sshKey2 = sshKeysByHostname.get(HOST2); - assertThat(SshUriPropertyProcessor.getHostname(sshKey2.getUri()), is(equalTo(HOST2))); - assertThat(sshKey2.getHostKeyAlgorithm(), is(nullValue())); - assertThat(sshKey2.getHostKey(), is(nullValue())); - assertThat(sshKey2.getPrivateKey(), is(equalTo(PRIVATE_KEY2))); + assertThat(SshUriPropertyProcessor.getHostname(sshKey2.getUri())) + .isEqualTo(HOST2); + assertThat(sshKey2.getHostKeyAlgorithm()).isNull(); + assertThat(sshKey2.getHostKey()).isNull(); + assertThat(sshKey2.getPrivateKey()).isEqualTo(PRIVATE_KEY2); JGitEnvironmentProperties sshKey3 = sshKeysByHostname.get(HOST3); - assertThat(SshUriPropertyProcessor.getHostname(sshKey3.getUri()), is(equalTo(HOST3))); - assertThat(sshKey3.getHostKeyAlgorithm(), is(nullValue())); - assertThat(sshKey3.getHostKey(), is(nullValue())); - assertThat(sshKey3.getPrivateKey(), is(equalTo(PRIVATE_KEY3))); + assertThat(SshUriPropertyProcessor.getHostname(sshKey3.getUri())) + .isEqualTo(HOST3); + assertThat(sshKey3.getHostKeyAlgorithm()).isNull(); + assertThat(sshKey3.getHostKey()).isNull(); + assertThat(sshKey3.getPrivateKey()).isEqualTo(PRIVATE_KEY3); } @Test public void testSameHostnameDifferentKeysFirstOneWins() { MultipleJGitEnvironmentProperties sshUriProperties = mainRepoPropertiesFixture(); - MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties nestedSshUriProperties = new MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties(); + MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties nestedSshUriProperties; + nestedSshUriProperties = new MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties(); nestedSshUriProperties.setUri(URI1); nestedSshUriProperties.setPrivateKey(PRIVATE_KEY1); nestedSshUriProperties.setHostKey(HOST_KEY1); nestedSshUriProperties.setHostKeyAlgorithm(ALGO1); addRepoProperties(sshUriProperties, nestedSshUriProperties, "repo2"); - SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor(sshUriProperties); - Map sshKeysByHostname = sshUriPropertyProcessor.getSshKeysByHostname(); + SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor( + sshUriProperties); + Map sshKeysByHostname = sshUriPropertyProcessor + .getSshKeysByHostname(); - assertThat(sshKeysByHostname.values(), hasSize(1)); + assertThat(sshKeysByHostname.values()).hasSize(1); JGitEnvironmentProperties sshKey = sshKeysByHostname.get(HOST1); assertMainRepo(sshKey); @@ -127,27 +141,33 @@ public class SshUriPropertyProcessorTest { @Test public void testNoSshUriProperties() { - SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor(new MultipleJGitEnvironmentProperties()); - Map sshKeysByHostname = sshUriPropertyProcessor.getSshKeysByHostname(); - assertThat(sshKeysByHostname.values(), hasSize(0)); + SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor( + new MultipleJGitEnvironmentProperties()); + Map sshKeysByHostname = sshUriPropertyProcessor + .getSshKeysByHostname(); + assertThat(sshKeysByHostname.values()).hasSize(0); } @Test public void testInvalidUriDoesNotAddEntry() { MultipleJGitEnvironmentProperties sshUriProperties = new MultipleJGitEnvironmentProperties(); sshUriProperties.setUri("invalid_uri"); - SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor(sshUriProperties); - Map sshKeysByHostname = sshUriPropertyProcessor.getSshKeysByHostname(); - assertThat(sshKeysByHostname.values(), hasSize(0)); + SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor( + sshUriProperties); + Map sshKeysByHostname = sshUriPropertyProcessor + .getSshKeysByHostname(); + assertThat(sshKeysByHostname.values()).hasSize(0); } @Test public void testHttpsUriDoesNotAddEntry() { MultipleJGitEnvironmentProperties sshUriProperties = new MultipleJGitEnvironmentProperties(); sshUriProperties.setUri("https://user@github.com/proj/repo.git"); - SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor(sshUriProperties); - Map sshKeysByHostname = sshUriPropertyProcessor.getSshKeysByHostname(); - assertThat(sshKeysByHostname.values(), hasSize(0)); + SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor( + sshUriProperties); + Map sshKeysByHostname = sshUriPropertyProcessor + .getSshKeysByHostname(); + assertThat(sshKeysByHostname.values()).hasSize(0); } private MultipleJGitEnvironmentProperties mainRepoPropertiesFixture() { @@ -159,16 +179,18 @@ public class SshUriPropertyProcessorTest { return result; } - private void addRepoProperties(MultipleJGitEnvironmentProperties mainRepoProperties, MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties repoProperties, String repoName) { + private void addRepoProperties(MultipleJGitEnvironmentProperties mainRepoProperties, + MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties repoProperties, + String repoName) { mainRepoProperties.getRepos().put(repoName, repoProperties); } private void assertMainRepo(JGitEnvironmentProperties sshKey) { - assertThat(sshKey, is(notNullValue())); - assertThat(SshUriPropertyProcessor.getHostname(sshKey.getUri()), is(equalTo(HOST1))); - assertThat(sshKey.getHostKeyAlgorithm(), is(equalTo(ALGO1))); - assertThat(sshKey.getHostKey(), is(equalTo(HOST_KEY1))); - assertThat(sshKey.getPrivateKey(), is(equalTo(PRIVATE_KEY1))); + assertThat(sshKey).isNotNull(); + assertThat(SshUriPropertyProcessor.getHostname(sshKey.getUri())).isEqualTo(HOST1); + assertThat(sshKey.getHostKeyAlgorithm()).isEqualTo(ALGO1); + assertThat(sshKey.getHostKey()).isEqualTo(HOST_KEY1); + assertThat(sshKey.getPrivateKey()).isEqualTo(PRIVATE_KEY1); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/EnvironmentPropertySourceTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/EnvironmentPropertySourceTest.java index 58cc5211..de282963 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/EnvironmentPropertySourceTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/EnvironmentPropertySourceTest.java @@ -1,18 +1,37 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.support; -import static org.junit.Assert.assertEquals; -import static org.springframework.cloud.config.server.support.EnvironmentPropertySource.resolvePlaceholders; - import org.junit.Test; + import org.springframework.core.env.StandardEnvironment; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.cloud.config.server.support.EnvironmentPropertySource.resolvePlaceholders; + public class EnvironmentPropertySourceTest { - private final StandardEnvironment env = new StandardEnvironment(); - - @Test - public void testEscapedPlaceholdersRemoved() { - assertEquals("${abc}", resolvePlaceholders(env, "\\${abc}")); - // JSON generated from jackson will be double escaped - assertEquals("${abc}", resolvePlaceholders(env, "\\\\${abc}")); - } + + private final StandardEnvironment env = new StandardEnvironment(); + + @Test + public void testEscapedPlaceholdersRemoved() { + assertThat(resolvePlaceholders(this.env, "\\${abc}")).isEqualTo("${abc}"); + // JSON generated from jackson will be double escaped + assertThat(resolvePlaceholders(this.env, "\\\\${abc}")).isEqualTo("${abc}"); + } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProviderTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProviderTest.java index 148a51e9..1d5ffd63 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProviderTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProviderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -43,6 +42,7 @@ public class GitSkipSslValidationCredentialsProviderTest { @Mock private CredentialsProvider mockDelegateCredentialsProvider; + private GitSkipSslValidationCredentialsProvider skipSslValidationCredentialsProvider; @Before @@ -53,51 +53,55 @@ public class GitSkipSslValidationCredentialsProviderTest { @Test public void testCanHandle() { - assertTrue("GitSkipSslValidationCredentialsProvider only handles HTTPS uris", - GitSkipSslValidationCredentialsProvider - .canHandle("https://github.com/org/repo")); - assertFalse("GitSkipSslValidationCredentialsProvider only handles HTTPS uris", - GitSkipSslValidationCredentialsProvider - .canHandle("git@github.com:org/repo")); + assertThat(GitSkipSslValidationCredentialsProvider + .canHandle("https://github.com/org/repo")).as( + "GitSkipSslValidationCredentialsProvider only handles HTTPS uris") + .isTrue(); + assertThat(GitSkipSslValidationCredentialsProvider + .canHandle("git@github.com:org/repo")).as( + "GitSkipSslValidationCredentialsProvider only handles HTTPS uris") + .isFalse(); } @Test public void testIsInteractive() { - assertFalse( - "GitSkipSslValidationCredentialsProvider with no delegate requires no user interaction", - skipSslValidationCredentialsProvider.isInteractive()); + assertThat(this.skipSslValidationCredentialsProvider.isInteractive()).as( + "GitSkipSslValidationCredentialsProvider with no delegate requires no user interaction") + .isFalse(); } @Test public void testIsInteractiveWithDelegate() { this.skipSslValidationCredentialsProvider = new GitSkipSslValidationCredentialsProvider( - mockDelegateCredentialsProvider); + this.mockDelegateCredentialsProvider); - when(mockDelegateCredentialsProvider.isInteractive()).thenReturn(true); + when(this.mockDelegateCredentialsProvider.isInteractive()).thenReturn(true); - assertTrue( - "With a delegate provider, isInteractive value depends on the delegate", - skipSslValidationCredentialsProvider.isInteractive()); + assertThat(this.skipSslValidationCredentialsProvider.isInteractive()).as( + "With a delegate provider, isInteractive value depends on the delegate") + .isTrue(); } @Test public void testSupportsSslFailureInformationalMessage() { CredentialItem informationalMessage = new CredentialItem.InformationalMessage( "text " + JGitText.get().sslFailureTrustExplanation + " more text"); - assertTrue( - "GitSkipSslValidationCredentialsProvider should always support SSL failure InformationalMessage", - skipSslValidationCredentialsProvider.supports(informationalMessage)); + assertThat(this.skipSslValidationCredentialsProvider + .supports(informationalMessage)).as( + "GitSkipSslValidationCredentialsProvider should always support SSL failure InformationalMessage") + .isTrue(); informationalMessage = new CredentialItem.InformationalMessage("unrelated"); - assertFalse( - "GitSkipSslValidationCredentialsProvider should not support unrelated InformationalMessage items", - skipSslValidationCredentialsProvider.supports(informationalMessage)); + assertThat(this.skipSslValidationCredentialsProvider + .supports(informationalMessage)).as( + "GitSkipSslValidationCredentialsProvider should not support unrelated InformationalMessage items") + .isFalse(); } @Test public void testSupportsSslFailureInformationalMessageWithDelegate() { this.skipSslValidationCredentialsProvider = new GitSkipSslValidationCredentialsProvider( - mockDelegateCredentialsProvider); + this.mockDelegateCredentialsProvider); testSupportsSslFailureInformationalMessage(); } @@ -106,31 +110,31 @@ public class GitSkipSslValidationCredentialsProviderTest { public void testSupportsSslValidationYesNoTypes() { CredentialItem yesNoType = new CredentialItem.YesNoType( JGitText.get().sslTrustNow); - assertTrue( - "GitSkipSslValidationCredentialsProvider should always support the trust now YesNoType item", - skipSslValidationCredentialsProvider.supports(yesNoType)); + assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)).as( + "GitSkipSslValidationCredentialsProvider should always support the trust now YesNoType item") + .isTrue(); yesNoType = new CredentialItem.YesNoType( MessageFormat.format(JGitText.get().sslTrustForRepo, "/a/path.git")); - assertTrue( - "GitSkipSslValidationCredentialsProvider should always support the trust repo YesNoType item", - skipSslValidationCredentialsProvider.supports(yesNoType)); + assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)).as( + "GitSkipSslValidationCredentialsProvider should always support the trust repo YesNoType item") + .isTrue(); yesNoType = new CredentialItem.YesNoType(JGitText.get().sslTrustAlways); - assertTrue( - "GitSkipSslValidationCredentialsProvider should always support the trust always YesNoType item", - skipSslValidationCredentialsProvider.supports(yesNoType)); + assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)).as( + "GitSkipSslValidationCredentialsProvider should always support the trust always YesNoType item") + .isTrue(); yesNoType = new CredentialItem.YesNoType("unrelated"); - assertFalse( - "GitSkipSslValidationCredentialsProvider should not support unrelated YesNoType items", - skipSslValidationCredentialsProvider.supports(yesNoType)); + assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)).as( + "GitSkipSslValidationCredentialsProvider should not support unrelated YesNoType items") + .isFalse(); } @Test public void testSupportsYesNoTypeWithDelegate() { this.skipSslValidationCredentialsProvider = new GitSkipSslValidationCredentialsProvider( - mockDelegateCredentialsProvider); + this.mockDelegateCredentialsProvider); testSupportsSslValidationYesNoTypes(); } @@ -139,29 +143,29 @@ public class GitSkipSslValidationCredentialsProviderTest { public void testSupportsUnrelatedCredentialItemTypes() { CredentialItem usernameCredentialItem = new CredentialItem.Username(); - boolean supportsItems = skipSslValidationCredentialsProvider + boolean supportsItems = this.skipSslValidationCredentialsProvider .supports(usernameCredentialItem); - assertFalse( - "Credential item types not related to SSL validation skipping should not be supported", - supportsItems); + assertThat(supportsItems).as( + "Credential item types not related to SSL validation skipping should not be supported") + .isFalse(); } @Test public void testSupportsUnrelatedCredentialItemTypesWithDelegate() { this.skipSslValidationCredentialsProvider = new GitSkipSslValidationCredentialsProvider( - mockDelegateCredentialsProvider); + this.mockDelegateCredentialsProvider); CredentialItem usernameCredentialItem = new CredentialItem.Username(); - when(mockDelegateCredentialsProvider.supports(usernameCredentialItem)) + when(this.mockDelegateCredentialsProvider.supports(usernameCredentialItem)) .thenReturn(true); - boolean supportsItems = skipSslValidationCredentialsProvider + boolean supportsItems = this.skipSslValidationCredentialsProvider .supports(usernameCredentialItem); - assertTrue( - "GitSkipSslValidationCredentialsProvider must support the types supported by its delegate CredentialsProvider", - supportsItems); + assertThat(supportsItems).as( + "GitSkipSslValidationCredentialsProvider must support the types supported by its delegate CredentialsProvider") + .isTrue(); } @Test(expected = UnsupportedCredentialItem.class) @@ -170,7 +174,7 @@ public class GitSkipSslValidationCredentialsProviderTest { CredentialItem usernameCredentialItem = new CredentialItem.Username(); CredentialItem passwordCredentialItem = new CredentialItem.Password(); - skipSslValidationCredentialsProvider.get(uri, usernameCredentialItem, + this.skipSslValidationCredentialsProvider.get(uri, usernameCredentialItem, passwordCredentialItem); } @@ -178,20 +182,20 @@ public class GitSkipSslValidationCredentialsProviderTest { public void testGetUnrelatedCredentialItemTypesWithDelegate() throws URISyntaxException { this.skipSslValidationCredentialsProvider = new GitSkipSslValidationCredentialsProvider( - mockDelegateCredentialsProvider); + this.mockDelegateCredentialsProvider); URIish uri = new URIish("https://example.com/repo.git"); CredentialItem usernameCredentialItem = new CredentialItem.Username(); CredentialItem passwordCredentialItem = new CredentialItem.Password(); - when(mockDelegateCredentialsProvider.get(uri, usernameCredentialItem, + when(this.mockDelegateCredentialsProvider.get(uri, usernameCredentialItem, passwordCredentialItem)).thenReturn(true); - boolean getSuccessful = skipSslValidationCredentialsProvider.get(uri, + boolean getSuccessful = this.skipSslValidationCredentialsProvider.get(uri, usernameCredentialItem, passwordCredentialItem); - assertTrue( - "GitSkipSslValidationCredentialsProvider must successfully get the types supported by its delegate CredentialsProvider", - getSuccessful); + assertThat(getSuccessful).as("GitSkipSslValidationCredentialsProvider " + + "must successfully get the types supported by its delegate CredentialsProvider") + .isTrue(); } @Test @@ -204,23 +208,23 @@ public class GitSkipSslValidationCredentialsProviderTest { CredentialItem.YesNoType trustAlways = new CredentialItem.YesNoType( JGitText.get().sslTrustAlways); - boolean getSuccessful = skipSslValidationCredentialsProvider.get(uri, message, - trustNow, trustAlways); + boolean getSuccessful = this.skipSslValidationCredentialsProvider.get(uri, + message, trustNow, trustAlways); - assertTrue( - "SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping", - getSuccessful); - assertTrue( - "SkipSSlValidationCredentialsProvider should trust the current repo operation", - trustNow.getValue()); - assertFalse("We should not globally skip all SSL validation", - trustAlways.getValue()); + assertThat(getSuccessful).as( + "SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping") + .isTrue(); + assertThat(trustNow.getValue()).as( + "SkipSSlValidationCredentialsProvider should trust the current repo operation") + .isTrue(); + assertThat(trustAlways.getValue()) + .as("We should not globally skip all SSL validation").isFalse(); } @Test public void testGetSslTrustItemsWithDelegate() throws URISyntaxException { this.skipSslValidationCredentialsProvider = new GitSkipSslValidationCredentialsProvider( - mockDelegateCredentialsProvider); + this.mockDelegateCredentialsProvider); testGetSslTrustItems(); } @@ -237,25 +241,26 @@ public class GitSkipSslValidationCredentialsProviderTest { CredentialItem.YesNoType trustAlways = new CredentialItem.YesNoType( JGitText.get().sslTrustAlways); - boolean getSuccessful = skipSslValidationCredentialsProvider.get(uri, message, - trustNow, trustForRepo, trustAlways); + boolean getSuccessful = this.skipSslValidationCredentialsProvider.get(uri, + message, trustNow, trustForRepo, trustAlways); - assertTrue( - "SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping", - getSuccessful); - assertTrue( - "SkipSSlValidationCredentialsProvider should trust the current repo operation", - trustNow.getValue()); - assertTrue("Future operations on this repository should also be trusted", - trustForRepo.getValue()); - assertFalse("We should not globally skip all SSL validation", - trustAlways.getValue()); + assertThat(getSuccessful).as( + "SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping") + .isTrue(); + assertThat(trustNow.getValue()).as( + "SkipSSlValidationCredentialsProvider should trust the current repo operation") + .isTrue(); + assertThat(trustForRepo.getValue()) + .as("Future operations on this repository should also be trusted") + .isTrue(); + assertThat(trustAlways.getValue()) + .as("We should not globally skip all SSL validation").isFalse(); } @Test public void testGetSslTrustItemsWithLocalRepoAndDelegate() throws URISyntaxException { this.skipSslValidationCredentialsProvider = new GitSkipSslValidationCredentialsProvider( - mockDelegateCredentialsProvider); + this.mockDelegateCredentialsProvider); testGetSslTrustItemsWithLocalRepo(); } @@ -264,17 +269,18 @@ public class GitSkipSslValidationCredentialsProviderTest { public void testReset() throws URISyntaxException { URIish uri = new URIish("https://example.com/repo.git"); - skipSslValidationCredentialsProvider.reset(uri); + this.skipSslValidationCredentialsProvider.reset(uri); } @Test public void testResetWithDelegate() throws URISyntaxException { this.skipSslValidationCredentialsProvider = new GitSkipSslValidationCredentialsProvider( - mockDelegateCredentialsProvider); + this.mockDelegateCredentialsProvider); URIish uri = new URIish("https://example.com/repo.git"); - skipSslValidationCredentialsProvider.reset(uri); + this.skipSslValidationCredentialsProvider.reset(uri); - verify(mockDelegateCredentialsProvider).reset(uri); + verify(this.mockDelegateCredentialsProvider).reset(uri); } + } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClientSupportTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClientSupportTest.java index b392e622..8e80ea86 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClientSupportTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClientSupportTest.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.springframework.cloud.config.server.support; import java.io.IOException; @@ -26,36 +42,39 @@ import static org.hamcrest.Matchers.isA; import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause; @RunWith(SpringRunner.class) -@SpringBootTest(classes = HttpClientSupportTest.TestConfiguration.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = HttpClientSupportTest.TestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HttpClientSupportTest { - @LocalServerPort - private String localServerPort; + @Rule + public ExpectedException expectedException = ExpectedException.none(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @LocalServerPort + private String localServerPort; - @Test - public void setsTimeout() throws GeneralSecurityException, IOException { - JGitEnvironmentProperties properties = new JGitEnvironmentProperties(); - properties.setTimeout(1); - CloseableHttpClient httpClient = HttpClientSupport.builder(properties).build(); + @Test + public void setsTimeout() throws GeneralSecurityException, IOException { + JGitEnvironmentProperties properties = new JGitEnvironmentProperties(); + properties.setTimeout(1); + CloseableHttpClient httpClient = HttpClientSupport.builder(properties).build(); - expectedException.expect(anyOf(isA(SocketTimeoutException.class), hasCause(isA(SocketTimeoutException.class)))); + this.expectedException.expect(anyOf(isA(SocketTimeoutException.class), + hasCause(isA(SocketTimeoutException.class)))); - httpClient.execute(new HttpGet(String.format("http://127.0.0.1:%s/test/endpoint", localServerPort))); - } + httpClient.execute(new HttpGet(String.format("http://127.0.0.1:%s/test/endpoint", + this.localServerPort))); + } - @SpringBootConfiguration - @EnableWebMvc - @EnableAutoConfiguration - @RestController - static class TestConfiguration { + @SpringBootConfiguration + @EnableWebMvc + @EnableAutoConfiguration + @RestController + static class TestConfiguration { - @GetMapping("/test/endpoint") - public void testEndpoint() throws InterruptedException { - Thread.sleep(2000); - } - } -} \ No newline at end of file + @GetMapping("/test/endpoint") + public void testEndpoint() throws InterruptedException { + Thread.sleep(2000); + } + + } + +} diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/bar.properties b/spring-cloud-config-server/src/test/resources/another-config-repo/bar.properties index 7daacd5d..ae3cdf5b 100644 --- a/spring-cloud-config-server/src/test/resources/another-config-repo/bar.properties +++ b/spring-cloud-config-server/src/test/resources/another-config-repo/bar.properties @@ -1 +1 @@ -foo: bar \ No newline at end of file +foo:bar diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/git/COMMIT_EDITMSG b/spring-cloud-config-server/src/test/resources/another-config-repo/git/COMMIT_EDITMSG index 38f51b1c..c8fcd951 100644 --- a/spring-cloud-config-server/src/test/resources/another-config-repo/git/COMMIT_EDITMSG +++ b/spring-cloud-config-server/src/test/resources/another-config-repo/git/COMMIT_EDITMSG @@ -1 +1 @@ -Move application.yml to subdir +Updated diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/git/index b/spring-cloud-config-server/src/test/resources/another-config-repo/git/index index 2e65e5aceb937f1e6aef5caf5dd9ee8f1a4b8338..8dc6753468879de162e1706aa2614de441956fe0 100644 GIT binary patch literal 261 zcmZ?q402{*U|<5_n23;_W?J*Ef@ssXQ?D^FGBY!_u%2dMXk5a;!2AM&893J2+>h?~ zuOVH}QRu8Or)Vi_6;lNRUs7U`UO`cQL26M+W@<6eJO+?CtX^4dV463v17aSVEt+|P zV!~d|61Ez=CwJTZc@Q(b%7 diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/git/logs/HEAD b/spring-cloud-config-server/src/test/resources/another-config-repo/git/logs/HEAD index 115205aa..152d7184 100644 --- a/spring-cloud-config-server/src/test/resources/another-config-repo/git/logs/HEAD +++ b/spring-cloud-config-server/src/test/resources/another-config-repo/git/logs/HEAD @@ -1,3 +1,4 @@ 0000000000000000000000000000000000000000 7df4a26d5437d9d4090cd5809967f870444cde8f Dave Syer 1406860717 -0700 7df4a26d5437d9d4090cd5809967f870444cde8f 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 Dave Syer 1415902155 +0000 checkout: moving from raw to master 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 c4bd92016dc14b9fe376d9c3f7af1c9d22d44ee4 Dave Syer 1415902338 +0000 commit: Move application.yml to subdir +c4bd92016dc14b9fe376d9c3f7af1c9d22d44ee4 3709aa0e4ed6d9c76fdf3a9980f2a7f84defd630 Marcin Grzejszczak 1549357674 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/git/logs/refs/heads/master b/spring-cloud-config-server/src/test/resources/another-config-repo/git/logs/refs/heads/master index dabf7fcd..0f970f01 100644 --- a/spring-cloud-config-server/src/test/resources/another-config-repo/git/logs/refs/heads/master +++ b/spring-cloud-config-server/src/test/resources/another-config-repo/git/logs/refs/heads/master @@ -1,2 +1,3 @@ 0000000000000000000000000000000000000000 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 Dave Syer 1406860776 -0700 branch: Created from 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 c4bd92016dc14b9fe376d9c3f7af1c9d22d44ee4 Dave Syer 1415902338 +0000 commit: Move application.yml to subdir +c4bd92016dc14b9fe376d9c3f7af1c9d22d44ee4 3709aa0e4ed6d9c76fdf3a9980f2a7f84defd630 Marcin Grzejszczak 1549357674 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/16/134a43183d280dc9bb3efce05c90c65d5c100a b/spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/16/134a43183d280dc9bb3efce05c90c65d5c100a new file mode 100644 index 0000000000000000000000000000000000000000..889a41a7e39b7350ca7b8106ddc8d86332094dfe GIT binary patch literal 33 pcmb0UjjR&y(ikHXJ zF!W6WnoX-B+Lr)Ak`Ra;f%hnm6MKYcZP-&_h)G;jGgTRzW=uJPv0Y}1DHd^|%aL6P zR4m5~kP$^t(Wl*~sxMTzAN9E|@^~-2&{H3V)lRpc?dI1}TaVHC&;`_6V~tU~zBc)< PqONnMCRu#}Z3<4-auQ0k literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/5f/72eaeb42ac3a2554e3cbc54291178a7c29be39 b/spring-cloud-config-server/src/test/resources/another-config-repo/git/objects/5f/72eaeb42ac3a2554e3cbc54291178a7c29be39 new file mode 100644 index 0000000000000000000000000000000000000000..be98dcaa5044cf0e34b0b8fecd9c57f8dbdc9037 GIT binary patch literal 88 zcmV-e0H^AVlXr?Ff%bxNJ=cyD=5k@NG&SKOf64W-v4`Ff%bxNGvGG$xKcx$;{8wtIW+|5EJ%tmax^}J-OTN R&x4o=$6{jyxB!+P5dN-<8Vmpc literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/git/refs/heads/master b/spring-cloud-config-server/src/test/resources/another-config-repo/git/refs/heads/master index 5ab04afa..288926bb 100644 --- a/spring-cloud-config-server/src/test/resources/another-config-repo/git/refs/heads/master +++ b/spring-cloud-config-server/src/test/resources/another-config-repo/git/refs/heads/master @@ -1 +1 @@ -c4bd92016dc14b9fe376d9c3f7af1c9d22d44ee4 +3709aa0e4ed6d9c76fdf3a9980f2a7f84defd630 diff --git a/spring-cloud-config-server/src/test/resources/another-config-repo/sub/application.yml b/spring-cloud-config-server/src/test/resources/another-config-repo/sub/application.yml index 8791c228..16134a43 100644 --- a/spring-cloud-config-server/src/test/resources/another-config-repo/sub/application.yml +++ b/spring-cloud-config-server/src/test/resources/another-config-repo/sub/application.yml @@ -1,2 +1,2 @@ -info: +info: foo: bar diff --git a/spring-cloud-config-server/src/test/resources/bad.yml b/spring-cloud-config-server/src/test/resources/bad.yml index fdd9e04d..33598709 100644 --- a/spring-cloud-config-server/src/test/resources/bad.yml +++ b/spring-cloud-config-server/src/test/resources/bad.yml @@ -1,4 +1,4 @@ foo: -# whitespace error! - bar: spam - bucket: wham \ No newline at end of file + # whitespace error! + bar: spam + bucket: wham diff --git a/spring-cloud-config-server/src/test/resources/compositeconfigserver.yml b/spring-cloud-config-server/src/test/resources/compositeconfigserver.yml index 65e1b217..4b3eafc1 100644 --- a/spring-cloud-config-server/src/test/resources/compositeconfigserver.yml +++ b/spring-cloud-config-server/src/test/resources/compositeconfigserver.yml @@ -6,4 +6,4 @@ spring: spring: cloud: config: - enabled: true \ No newline at end of file + enabled: true diff --git a/spring-cloud-config-server/src/test/resources/config-repo/application.yml b/spring-cloud-config-server/src/test/resources/config-repo/application.yml index d6acc405..7a68a4bb 100644 --- a/spring-cloud-config-server/src/test/resources/config-repo/application.yml +++ b/spring-cloud-config-server/src/test/resources/config-repo/application.yml @@ -1,3 +1,3 @@ -info: +info: foo: bar raw: true diff --git a/spring-cloud-config-server/src/test/resources/config-repo/bar.properties b/spring-cloud-config-server/src/test/resources/config-repo/bar.properties index 7daacd5d..ae3cdf5b 100644 --- a/spring-cloud-config-server/src/test/resources/config-repo/bar.properties +++ b/spring-cloud-config-server/src/test/resources/config-repo/bar.properties @@ -1 +1 @@ -foo: bar \ No newline at end of file +foo:bar diff --git a/spring-cloud-config-server/src/test/resources/config-repo/git/COMMIT_EDITMSG b/spring-cloud-config-server/src/test/resources/config-repo/git/COMMIT_EDITMSG new file mode 100644 index 00000000..c8fcd951 --- /dev/null +++ b/spring-cloud-config-server/src/test/resources/config-repo/git/COMMIT_EDITMSG @@ -0,0 +1 @@ +Updated diff --git a/spring-cloud-config-server/src/test/resources/config-repo/git/index b/spring-cloud-config-server/src/test/resources/config-repo/git/index index 95bd7dda7fa5a0dd8fec6fd83c92eb434a0f1397..eaa4dce20200bd4bd5ea2d3060731ffcfdde49e6 100644 GIT binary patch delta 202 zcmaFJ_>i&Q#WTp6fq{VugkvH?cJjRL%7W1hjLgi8E$q`67#f!_FfhM>Up2RYHRcp8WvybWm^edGW8vh+FMfX-7D-OqQgxqE?<4EE co1A;5o%GLSlC`~4pZ$mP%9Zx(BHJzi0P~MXtpET3 literal 225 zcmZ?q402{*U|<5_h!BzgK$-zYGcqu+F#PeI!@$tEgn@zaD^N-Vh-I#=Il?-3UE##+ zLwN?1K6I-*xxQu{1Ak&cK~83JVo7Fxo?c~c4p3qEmVcf=3QmK~v#I=pW*$fFs zE@vORKTTJb@$`%vh4xR6Fz_WM7U>lfb%7 diff --git a/spring-cloud-config-server/src/test/resources/config-repo/git/logs/HEAD b/spring-cloud-config-server/src/test/resources/config-repo/git/logs/HEAD index 9e452d3e..337958de 100644 --- a/spring-cloud-config-server/src/test/resources/config-repo/git/logs/HEAD +++ b/spring-cloud-config-server/src/test/resources/config-repo/git/logs/HEAD @@ -3,3 +3,4 @@ 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 7df4a26d5437d9d4090cd5809967f870444cde8f Ryan Baxter 1481905407 -0500 checkout: moving from master to raw 7df4a26d5437d9d4090cd5809967f870444cde8f 7df4a26d5437d9d4090cd5809967f870444cde8f Ryan Baxter 1481905544 -0500 checkout: moving from raw to composite 7df4a26d5437d9d4090cd5809967f870444cde8f 7df4a26d5437d9d4090cd5809967f870444cde8f Ryan Baxter 1481905552 -0500 checkout: moving from composite to raw +7df4a26d5437d9d4090cd5809967f870444cde8f 2921d46f948329996d3eb4a3d11aaaff6ccda84f Marcin Grzejszczak 1549357696 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/config-repo/git/logs/refs/heads/raw b/spring-cloud-config-server/src/test/resources/config-repo/git/logs/refs/heads/raw index c6423ee9..42582eeb 100644 --- a/spring-cloud-config-server/src/test/resources/config-repo/git/logs/refs/heads/raw +++ b/spring-cloud-config-server/src/test/resources/config-repo/git/logs/refs/heads/raw @@ -1 +1,2 @@ 0000000000000000000000000000000000000000 7df4a26d5437d9d4090cd5809967f870444cde8f Dave Syer 1406860717 -0700 +7df4a26d5437d9d4090cd5809967f870444cde8f 2921d46f948329996d3eb4a3d11aaaff6ccda84f Marcin Grzejszczak 1549357696 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/config-repo/git/objects/29/21d46f948329996d3eb4a3d11aaaff6ccda84f b/spring-cloud-config-server/src/test/resources/config-repo/git/objects/29/21d46f948329996d3eb4a3d11aaaff6ccda84f new file mode 100644 index 0000000000000000000000000000000000000000..3b755f17c5806a8b52d8867ff2b86e80321b4995 GIT binary patch literal 160 zcmV;R0AK%j0i}*P4#F@H0IB^7_ef}+tYfc)5FHgI4_Lfw&KxqP$?HLBcmVB4GnzE^ z{jJ&tVO5K&Wk+pv8BueJz>Op7&KOuSxJI)BpHv9QOk8xRHb_QpI`P;BAweKW;v;;u zkYfNuOrkLxe%I?*?2${l4farGy}#x(^TTfYh3zjtwwazg>pW8HLr0xmg99*Wd9C_i O#hfPLs$xF1i%r}mx=Jtr literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/config-repo/git/objects/7a/68a4bbc80b44c287787e2306ff9fd7de35cc54 b/spring-cloud-config-server/src/test/resources/config-repo/git/objects/7a/68a4bbc80b44c287787e2306ff9fd7de35cc54 new file mode 100644 index 0000000000000000000000000000000000000000..cd40d0e050f4052321e773f60f695b57ff7ce5eb GIT binary patch literal 43 zcmV+`0M!3@0ZYosPf{>4XUNP;%eUfEP)N(qw^B$-EaECkEVoi9DJo6n0sy?O3Z$+9 B5~2VA literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/config-repo/git/objects/a1/9381f44efc80a21996b47adf012ef105ced909 b/spring-cloud-config-server/src/test/resources/config-repo/git/objects/a1/9381f44efc80a21996b47adf012ef105ced909 new file mode 100644 index 0000000000000000000000000000000000000000..be1e3f09427d876cb2efe04550d77fc0e182392a GIT binary patch literal 97 zcmV-n0G|JN0V^p=O;xZkWiT`_Ff%bxNGvGG$xKcx$;{8wtIW+|sLEKf`vkYkq4tV8 zWw!tGuirC069QG5lvt!!P?TSgT2zvmTFkJ{=6-a?e+}t+jzVXRIYmoZtC%VPH~Aw4 DYYZ(O literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 b/spring-cloud-config-server/src/test/resources/config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 new file mode 100644 index 0000000000000000000000000000000000000000..8e49e7509f7e7d9160992d80ce2f4a3af9c14c2b GIT binary patch literal 23 fcmbB7!5IxO%>HV299+$_oF-h zYe?5~6gq3nDO$=}#ZXjq oxr$X~3CG4`cj|2BN3%i&Q#WTp6fq{Vugd+pB?1ZnWIfH1yxA(R%FmNz4fcRtW8hCLD9Fi7PAtjH&(o{S%>f!18K|+4)7W(>jE0!! znvP_iB+yU>j@ngcV|QH6K6Zbat}Nr}88-^;pB|YwLs8>-jmVj;KcCDI+;&A=yKKYd e^FHsxz9`@L-+#MK%EQlZ%AJerKV+;hNCW^i&Pv_@ diff --git a/spring-cloud-config-server/src/test/resources/encrypt-repo/git/logs/HEAD b/spring-cloud-config-server/src/test/resources/encrypt-repo/git/logs/HEAD index 0eda72a7..dc9c2ab0 100644 --- a/spring-cloud-config-server/src/test/resources/encrypt-repo/git/logs/HEAD +++ b/spring-cloud-config-server/src/test/resources/encrypt-repo/git/logs/HEAD @@ -5,3 +5,4 @@ 7df4a26d5437d9d4090cd5809967f870444cde8f 7df4a26d5437d9d4090cd5809967f870444cde8f Ryan Baxter 1481905552 -0500 checkout: moving from composite to raw 7df4a26d5437d9d4090cd5809967f870444cde8f 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 Dave Syer 1498491043 +0100 checkout: moving from raw to master 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 ad5e0cb7036ed11ddd4b7be6ed86ad3565c8a3fc Dave Syer 1498491468 +0100 commit: Add encrypted property +ad5e0cb7036ed11ddd4b7be6ed86ad3565c8a3fc bd414a6cc8653d7e282df0a257babc6283b83596 Marcin Grzejszczak 1549357702 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/encrypt-repo/git/logs/refs/heads/master b/spring-cloud-config-server/src/test/resources/encrypt-repo/git/logs/refs/heads/master index 4310fccd..5412791a 100644 --- a/spring-cloud-config-server/src/test/resources/encrypt-repo/git/logs/refs/heads/master +++ b/spring-cloud-config-server/src/test/resources/encrypt-repo/git/logs/refs/heads/master @@ -1,2 +1,3 @@ 0000000000000000000000000000000000000000 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 Dave Syer 1406860776 -0700 branch: Created from 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 9f01fb972bc9617e4ea59f5c8ee3ceb5ff515cd0 ad5e0cb7036ed11ddd4b7be6ed86ad3565c8a3fc Dave Syer 1498491468 +0100 commit: Add encrypted property +ad5e0cb7036ed11ddd4b7be6ed86ad3565c8a3fc bd414a6cc8653d7e282df0a257babc6283b83596 Marcin Grzejszczak 1549357702 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/encrypt-repo/git/objects/1d/3ce3ac9e4a7557e95e990c264470237ddb9488 b/spring-cloud-config-server/src/test/resources/encrypt-repo/git/objects/1d/3ce3ac9e4a7557e95e990c264470237ddb9488 new file mode 100644 index 0000000000000000000000000000000000000000..7bd56244d0f88167d97532411d96747d37202913 GIT binary patch literal 418 zcmV;T0bTxh0UeCXa;iW81+(TW++{&oAaAY8VnB%?pa>XrCosT>4B(9NNaf#eZg!`- zt50%ol9{COZwTkjikZ#wrdiFB>w{tD^EpG>2g1dF-aeWf-62`cAWk1+OPRF6Ir?*d z&HHzX+7do~zAHGc>XAZ1f7cK2jiw~RNjYd-gg%w46q=lI2@O4?vaj|p@0E_Z@*;vh z?u5%Za8=cN@?;OP=Mc4Sa_Vi4j4-V$D?YMiByRFhcyb$-Wh*eWQ*Nk<~U)$S(i z4tA`ex((9~NHt!^ZBVPQaxRyHfc)Sbd~uop3^m$2&J=dNgk-xZY`(vu z6;wQA^rTB$w<|^L5!V9RB^K!w6y+DB7L{bC7Bj4~xgXu}UqiZ{qtIDnPSH}`2II;-r-jVq;?D0gmlLftD(SrLPCE@BqfU;dJ~M z$D!ILz^WEii;7GUypOJZSW=|9Mwo$bJ literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/encrypt-repo/git/refs/heads/master b/spring-cloud-config-server/src/test/resources/encrypt-repo/git/refs/heads/master index ae0c4a61..51053139 100644 --- a/spring-cloud-config-server/src/test/resources/encrypt-repo/git/refs/heads/master +++ b/spring-cloud-config-server/src/test/resources/encrypt-repo/git/refs/heads/master @@ -1 +1 @@ -ad5e0cb7036ed11ddd4b7be6ed86ad3565c8a3fc +bd414a6cc8653d7e282df0a257babc6283b83596 diff --git a/spring-cloud-config-server/src/test/resources/foo-cloud.properties b/spring-cloud-config-server/src/test/resources/foo-cloud.properties index 9e019360..0184332c 100644 --- a/spring-cloud-config-server/src/test/resources/foo-cloud.properties +++ b/spring-cloud-config-server/src/test/resources/foo-cloud.properties @@ -1 +1 @@ -bar: cloud \ No newline at end of file +bar:cloud diff --git a/spring-cloud-config-server/src/test/resources/foo-development.properties b/spring-cloud-config-server/src/test/resources/foo-development.properties index 15b07370..02b13487 100644 --- a/spring-cloud-config-server/src/test/resources/foo-development.properties +++ b/spring-cloud-config-server/src/test/resources/foo-development.properties @@ -1 +1 @@ -bar: spam \ No newline at end of file +bar:spam diff --git a/spring-cloud-config-server/src/test/resources/foo-local.txt b/spring-cloud-config-server/src/test/resources/foo-local.txt index b3694701..f925e4be 100644 --- a/spring-cloud-config-server/src/test/resources/foo-local.txt +++ b/spring-cloud-config-server/src/test/resources/foo-local.txt @@ -1 +1 @@ -foo: local \ No newline at end of file +foo: local diff --git a/spring-cloud-config-server/src/test/resources/foo.properties b/spring-cloud-config-server/src/test/resources/foo.properties index 7daacd5d..ae3cdf5b 100644 --- a/spring-cloud-config-server/src/test/resources/foo.properties +++ b/spring-cloud-config-server/src/test/resources/foo.properties @@ -1 +1 @@ -foo: bar \ No newline at end of file +foo:bar diff --git a/spring-cloud-config-server/src/test/resources/keystore-bootstrap.yml b/spring-cloud-config-server/src/test/resources/keystore-bootstrap.yml index b5950933..9d148a21 100644 --- a/spring-cloud-config-server/src/test/resources/keystore-bootstrap.yml +++ b/spring-cloud-config-server/src/test/resources/keystore-bootstrap.yml @@ -10,4 +10,4 @@ encrypt: location: classpath:server.jks password: letmein alias: myKey - \ No newline at end of file + diff --git a/spring-cloud-config-server/src/test/resources/master-labeltest-config-repo/git/COMMIT_EDITMSG b/spring-cloud-config-server/src/test/resources/master-labeltest-config-repo/git/COMMIT_EDITMSG index 1b5f2002..c8fcd951 100644 --- a/spring-cloud-config-server/src/test/resources/master-labeltest-config-repo/git/COMMIT_EDITMSG +++ b/spring-cloud-config-server/src/test/resources/master-labeltest-config-repo/git/COMMIT_EDITMSG @@ -1 +1 @@ -test case +Updated diff --git a/spring-cloud-config-server/src/test/resources/master-labeltest-config-repo/git/index b/spring-cloud-config-server/src/test/resources/master-labeltest-config-repo/git/index index 728ccc4dbd1cbdfa48e623778e4b5f10b6c42326..26b10e7c708016f5a391620bc9b033b6aed1f6fb 100644 GIT binary patch delta 124 zcmaFKc#YA(#WTp6fq{VugkvIt8RX6%>4VV>jLgi8E$lNH7#f!_FfhLW;fV%1Dj<1z up0h158mjIfin<1CX*LF3Lj?ma7o+&MYd4$4U#WTp6fq{VughQ?z1yT$QFq#o0KJn*$28PBZRYq!$L2?rfbW}pF9GMGI z2ce0~!yOJG{Geqx(na n*l7>B_cpWS`HJv3KAs$P*WtAP`%kj(`DgJeYI}9G@!bOe4Ni%` literal 393 zcmZ?q402{*U|<4b=CCt;za@gD*w++A4~40Bc84hsW~2g|YL s-VqRgUVHLZU1%(u-43U);6EzgTYDnj5u?00ARm}Z2$lO diff --git a/spring-cloud-config-server/src/test/resources/nested-repo/git/logs/HEAD b/spring-cloud-config-server/src/test/resources/nested-repo/git/logs/HEAD index 60dce6c4..3a37da54 100644 --- a/spring-cloud-config-server/src/test/resources/nested-repo/git/logs/HEAD +++ b/spring-cloud-config-server/src/test/resources/nested-repo/git/logs/HEAD @@ -1 +1,2 @@ 0000000000000000000000000000000000000000 012b8908f80e4d19436ffaabcd08bf32f43644ec Dave Syer 1456246639 +0000 commit (initial): Two nested dirs +012b8908f80e4d19436ffaabcd08bf32f43644ec 9d6f44a27376f0dbe4722099e138904788ef561a Marcin Grzejszczak 1549357722 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/nested-repo/git/logs/refs/heads/master b/spring-cloud-config-server/src/test/resources/nested-repo/git/logs/refs/heads/master index 60dce6c4..3a37da54 100644 --- a/spring-cloud-config-server/src/test/resources/nested-repo/git/logs/refs/heads/master +++ b/spring-cloud-config-server/src/test/resources/nested-repo/git/logs/refs/heads/master @@ -1 +1,2 @@ 0000000000000000000000000000000000000000 012b8908f80e4d19436ffaabcd08bf32f43644ec Dave Syer 1456246639 +0000 commit (initial): Two nested dirs +012b8908f80e4d19436ffaabcd08bf32f43644ec 9d6f44a27376f0dbe4722099e138904788ef561a Marcin Grzejszczak 1549357722 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/nested-repo/git/objects/16/134a43183d280dc9bb3efce05c90c65d5c100a b/spring-cloud-config-server/src/test/resources/nested-repo/git/objects/16/134a43183d280dc9bb3efce05c90c65d5c100a new file mode 100644 index 0000000000000000000000000000000000000000..889a41a7e39b7350ca7b8106ddc8d86332094dfe GIT binary patch literal 33 pcmb8U@$Z=Ff%bxNGvGG$xKcx$;{8wD=5k@NG&SKOf67FlI0`FfcPQQAjK($jMAjEXmBz)2qzQVGtAca+a{w;61t9 z?$3jm3CCh%1h`BLfIuNBv53L;{~4RRXEYxNocJ#zc+~o9IcrTAL^drypW*QC(v9vP XonxmxO}L literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/nested-repo/git/objects/9d/6f44a27376f0dbe4722099e138904788ef561a b/spring-cloud-config-server/src/test/resources/nested-repo/git/objects/9d/6f44a27376f0dbe4722099e138904788ef561a new file mode 100644 index 00000000..d9605d23 --- /dev/null +++ b/spring-cloud-config-server/src/test/resources/nested-repo/git/objects/9d/6f44a27376f0dbe4722099e138904788ef561a @@ -0,0 +1 @@ +x¥Î;!€akNAob†×‰1vV–`]uAlöôšm<€íWüùi†¾ImaÓj)2bÌ8£rÎë³fÍNq§MHž”QbÆZÆ&Aé"PlVÑšŽ1Q†Øhþ‚µ…¾ÛmªòŒ•úQžêR|Èý°Úñú³Ýü8U@$Z=Ff%bxNGvGG$xKcx$;{8wD=5k@NG&SKOf6>kmGyoK Z|BcOg&o+E~ywS+V@ZYyr3jk<88OvBj9UTAw literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/nested-repo/git/objects/fa/6aef940fd8b36ee6b0f1e3b1324c31fef6eaa0 b/spring-cloud-config-server/src/test/resources/nested-repo/git/objects/fa/6aef940fd8b36ee6b0f1e3b1324c31fef6eaa0 new file mode 100644 index 0000000000000000000000000000000000000000..6e055e08ae778451807fe35a9a4be02d43b5d618 GIT binary patch literal 21 dcmb$4U#WTp6fq{VughQ?z1yT$QFq#o0KJn*$28PBZRYq!$L2?rfbW}pF9GMGI z2ce?3* z-cRAbu{rPAhL4Xo8u=Lh`}S(VL=PDokUob0C#HevL;I&e^?yXyzs}}3WVr zXN@^UOIfR!Dkd%vQ49%kbp^UZlEFy9fGd0Jg_#md=G=b8xF%r7)huHdhwFS3w}goN Y-lmv2L#4Bg<+cg)2hE?t+8n`*08Xh#=l}o! delta 168 zcmdnXG>6H<#WTp6fq{Vugu~*t9MN7~xgJI{FmNz4ToCPJU}#*zz`* 1449047236 +0000 rebase -i (squash): Move application.yml to subdir dfe21d586fc45ba72db173421c5139e26e50a7af dfe21d586fc45ba72db173421c5139e26e50a7af Dave Syer 1449047243 +0000 rebase -i (finish): returning to refs/heads/master dfe21d586fc45ba72db173421c5139e26e50a7af 29f2b1020f4b87e1de6aab368ff496cc4e99a959 Dave Syer 1449047248 +0000 commit (amend): Add application.properties +29f2b1020f4b87e1de6aab368ff496cc4e99a959 df6fc33edab5de1a6faaaa141de2ff0d99fb99e2 Marcin Grzejszczak 1549357756 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/test2-config-repo/git/logs/refs/heads/master b/spring-cloud-config-server/src/test/resources/test2-config-repo/git/logs/refs/heads/master index 588ca3bb..e68a2b39 100644 --- a/spring-cloud-config-server/src/test/resources/test2-config-repo/git/logs/refs/heads/master +++ b/spring-cloud-config-server/src/test/resources/test2-config-repo/git/logs/refs/heads/master @@ -3,3 +3,4 @@ c4bd92016dc14b9fe376d9c3f7af1c9d22d44ee4 dfd1f2f006c9ea71be688e3eeaf383ff640fd21a Dave Syer 1449047214 +0000 commit: Fix dfd1f2f006c9ea71be688e3eeaf383ff640fd21a dfe21d586fc45ba72db173421c5139e26e50a7af Dave Syer 1449047243 +0000 rebase -i (finish): refs/heads/master onto c4bd92016dc14b9fe376d9c3f7af1c9d22d44ee4 dfe21d586fc45ba72db173421c5139e26e50a7af 29f2b1020f4b87e1de6aab368ff496cc4e99a959 Dave Syer 1449047248 +0000 commit (amend): Add application.properties +29f2b1020f4b87e1de6aab368ff496cc4e99a959 df6fc33edab5de1a6faaaa141de2ff0d99fb99e2 Marcin Grzejszczak 1549357756 +0100 commit: Updated diff --git a/spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/6b/b5d09918a49cdbea01ac50b8d56a334440d70e b/spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/6b/b5d09918a49cdbea01ac50b8d56a334440d70e new file mode 100644 index 0000000000000000000000000000000000000000..493358f80a0597bd6667a33ed660b5a95aeb651f GIT binary patch literal 95 zcmV-l0HFVP0V^p=O;xZoVlXr?Ff%bxNGvGG$xKcx$;{8wD=5k@NG&SKOf6>kmGyoK z|BcOg&o+E~ywS+V@ZYyr3!plZ5{r;kuCuux-SJ;Tx}KxZSz}JoQr0S_3INwqD9xh1 BEN}n- literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 b/spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/ae/3cdf5b88ff281b7f087143289c72a5057a0278 new file mode 100644 index 0000000000000000000000000000000000000000..8e49e7509f7e7d9160992d80ce2f4a3af9c14c2b GIT binary patch literal 23 fcmbok>_>eni`-vJT==2)!^)1=AKT5(gEkJyy0&#*Z@~blxV~2T Quc9t<;wnjf04v2#dZn^PZvX%Q literal 0 HcmV?d00001 diff --git a/spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/fa/6aef940fd8b36ee6b0f1e3b1324c31fef6eaa0 b/spring-cloud-config-server/src/test/resources/test2-config-repo/git/objects/fa/6aef940fd8b36ee6b0f1e3b1324c31fef6eaa0 new file mode 100644 index 0000000000000000000000000000000000000000..6e055e08ae778451807fe35a9a4be02d43b5d618 GIT binary patch literal 21 dcmb - + 4.0.0 org.springframework.cloud diff --git a/spring-cloud-starter-config/src/main/resources/META-INF/spring.provides b/spring-cloud-starter-config/src/main/resources/META-INF/spring.provides index 3628be6e..7ab18867 100644 --- a/spring-cloud-starter-config/src/main/resources/META-INF/spring.provides +++ b/spring-cloud-starter-config/src/main/resources/META-INF/spring.provides @@ -1 +1 @@ -provides: spring-cloud-config-client \ No newline at end of file +provides: spring-cloud-config-client diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml new file mode 100644 index 00000000..57a18a24 --- /dev/null +++ b/src/checkstyle/checkstyle-suppressions.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + +