diff --git a/.flattened-pom.xml b/.flattened-pom.xml new file mode 100644 index 000000000..66602fa5a --- /dev/null +++ b/.flattened-pom.xml @@ -0,0 +1,134 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-build + 4.1.0-SNAPSHOT + + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + pom + Spring Cloud Zookeeper + Spring Cloud Zookeeper + https://spring.io/spring-cloud/spring-cloud-zookeeper + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git + https://github.com/spring-cloud/spring-cloud-zookeeper + + + + spring + + + + false + + + true + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + + + false + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + false + + spring-releases + Spring Releases + https://repo.spring.io/release + + + + + diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index eb9a16ae6..000000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,45 +0,0 @@ - -# Contributing - -Spring Cloud is released under the non-restrictive Apache 2.0 license, -and follows a very standard Github development process, using Github -tracker for issues and merging pull requests into master. If you want -to contribute even something trivial please do not hesitate, but -follow the guidelines below. - -## Sign the Contributor License Agreement -Before we accept a non-trivial patch or pull request we will need you to sign the -[Contributor License Agreement](https://cla.pivotal.io/sign/spring). -Signing the contributor's agreement does not grant anyone commit rights to the main -repository, but it does mean that we can accept your contributions, and you will get an -author credit if we do. Active contributors might be asked to join the core team, and -given the ability to merge pull requests. - -## Code of Conduct -This project adheres to the Contributor Covenant [code of -conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report -unacceptable behavior to spring-code-of-conduct@pivotal.io. - -## Code Conventions and Housekeeping -None of these is essential for a pull request, but they will all help. They can also be -added after the original pull request but before a merge. - -* Use the Spring Framework code format conventions. If you use Eclipse - you can import formatter settings using the - `eclipse-code-formatter.xml` file from the - [Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the - [Eclipse Code Formatter Plugin](https://plugins.jetbrains.com/plugin/6546) to import the same file. -* Make sure all new `.java` files to have a simple Javadoc class comment with at least an - `@author` tag identifying you, and preferably at least a paragraph on what the class is - for. -* Add the ASF license header comment to all new `.java` files (copy from existing files - in the project) -* Add yourself as an `@author` to the .java files that you modify substantially (more - than cosmetic changes). -* Add some Javadocs and, if you change the namespace, some XSD doc elements. -* A few unit tests would help a lot as well -- someone has to do it. -* If no-one else is using your branch, please rebase it against the current master (or - other target branch in the main project). -* When writing a commit message please follow [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html), - if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit - message (where XXXX is the issue number). diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 0bc5ef4fa..000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,20 +0,0 @@ - diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index aeafef9d3..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: '' -labels: '' -assignees: '' - ---- - -**Describe the bug** -Please provide details of the problem, including the version of Spring Cloud that you -are using. - -**Sample** -If possible, please provide a test case or sample application that reproduces -the problem. This makes it much easier for us to diagnose the problem and to verify that -we have fixed it. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index bbcbbe7d6..000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: '' -assignees: '' - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml new file mode 100644 index 000000000..6114dd1c6 --- /dev/null +++ b/.github/workflows/deploy-docs.yml @@ -0,0 +1,53 @@ +name: Deploy Docs +run-name: ${{ format('{0} ({1})', github.workflow, github.event.inputs.build-refname || 'all') }} +on: + workflow_dispatch: + inputs: + build-refname: + description: Enter git refname to build (e.g., 5.7.x). + required: false + push: + branches: docs-build +env: + GRADLE_ENTERPRISE_SECRET_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_SECRET_ACCESS_KEY }} +permissions: + contents: write +jobs: + build: + if: github.repository_owner == 'spring-cloud' + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 5 + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + - name: Set up refname build + if: github.event.inputs.build-refname + run: | + git fetch --depth 1 https://github.com/$GITHUB_REPOSITORY ${{ github.event.inputs.build-refname }} + export BUILD_REFNAME=${{ github.event.inputs.build-refname }} + echo "BUILD_REFNAME=$BUILD_REFNAME" >> $GITHUB_ENV + export BUILD_VERSION=$(git cat-file --textconv FETCH_HEAD:pom.xml | python3 -c "import xml.etree.ElementTree as xml; from sys import stdin; print(xml.parse(stdin).getroot().find('{http://maven.apache.org/POM/4.0.0}version').text)") + echo BUILD_VERSION=$BUILD_VERSION >> $GITHUB_ENV + - name: Run Antora + run: | + ./mvnw --no-transfer-progress -B antora + - name: Publish Docs + uses: spring-io/spring-doc-actions/rsync-antora-reference@v0.0.11 + with: + docs-username: ${{ secrets.DOCS_USERNAME }} + docs-host: ${{ secrets.DOCS_HOST }} + docs-ssh-key: ${{ secrets.DOCS_SSH_KEY }} + docs-ssh-host-key: ${{ secrets.DOCS_SSH_HOST_KEY }} + site-path: target/antora/site + - name: Bust Cloudflare Cache + uses: spring-io/spring-doc-actions/bust-cloudflare-antora-cache@v0.0.11 + with: + context-root: spring-cloud-zookeeper + cloudflare-zone-id: ${{ secrets.CLOUDFLARE_ZONE_ID }} + cloudflare-cache-token: ${{ secrets.CLOUDFLARE_CACHE_TOKEN }} diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml deleted file mode 100644 index 98bf13c3d..000000000 --- a/.github/workflows/maven.yml +++ /dev/null @@ -1,37 +0,0 @@ -# This workflow will build a Java project with Maven -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven - -name: Build - -on: - push: - branches: [ main, 3.1.x ] - pull_request: - branches: [ main, 3.1.x ] - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up JDK - uses: actions/setup-java@v2 - with: - distribution: 'temurin' - java-version: '17' - - name: Cache local Maven repository - uses: actions/cache@v2 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven- - - name: Build with Maven - run: ./mvnw clean install -B -U -Pspring -Dmaven.test.redirectTestOutputToFile=true - - name: Publish Test Report - uses: mikepenz/action-junit-report@v2 - if: always() # always run even if the previous step fails - with: - report_paths: '**/surefire-reports/TEST-*.xml' \ No newline at end of file diff --git a/.gitignore b/.gitignore index 84d578d91..6be8a4a16 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,22 @@ -*~ -#* -*# -.#* -.classpath -.project +target/ .settings/ -.factorypath +.project +.classpath +*.orig .springBeans -target/ -_site/ -.idea -*.iml -*.swp -*.log -.checkstyle +.factorypath +.sts4-cache +.ant-targets-build.xml +src/ant/.ant-targets-upload-dist.xml +*.sonar4clipse* .DS_Store -.vscode/ -.flattened-pom.xml +*.iml +*.ipr +*.iws +/.idea/ +*.graphml +node +node_modules +build +package.json +package-lock.json diff --git a/.java-version b/.java-version deleted file mode 100644 index 98d9bcb75..000000000 --- a/.java-version +++ /dev/null @@ -1 +0,0 @@ -17 diff --git a/.mvn/maven.config b/.mvn/maven.config deleted file mode 100644 index a68299056..000000000 --- a/.mvn/maven.config +++ /dev/null @@ -1 +0,0 @@ --P spring diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 000000000..b901097f2 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present 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. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar index 5fd4d5023..2cc7d4a55 100644 Binary files a/.mvn/wrapper/maven-wrapper.jar and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 6686a643d..642d572ce 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,18 +1,2 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.0/apache-maven-3.9.0-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/.sdkmanrc b/.sdkmanrc deleted file mode 100644 index 415f90832..000000000 --- a/.sdkmanrc +++ /dev/null @@ -1,3 +0,0 @@ -# Enable auto-env through the sdkman_auto_env config -# Add key=value pairs of SDKs to use below -java=17.0.1-tem diff --git a/.settings.xml b/.settings.xml deleted file mode 100644 index 248255ff7..000000000 --- a/.settings.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - repo.spring.io - ${env.CI_DEPLOY_USERNAME} - ${env.CI_DEPLOY_PASSWORD} - - - - - - spring - true - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone-local - - false - - - - spring-releases - Spring Releases - https://repo.spring.io/release - - false - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone-local - - false - - - - - - diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 62589edd1..000000000 --- a/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/README.adoc b/README.adoc index ba34bba3e..e0fd60033 100644 --- a/README.adoc +++ b/README.adoc @@ -1,629 +1,23 @@ -//// -DO NOT EDIT THIS FILE. IT WAS GENERATED. -Manual changes to this file will be lost when it is generated again. -Edit the files in the src/main/asciidoc/ directory instead. -//// += Spring Cloud Zookeeper Docs Build +You're currently viewing the Antora playbook branch. +The playbook branch hosts the docs build that is used to build and publish the production docs site. -image::https://travis-ci.org/spring-cloud/spring-cloud-zookeeper.svg?branch=master[Build Status, link=https://travis-ci.org/spring-cloud/spring-cloud-zookeeper] +The Spring Cloud Zookeeper reference docs are built using https://antora.org[Antora]. +This README covers how to build the docs in a software branch as well as how to build the production docs site locally. +== Building the Site +You can build the entire site by invoking the following on the docs-build branch and then viewing the site at `target/site/index.html` -:doctype: book -:idprefix: -:idseparator: - -:toc: left -:toclevels: 4 -:tabsize: 4 -:numbered: -:sectanchors: -:sectnums: -:icons: font -:hide-uri-scheme: -:docinfo: shared,private - -:sc-ext: java -:project-full-name: Spring Cloud Zookeeper - -This project provides Zookeeper integrations for Spring Boot applications through -autoconfiguration and binding to the Spring Environment and other Spring programming model -idioms. With a few annotations, you can quickly enable and configure the common patterns -inside your application and build large distributed systems with Zookeeper based -components. The provided patterns include Service Discovery and Configuration. The project -also provides client-side load-balancing via integration with Spring Cloud LoadBalancer. - - -:doctype: book -:idprefix: -:idseparator: - -:toc: left -:toclevels: 4 -:tabsize: 4 -:numbered: -:sectanchors: -:sectnums: -:icons: font -:hide-uri-scheme: -:docinfo: shared,private - -:sc-ext: java -:project-full-name: Spring Cloud Zookeeper - -== Quick Start - -This quick start walks through using Spring Cloud Zookeeper for Service Discovery and Distributed Configuration. - -First, run Zookeeper on your machine. Then you can access it and use it as a Service Registry and Configuration source with Spring Cloud Zookeeper. - -=== Discovery Client Usage - -To use these features in an application, you can build it as a Spring Boot application that depends on `spring-cloud-zookeeper-core` and `spring-cloud-zookeeper-discovery`. -The most convenient way to add the dependency is with a Spring Boot starter: `org.springframework.cloud:spring-cloud-starter-zookeeper-discovery`. -We recommend using dependency management and `spring-boot-starter-parent`. -The following example shows a typical Maven configuration: - -[source,xml,indent=0] -.pom.xml ----- - - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - - - - - - org.springframework.cloud - spring-cloud-starter-zookeeper-discovery - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - ----- - -The following example shows a typical Gradle setup: - -[source,groovy,indent=0] -.build.gradle ----- -plugins { - id 'org.springframework.boot' version ${spring-boot-version} - id 'io.spring.dependency-management' version ${spring-dependency-management-version} - id 'java' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.cloud:spring-cloud-starter-zookeeper-discovery' - testImplementation 'org.springframework.boot:spring-boot-starter-test' -} -dependencyManagement { - imports { - mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" - } -} ----- - -WARNING: Depending on the version you are using, you might need to adjust Apache Zookeeper version used in your project. -You can read more about it in the <>. - -Now you can create a standard Spring Boot application, such as the following HTTP server: - ----- -@SpringBootApplication -@RestController -public class Application { - - @GetMapping("/") - public String home() { - return "Hello World!"; - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} ----- - -When this HTTP server runs, it connects to Zookeeper, which runs on the default local port (2181). -To modify the startup behavior, you can change the location of Zookeeper by using `application.properties`, as shown in the following example: - ----- -spring: - cloud: - zookeeper: - connect-string: localhost:2181 ----- - -You can now use `DiscoveryClient`, `@LoadBalanced RestTemplate`, or `@LoadBalanced WebClient.Builder` to retrieve services and instances data from Zookeeper, as shown in the following example: - -[source,java,indent=0] ----- -@Autowired -private DiscoveryClient discoveryClient; - -public String serviceUrl() { - List list = discoveryClient.getInstances("STORES"); - if (list != null && list.size() > 0 ) { - return list.get(0).getUri().toString(); - } - return null; -} +[source,bash] ---- - -=== Distributed Configuration Usage - -To use these features in an application, you can build it as a Spring Boot application that depends on `spring-cloud-zookeeper-core` and `spring-cloud-zookeeper-config`. -The most convenient way to add the dependency is with a Spring Boot starter: `org.springframework.cloud:spring-cloud-starter-zookeeper-config`. -We recommend using dependency management and `spring-boot-starter-parent`. -The following example shows a typical Maven configuration: - -[source,xml,indent=0] -.pom.xml ----- - - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - - - - - - org.springframework.cloud - spring-cloud-starter-zookeeper-config - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - ----- - -The following example shows a typical Gradle setup: - -[source,groovy,indent=0] -.build.gradle ----- -plugins { - id 'org.springframework.boot' version ${spring-boot-version} - id 'io.spring.dependency-management' version ${spring-dependency-management-version} - id 'java' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.cloud:spring-cloud-starter-zookeeper-config' - testImplementation 'org.springframework.boot:spring-boot-starter-test' -} -dependencyManagement { - imports { - mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" - } -} ----- - -WARNING: Depending on the version you are using, you might need to adjust Apache Zookeeper version used in your project. -You can read more about it in the <>. - -Now you can create a standard Spring Boot application, such as the following HTTP server: - ----- -@SpringBootApplication -@RestController -public class Application { - - @GetMapping("/") - public String home() { - return "Hello World!"; - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} +./mvnw antora ---- -The application retrieves configuration data from Zookeeper. - -WARNING: If you use Spring Cloud Zookeeper Config, you need to set the `spring.config.import` property in order to bind to Zookeeper. -You can read more about it in the <>. - -== Zookeeper overview - -ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services. -See the -https://zookeeper.apache.org[Zookeeper site] for more information. -Spring Cloud Zookeeper also builds on the https://curator.apache.org[Apache Curator] project, which started life at Netflix. - -== Spring Cloud Zookeeper Features - -Spring Cloud Zookeeper includes the following features: - -* Spring Cloud `DiscoveryClient` implementation (supports Spring Cloud LoadBalancer) -* Zookeeper-based `PropertySource` loaded during the 'bootstrap' phase - -== Running the Sample - -. https://zookeeper.apache.org/doc/current/zookeeperStarted.html#sc_Download[Install -zookeeper] (On a mac with homebrew, use `brew install zookeeper`). -. https://zookeeper.apache.org/doc/current/zookeeperStarted.html#sc_InstallingSingleMode[Start -zookeeper]. -. https://zookeeper.apache.org/doc/current/zookeeperStarted.html#sc_ConnectingToZooKeeper[Verify -zookeeper is running]. -. Run `mvn --settings .settings.xml package`. -Doing so brings in the required Spring Cloud Maven repositories and Build. -. Run `java -jar spring-cloud-zookeeper-sample/target/spring-cloud-zookeeper-sample-1.2.0.BUILD-SNAPSHOT.jar`. -. Visit http://localhost:8080 to verify that `{"serviceId":"testZookeeperApp","host":"","port":8080}` works. -. Run `java -jar spring-cloud-zookeeper-sample/target/spring-cloud-zookeeper-sample-1.2.0.BUILD-SNAPSHOT.jar --server.port=8081` -. Visit http://localhost:8080 again to verify that `{"serviceId":"testZookeeperApp","host":"","port":8081}` eventually shows up in the results in a round-robin fashion. (It may take a minute or so.) - -== Building - -:jdkversion: 17 - -=== Basic Compile and Test - -To build the source you will need to install JDK {jdkversion}. - -Spring Cloud uses Maven for most build-related activities, and you -should be able to get off the ground quite quickly by cloning the -project you are interested in and typing +== Building a Specific Branch +[source,bash] ---- -$ ./mvnw install +./mvnw antora ---- - -NOTE: You can also install Maven (>=3.3.3) yourself and run the `mvn` command -in place of `./mvnw` in the examples below. If you do that you also -might need to add `-P spring` if your local Maven settings do not -contain repository declarations for spring pre-release artifacts. - -NOTE: Be aware that you might need to increase the amount of memory -available to Maven by setting a `MAVEN_OPTS` environment variable with -a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in -the `.mvn` configuration, so if you find you have to do it to make a -build succeed, please raise a ticket to get the settings added to -source control. - -The projects that require middleware (i.e. Redis) for testing generally -require that a local instance of [Docker](https://www.docker.com/get-started) is installed and running. - - -=== Documentation - -The spring-cloud-build module has a "docs" profile, and if you switch -that on it will try to build asciidoc sources from -`src/main/asciidoc`. As part of that process it will look for a -`README.adoc` and process it by loading all the includes, but not -parsing or rendering it, just copying it to `${main.basedir}` -(defaults to `${basedir}`, i.e. the root of the project). If there are -any changes in the README it will then show up after a Maven build as -a modified file in the correct place. Just commit it and push the change. - -=== Working with the code -If you don't have an IDE preference we would recommend that you use -https://www.springsource.com/developer/sts[Spring Tools Suite] or -https://eclipse.org[Eclipse] when working with the code. We use the -https://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools -should also work without issue as long as they use Maven 3.3.3 or better. - -==== Activate the Spring Maven profile -Spring Cloud projects require the 'spring' Maven profile to be activated to resolve -the spring milestone and snapshot repositories. Use your preferred IDE to set this -profile to be active, or you may experience build errors. - -==== Importing into eclipse with m2eclipse -We recommend the https://eclipse.org/m2e/[m2eclipse] eclipse plugin when working with -eclipse. If you don't already have m2eclipse installed it is available from the "eclipse -marketplace". - -NOTE: Older versions of m2e do not support Maven 3.3, so once the -projects are imported into Eclipse you will also need to tell -m2eclipse to use the right profile for the projects. If you -see many different errors related to the POMs in the projects, check -that you have an up to date installation. If you can't upgrade m2e, -add the "spring" profile to your `settings.xml`. Alternatively you can -copy the repository settings from the "spring" profile of the parent -pom into your `settings.xml`. - -==== Importing into eclipse without m2eclipse -If you prefer not to use m2eclipse you can generate eclipse project metadata using the -following command: - -[indent=0] ----- - $ ./mvnw eclipse:eclipse ----- - -The generated eclipse projects can be imported by selecting `import existing projects` -from the `file` menu. - - -== Contributing - -:spring-cloud-build-branch: master - -Spring Cloud is released under the non-restrictive Apache 2.0 license, -and follows a very standard Github development process, using Github -tracker for issues and merging pull requests into master. If you want -to contribute even something trivial please do not hesitate, but -follow the guidelines below. - -=== Sign the Contributor License Agreement -Before we accept a non-trivial patch or pull request we will need you to sign the -https://cla.pivotal.io/sign/spring[Contributor License Agreement]. -Signing the contributor's agreement does not grant anyone commit rights to the main -repository, but it does mean that we can accept your contributions, and you will get an -author credit if we do. Active contributors might be asked to join the core team, and -given the ability to merge pull requests. - -=== Code of Conduct -This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of -conduct]. By participating, you are expected to uphold this code. Please report -unacceptable behavior to spring-code-of-conduct@pivotal.io. - -=== Code Conventions and Housekeeping -None of these is essential for a pull request, but they will all help. They can also be -added after the original pull request but before a merge. - -* Use the Spring Framework code format conventions. If you use Eclipse - you can import formatter settings using the - `eclipse-code-formatter.xml` file from the - https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring - Cloud Build] project. If using IntelliJ, you can use the - https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter - Plugin] to import the same file. -* Make sure all new `.java` files to have a simple Javadoc class comment with at least an - `@author` tag identifying you, and preferably at least a paragraph on what the class is - for. -* Add the ASF license header comment to all new `.java` files (copy from existing files - in the project) -* Add yourself as an `@author` to the .java files that you modify substantially (more - than cosmetic changes). -* Add some Javadocs and, if you change the namespace, some XSD doc elements. -* A few unit tests would help a lot as well -- someone has to do it. -* If no-one else is using your branch, please rebase it against the current master (or - other target branch in the main project). -* When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], - if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit - message (where XXXX is the issue number). - -=== Checkstyle - -Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are: - -.spring-cloud-build-tools/ ----- -└── src -    ├── checkstyle -    │   └── checkstyle-suppressions.xml <3> -    └── main -    └── resources -    ├── checkstyle-header.txt <2> -    └── checkstyle.xml <1> ----- -<1> Default Checkstyle rules -<2> File header setup -<3> Default suppression rules - -==== Checkstyle configuration - -Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins. - -.pom.xml ----- - -true <1> - true - <2> - true - <3> - - - - - <4> - io.spring.javaformat - spring-javaformat-maven-plugin - - <5> - org.apache.maven.plugins - maven-checkstyle-plugin - - - - - - <5> - org.apache.maven.plugins - maven-checkstyle-plugin - - - - ----- -<1> Fails the build upon Checkstyle errors -<2> Fails the build upon Checkstyle violations -<3> Checkstyle analyzes also the test sources -<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules -<5> Add checkstyle plugin to your build and reporting phases - -If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example: - -.projectRoot/src/checkstyle/checkstyle-suppresions.xml ----- - - - - - - ----- - -It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script: - -```bash -$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig -$ touch .springformat -``` - -=== IDE setup - -==== Intellij IDEA - -In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. -The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project. - -.spring-cloud-build-tools/ ----- -└── src -    ├── checkstyle -    │   └── checkstyle-suppressions.xml <3> -    └── main -    └── resources -    ├── checkstyle-header.txt <2> -    ├── checkstyle.xml <1> -    └── intellij -       ├── Intellij_Project_Defaults.xml <4> -       └── Intellij_Spring_Boot_Java_Conventions.xml <5> ----- -<1> Default Checkstyle rules -<2> File header setup -<3> Default suppression rules -<4> Project defaults for Intellij that apply most of Checkstyle rules -<5> Project style conventions for Intellij that apply most of Checkstyle rules - -.Code style - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style] - -Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file. - -.Inspection profiles - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style] - -Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file. - -.Checkstyle - -To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle] - -Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables: - -- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL. -- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL. -- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`. - -IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. - -=== Duplicate Finder - -Spring Cloud Build brings along the `basepom:duplicate-finder-maven-plugin`, that enables flagging duplicate and conflicting classes and resources on the java classpath. - -==== Duplicate Finder configuration - -Duplicate finder is *enabled by default* and will run in the `verify` phase of your Maven build, but it will only take effect in your project if you add the `duplicate-finder-maven-plugin` to the `build` section of the projecst's `pom.xml`. - -.pom.xml -[source,xml] ----- - - - - org.basepom.maven - duplicate-finder-maven-plugin - - - ----- - -For other properties, we have set defaults as listed in the https://github.com/basepom/duplicate-finder-maven-plugin/wiki[plugin documentation]. - -You can easily override them but setting the value of the selected property prefixed with `duplicate-finder-maven-plugin`. For example, set `duplicate-finder-maven-plugin.skip` to `true` in order to skip duplicates check in your build. - -If you need to add `ignoredClassPatterns` or `ignoredResourcePatterns` to your setup, make sure to add them in the plugin configuration section of your project: - -[source,xml] ----- - - - - org.basepom.maven - duplicate-finder-maven-plugin - - - org.joda.time.base.BaseDateTime - .*module-info - - - changelog.txt - - - - - - - ----- - diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index 046859563..000000000 --- a/SECURITY.md +++ /dev/null @@ -1,5 +0,0 @@ -# Security Policy - -## Reporting a Vulnerability - -To report security vulnerabilities, please go to https://pivotal.io/security. diff --git a/docs/antora-playbook.yml b/antora-playbook.yml similarity index 61% rename from docs/antora-playbook.yml rename to antora-playbook.yml index 9a70e676c..06396649a 100644 --- a/docs/antora-playbook.yml +++ b/antora-playbook.yml @@ -6,38 +6,39 @@ antora: - '@antora/collector-extension' - '@antora/atlas-extension' - require: '@springio/antora-extensions/root-component-extension' - root_component_name: 'PROJECT_WITHOUT_SPRING' - # FIXME: Run antora once using this extension to migrate to the Asciidoc Tabs syntax - # and then remove this extension - - require: '@springio/antora-extensions/tabs-migration-extension' - unwrap_example_block: always - save_result: true + root_component_name: 'cloud-zookeeper' site: - title: PROJECT_FULL_NAME - url: https://docs.spring.io/PROJECT_NAME/reference/ + title: Spring Cloud Zookeeper + url: https://docs.spring.io/spring-cloud-zookeeper/reference + robots: allow +git: + ensure_git_suffix: false content: sources: - - url: ./.. - branches: HEAD + - url: https://github.com/spring-cloud/spring-cloud-zookeeper + # Refname matching: + # https://docs.antora.org/antora/latest/playbook/content-refname-matching/ + branches: [ main ] + tags: [ '({4..9}).+({1..9}).+({0..9})?(-{RC,M}+({0..9}))', '!4.1.0-M1' ] start_path: docs - worktrees: true asciidoc: attributes: page-stackoverflow-url: https://stackoverflow.com/tags/spring-cloud page-pagination: '' hide-uri-scheme: '@' tabs-sync-option: '@' - chomp: 'all' extensions: - '@asciidoctor/tabs' - '@springio/asciidoctor-extensions' - sourcemap: true urls: + latest_version_segment_strategy: redirect:to latest_version_segment: '' + redirect_facility: httpd +ui: + bundle: + url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.3.5/ui-bundle.zip + snapshot: true runtime: log: failure_level: warn format: pretty -ui: - bundle: - url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.3.5/ui-bundle.zip diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index 829bce759..000000000 --- a/docker-compose.yml +++ /dev/null @@ -1,4 +0,0 @@ -zookeeper: - image: zookeeper - ports: - - "2181:2181" diff --git a/docs/.flattened-pom.xml b/docs/.flattened-pom.xml new file mode 100644 index 000000000..ec32b55fe --- /dev/null +++ b/docs/.flattened-pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + + org.springframework.cloud + spring-cloud-zookeeper-docs + 4.1.0-SNAPSHOT + Spring Cloud Zookeeper Docs + Spring Cloud Docs + https://spring.io/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-docs + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-docs + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-docs + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-docs + + + + org.springframework.cloud + spring-cloud-starter-zookeeper-all + 4.1.0-SNAPSHOT + compile + + + diff --git a/docs/.github/workflows/deploy-docs.yml b/docs/.github/workflows/deploy-docs.yml deleted file mode 100644 index be4b92dfc..000000000 --- a/docs/.github/workflows/deploy-docs.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: Deploy Docs -on: - push: - branches-ignore: [ gh-pages ] - tags: '**' - repository_dispatch: - types: request-build-reference # legacy - #schedule: - #- cron: '0 10 * * *' # Once per day at 10am UTC - workflow_dispatch: -permissions: - actions: write -jobs: - build: - runs-on: ubuntu-latest - # if: github.repository_owner == 'spring-cloud' - steps: - - name: Checkout - uses: actions/checkout@v3 - with: - ref: docs-build - fetch-depth: 1 - - name: Dispatch (partial build) - if: github.ref_type == 'branch' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: gh workflow run deploy-docs.yml -r $(git rev-parse --abbrev-ref HEAD) -f build-refname=${{ github.ref_name }} - - name: Dispatch (full build) - if: github.ref_type == 'tag' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: gh workflow run deploy-docs.yml -r $(git rev-parse --abbrev-ref HEAD) diff --git a/docs/antora.yml b/docs/antora.yml deleted file mode 100644 index 15b346da0..000000000 --- a/docs/antora.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: PROJECT_WITHOUT_SPRING -version: true -title: PROJECT_NAME -nav: - - modules/ROOT/nav.adoc -ext: - collector: - run: - command: ./mvnw --no-transfer-progress -B process-resources -Pdocs -pl docs -Dantora-maven-plugin.phase=none -Dgenerate-docs.phase=none -Dgenerate-readme.phase=none -Dgenerate-cloud-resources.phase=none -Dmaven-dependency-plugin-for-docs.phase=none -Dmaven-dependency-plugin-for-docs-classes.phase=none -DskipTests - local: true - scan: - dir: ./target/classes/antora-resources/ diff --git a/docs/modules/ROOT/assets/images/.gitkeep b/docs/modules/ROOT/assets/images/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc deleted file mode 100644 index eb712b7d8..000000000 --- a/docs/modules/ROOT/nav.adoc +++ /dev/null @@ -1,18 +0,0 @@ -* xref:index.adoc[] -* xref:spring-cloud-zookeeper.adoc[] -** xref:spring-cloud-zookeeper/quick-start.adoc[] -** xref:spring-cloud-zookeeper/install.adoc[] -** xref:spring-cloud-zookeeper/discovery.adoc[] -** xref:spring-cloud-zookeeper/other-componentes.adoc[] -** xref:spring-cloud-zookeeper/service-registry.adoc[] -** xref:spring-cloud-zookeeper/dependencies.adoc[] -** xref:spring-cloud-zookeeper/dependency-watcher.adoc[] -** xref:spring-cloud-zookeeper/config.adoc[] -* xref:intro.adoc[] -* xref:_attributes.adoc[] -* xref:quickstart.adoc[] -* xref:README.adoc[] -* xref:_configprops.adoc[] -* xref:appendix.adoc[] -* xref:sagan-boot.adoc[] -* xref:sagan-index.adoc[] diff --git a/docs/modules/ROOT/pages/README.adoc b/docs/modules/ROOT/pages/README.adoc deleted file mode 100644 index bc52c72b7..000000000 --- a/docs/modules/ROOT/pages/README.adoc +++ /dev/null @@ -1,49 +0,0 @@ -image::https://travis-ci.org/spring-cloud/spring-cloud-zookeeper.svg?branch=master[Build Status, link=https://travis-ci.org/spring-cloud/spring-cloud-zookeeper] - - - -[[quick-start]] -= Quick Start - - -[[zookeeper-overview]] -= Zookeeper overview - -ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services. -See the -https://zookeeper.apache.org[Zookeeper site] for more information. -Spring Cloud Zookeeper also builds on the https://curator.apache.org[Apache Curator] project, which started life at Netflix. - -[[spring-cloud-zookeeper-features]] -= Spring Cloud Zookeeper Features - -Spring Cloud Zookeeper includes the following features: - -* Spring Cloud `DiscoveryClient` implementation (supports Spring Cloud LoadBalancer) -* Zookeeper-based `PropertySource` loaded during the 'bootstrap' phase - -[[running-the-sample]] -= Running the Sample - -. https://zookeeper.apache.org/doc/current/zookeeperStarted.html#sc_Download[Install -zookeeper] (On a mac with homebrew, use `brew install zookeeper`). -. https://zookeeper.apache.org/doc/current/zookeeperStarted.html#sc_InstallingSingleMode[Start -zookeeper]. -. https://zookeeper.apache.org/doc/current/zookeeperStarted.html#sc_ConnectingToZooKeeper[Verify -zookeeper is running]. -. Run `mvn --settings .settings.xml package`. -Doing so brings in the required Spring Cloud Maven repositories and Build. -. Run `java -jar spring-cloud-zookeeper-sample/target/spring-cloud-zookeeper-sample-1.2.0.BUILD-SNAPSHOT.jar`. -. Visit http://localhost:8080 to verify that `{"serviceId":"testZookeeperApp","host":"","port":8080}` works. -. Run `java -jar spring-cloud-zookeeper-sample/target/spring-cloud-zookeeper-sample-1.2.0.BUILD-SNAPSHOT.jar --server.port=8081` -. Visit http://localhost:8080 again to verify that `{"serviceId":"testZookeeperApp","host":"","port":8081}` eventually shows up in the results in a round-robin fashion. (It may take a minute or so.) - -[[building]] -= Building - -include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/building.adoc[] - -[[contributing]] -= Contributing - -include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[] diff --git a/docs/modules/ROOT/pages/_attributes.adoc b/docs/modules/ROOT/pages/_attributes.adoc deleted file mode 100644 index c26a2d097..000000000 --- a/docs/modules/ROOT/pages/_attributes.adoc +++ /dev/null @@ -1,14 +0,0 @@ - -:doctype: book -:idprefix: -:idseparator: - -:tabsize: 4 -:numbered: -:sectanchors: -:sectnums: -:icons: font -:hide-uri-scheme: -:docinfo: shared,private - -:sc-ext: java -:project-full-name: Spring Cloud Zookeeper diff --git a/docs/modules/ROOT/pages/_configprops.adoc b/docs/modules/ROOT/pages/_configprops.adoc deleted file mode 100644 index 451fd2458..000000000 --- a/docs/modules/ROOT/pages/_configprops.adoc +++ /dev/null @@ -1,35 +0,0 @@ -|=== -|Name | Default | Description - -|spring.cloud.zookeeper.base-sleep-time-ms | `+++50+++` | Initial amount of time to wait between retries. -|spring.cloud.zookeeper.block-until-connected-unit | | The unit of time related to blocking on connection to Zookeeper. -|spring.cloud.zookeeper.block-until-connected-wait | `+++10+++` | Wait time to block on connection to Zookeeper. -|spring.cloud.zookeeper.config.default-context | `+++application+++` | The name of the default context. -|spring.cloud.zookeeper.config.enabled | `+++true+++` | -|spring.cloud.zookeeper.config.fail-fast | `+++true+++` | Throw exceptions during config lookup if true, otherwise, log warnings. -|spring.cloud.zookeeper.config.name | | Alternative to spring.application.name to use in looking up values in zookeeper. -|spring.cloud.zookeeper.config.profile-separator | `+++,+++` | Separator for profile appended to the application name. -|spring.cloud.zookeeper.config.root | `+++config+++` | Root folder where the configuration for Zookeeper is kept. -|spring.cloud.zookeeper.connect-string | `+++localhost:2181+++` | Connection string to the Zookeeper cluster. -|spring.cloud.zookeeper.connection-timeout | | The configured connection timeout in milliseconds. -|spring.cloud.zookeeper.dependencies | | Mapping of alias to ZookeeperDependency. From LoadBalancer perspective the alias is actually serviceID since SC LoadBalancer can't accept nested structures in serviceID. -|spring.cloud.zookeeper.dependency-configurations | | -|spring.cloud.zookeeper.dependency-names | | -|spring.cloud.zookeeper.discovery.enabled | `+++true+++` | -|spring.cloud.zookeeper.discovery.initial-status | | The initial status of this instance (defaults to {@link StatusConstants#STATUS_UP}). -|spring.cloud.zookeeper.discovery.instance-host | | Predefined host with which a service can register itself in Zookeeper. Corresponds to the {code address} from the URI spec. -|spring.cloud.zookeeper.discovery.instance-id | | Id used to register with zookeeper. Defaults to a random UUID. -|spring.cloud.zookeeper.discovery.instance-port | | Port to register the service under (defaults to listening port). -|spring.cloud.zookeeper.discovery.instance-ssl-port | | Ssl port of the registered service. -|spring.cloud.zookeeper.discovery.metadata | | Gets the metadata name/value pairs associated with this instance. This information is sent to zookeeper and can be used by other instances. -|spring.cloud.zookeeper.discovery.order | `+++0+++` | Order of the discovery client used by `CompositeDiscoveryClient` for sorting available clients. -|spring.cloud.zookeeper.discovery.register | `+++true+++` | Register as a service in zookeeper. -|spring.cloud.zookeeper.discovery.root | `+++/services+++` | Root Zookeeper folder in which all instances are registered. -|spring.cloud.zookeeper.discovery.uri-spec | `+++{scheme}://{address}:{port}+++` | The URI specification to resolve during service registration in Zookeeper. -|spring.cloud.zookeeper.enabled | `+++true+++` | Is Zookeeper enabled. -|spring.cloud.zookeeper.max-retries | `+++10+++` | Max number of times to retry. -|spring.cloud.zookeeper.max-sleep-ms | `+++500+++` | Max time in ms to sleep on each retry. -|spring.cloud.zookeeper.prefix | | Common prefix that will be applied to all Zookeeper dependencies' paths. -|spring.cloud.zookeeper.session-timeout | | The configured/negotiated session timeout in milliseconds. Please refer to Curator's Tech Note 14 to understand how Curator implements connection sessions. @see Curator's Tech Note 14 - -|=== diff --git a/docs/modules/ROOT/pages/appendix.adoc b/docs/modules/ROOT/pages/appendix.adoc deleted file mode 100644 index eef1c9056..000000000 --- a/docs/modules/ROOT/pages/appendix.adoc +++ /dev/null @@ -1,13 +0,0 @@ -:numbered!: -[appendix] -[[common-application-properties]] -= Common application properties -:page-section-summary-toc: 1 - - -Various properties can be specified inside your `application.properties` file, inside your `application.yml` file, or as command line switches. -This appendix provides a list of common {project-full-name} properties and references to the underlying classes that consume them. - -NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list. -Also, you can define your own properties. - diff --git a/docs/modules/ROOT/pages/index.adoc b/docs/modules/ROOT/pages/index.adoc deleted file mode 100755 index e69de29bb..000000000 diff --git a/docs/modules/ROOT/pages/intro.adoc b/docs/modules/ROOT/pages/intro.adoc deleted file mode 100644 index b6e6b4c4b..000000000 --- a/docs/modules/ROOT/pages/intro.adoc +++ /dev/null @@ -1,8 +0,0 @@ - - -This project provides Zookeeper integrations for Spring Boot applications through -autoconfiguration and binding to the Spring Environment and other Spring programming model -idioms. With a few annotations, you can quickly enable and configure the common patterns -inside your application and build large distributed systems with Zookeeper based -components. The provided patterns include Service Discovery and Configuration. The project -also provides client-side load-balancing via integration with Spring Cloud LoadBalancer. diff --git a/docs/modules/ROOT/pages/quickstart.adoc b/docs/modules/ROOT/pages/quickstart.adoc deleted file mode 100644 index 0ae4f4c9f..000000000 --- a/docs/modules/ROOT/pages/quickstart.adoc +++ /dev/null @@ -1,234 +0,0 @@ -This quick start walks through using Spring Cloud Zookeeper for Service Discovery and Distributed Configuration. - -First, run Zookeeper on your machine. Then you can access it and use it as a Service Registry and Configuration source with Spring Cloud Zookeeper. - -[[discovery-client-usage]] -= Discovery Client Usage - -To use these features in an application, you can build it as a Spring Boot application that depends on `spring-cloud-zookeeper-core` and `spring-cloud-zookeeper-discovery`. -The most convenient way to add the dependency is with a Spring Boot starter: `org.springframework.cloud:spring-cloud-starter-zookeeper-discovery`. -We recommend using dependency management and `spring-boot-starter-parent`. -The following example shows a typical Maven configuration: - -[source,xml,indent=0] -.pom.xml ----- - - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - - - - - - org.springframework.cloud - spring-cloud-starter-zookeeper-discovery - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - ----- - -The following example shows a typical Gradle setup: - -[source,groovy,indent=0] -.build.gradle ----- -plugins { - id 'org.springframework.boot' version ${spring-boot-version} - id 'io.spring.dependency-management' version ${spring-dependency-management-version} - id 'java' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.cloud:spring-cloud-starter-zookeeper-discovery' - testImplementation 'org.springframework.boot:spring-boot-starter-test' -} -dependencyManagement { - imports { - mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" - } -} ----- - -WARNING: Depending on the version you are using, you might need to adjust Apache Zookeeper version used in your project. -You can read more about it in the xref:spring-cloud-zookeeper/install.adoc[Install Zookeeper section]. - -Now you can create a standard Spring Boot application, such as the following HTTP server: - ----- -@SpringBootApplication -@RestController -public class Application { - - @GetMapping("/") - public String home() { - return "Hello World!"; - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} ----- - -When this HTTP server runs, it connects to Zookeeper, which runs on the default local port (2181). -To modify the startup behavior, you can change the location of Zookeeper by using `application.properties`, as shown in the following example: - ----- -spring: - cloud: - zookeeper: - connect-string: localhost:2181 ----- - -You can now use `DiscoveryClient`, `@LoadBalanced RestTemplate`, or `@LoadBalanced WebClient.Builder` to retrieve services and instances data from Zookeeper, as shown in the following example: - -[source,java,indent=0] ----- -@Autowired -private DiscoveryClient discoveryClient; - -public String serviceUrl() { - List list = discoveryClient.getInstances("STORES"); - if (list != null && list.size() > 0 ) { - return list.get(0).getUri().toString(); - } - return null; -} ----- - -[[distributed-configuration-usage]] -= Distributed Configuration Usage - -To use these features in an application, you can build it as a Spring Boot application that depends on `spring-cloud-zookeeper-core` and `spring-cloud-zookeeper-config`. -The most convenient way to add the dependency is with a Spring Boot starter: `org.springframework.cloud:spring-cloud-starter-zookeeper-config`. -We recommend using dependency management and `spring-boot-starter-parent`. -The following example shows a typical Maven configuration: - -[source,xml,indent=0] -.pom.xml ----- - - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - - - - - - org.springframework.cloud - spring-cloud-starter-zookeeper-config - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - ----- - -The following example shows a typical Gradle setup: - -[source,groovy,indent=0] -.build.gradle ----- -plugins { - id 'org.springframework.boot' version ${spring-boot-version} - id 'io.spring.dependency-management' version ${spring-dependency-management-version} - id 'java' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.cloud:spring-cloud-starter-zookeeper-config' - testImplementation 'org.springframework.boot:spring-boot-starter-test' -} -dependencyManagement { - imports { - mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" - } -} ----- - -WARNING: Depending on the version you are using, you might need to adjust Apache Zookeeper version used in your project. -You can read more about it in the xref:spring-cloud-zookeeper/install.adoc[Install Zookeeper section]. - -Now you can create a standard Spring Boot application, such as the following HTTP server: - ----- -@SpringBootApplication -@RestController -public class Application { - - @GetMapping("/") - public String home() { - return "Hello World!"; - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} ----- - -The application retrieves configuration data from Zookeeper. - -WARNING: If you use Spring Cloud Zookeeper Config, you need to set the `spring.config.import` property in order to bind to Zookeeper. -You can read more about it in the xref:spring-cloud-zookeeper/config.adoc#config-data-import[Spring Boot Config Data Import section]. diff --git a/docs/modules/ROOT/pages/sagan-boot.adoc b/docs/modules/ROOT/pages/sagan-boot.adoc deleted file mode 100644 index 8b1378917..000000000 --- a/docs/modules/ROOT/pages/sagan-boot.adoc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/docs/modules/ROOT/pages/sagan-index.adoc b/docs/modules/ROOT/pages/sagan-index.adoc deleted file mode 100644 index 1da6a8884..000000000 --- a/docs/modules/ROOT/pages/sagan-index.adoc +++ /dev/null @@ -1,38 +0,0 @@ - - -Spring Cloud Zookeeper provides http://zookeeper.apache.org/[Apache Zookeeper] integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms. With a few simple annotations you can quickly enable and configure the common patterns inside your application and build large distributed systems with Zookeeper. The patterns provided include Service Discovery and Distributed Configuration. - -## Features - -* Service Discovery: instances can be registered with Zookeeper and clients can discover the instances using Spring-managed beans - * Supports Spring Cloud LoadBalancer - client-side load-balancing solution - * Supports Spring Cloud OpenFeign -* Distributed Configuration: using Zookeeper as a data store - -## Quick Start - -As long as Spring Cloud Zookeeper, http://curator.apache.org/[Apache Curator] and the Zookeeper Java Client are on the -classpath any Spring Boot application with `@EnableDiscoveryClient` will try to contact a Zookeeper -agent on `localhost:2181` (the default value of -`zookeeper.connectString`). - -```java -@Configuration -@EnableAutoConfiguration -@EnableDiscoveryClient -@RestController -public class Application { - - @RequestMapping("/") - public String home() { - return "Hello World"; - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} -``` - -A local Zookeeper server must be running. See the http://zookeeper.apache.org/[Zookeeper documentation] on how to run a Zookeeper server. diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper.adoc deleted file mode 100644 index 7ebf8bafe..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper.adoc +++ /dev/null @@ -1,7 +0,0 @@ - -[[spring-cloud-zookeeper]] -= Spring Cloud Zookeeper -:page-section-summary-toc: 1 - - - diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper/config.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper/config.adoc deleted file mode 100644 index a4f5b4a4d..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper/config.adoc +++ /dev/null @@ -1,143 +0,0 @@ -[[spring-cloud-zookeeper-config]] -= Distributed Configuration with Zookeeper - -Zookeeper provides a -https://zookeeper.apache.org/doc/current/zookeeperOver.html#sc_dataModelNameSpace[hierarchical namespace] -that lets clients store arbitrary data, such as configuration data. Spring Cloud Zookeeper -Config is an alternative to the -https://github.com/spring-cloud/spring-cloud-config[Config Server and Client]. -Configuration is loaded into the Spring Environment during the special "`bootstrap`" -phase. Configuration is stored in the `/config` namespace by default. Multiple -`PropertySource` instances are created, based on the application's name and the active -profiles, to mimic the Spring Cloud Config order of resolving properties. For example, an -application with a name of `testApp` and with the `dev` profile has the following property -sources created for it: - -* `config/testApp,dev` -* `config/testApp` -* `config/application,dev` -* `config/application` - -The most specific property source is at the top, with the least specific at the bottom. -Properties in the `config/application` namespace apply to all applications that use -zookeeper for configuration. Properties in the `config/testApp` namespace are available -only to the instances of the service named `testApp`. - -Configuration is currently read on startup of the application. Sending a HTTP `POST` -request to `/refresh` causes the configuration to be reloaded. Watching the configuration -namespace (which Zookeeper supports) is not currently implemented. - -[[activating]] -== Activating - -Including a dependency on -`org.springframework.cloud:spring-cloud-starter-zookeeper-config` enables -autoconfiguration that sets up Spring Cloud Zookeeper Config. - -CAUTION: When working with version 3.4 of Zookeeper you need to change -the way you include the dependency as described xref:spring-cloud-zookeeper/install.adoc[here]. - -[[config-data-import]] -== Spring Boot Config Data Import - -Spring Boot 2.4 introduced a new way to import configuration data via the `spring.config.import` property. This is now the default way to get configuration from Zookeeper. - -To optionally connect to Zookeeper for configuration set the following in application.properties: - -.application.properties -[source,properties] ----- -spring.config.import=optional:zookeeper: ----- - -This will connect to Zookeeper at the default location of "localhost:2181". Removing the `optional:` prefix will cause Zookeeper Config to fail if it is unable to connect to Zookeeper. To change the connection properties of Zookeeper Config either set `spring.cloud.zookeeper.connect-string` or add the connect string to the `spring.config.import` statement such as, `spring.config.import=optional:zookeeper:myhost:2818`. The location in the import property has precedence over the `connect-string` property. - -Zookeeper Config will try to load values from four automatic contexts based on `spring.cloud.zookeeper.config.name` (which defaults to the value of the `spring.application.name` property) and `spring.cloud.zookeeper.config.default-context` (which defaults to `application`). If you want to specify the contexts rather than using the computed ones, you can add that information to the `spring.config.import` statement. - -.application.properties -[source,properties] ----- -spring.config.import=optional:zookeeper:myhost:2181/contextone;/context/two ----- - -This will optionally load configuration only from `/contextone` and `/context/two`. - -NOTE: A `bootstrap` file (properties or yaml) is *not* needed for the Spring Boot Config Data method of import via `spring.config.import`. - -[[customizing]] -== Customizing - -Zookeeper Config may be customized by setting the following properties: - -[source,yml,indent=0] ----- -spring: - cloud: - zookeeper: - config: - enabled: true - root: configuration - defaultContext: apps - profileSeparator: '::' ----- - -* `enabled`: Setting this value to `false` disables Zookeeper Config. -* `root`: Sets the base namespace for configuration values. -* `defaultContext`: Sets the name used by all applications. -* `profileSeparator`: Sets the value of the separator used to separate the profile name in -property sources with profiles. - -CAUTION: If you have set `spring.cloud.bootstrap.enabled=true` or `spring.config.use-legacy-processing=true`, or included `spring-cloud-starter-bootstrap`, then the above values will need to be placed in `bootstrap.yml` instead of `application.yml`. - -[[access-control-lists-acls]] -== Access Control Lists (ACLs) - -You can add authentication information for Zookeeper ACLs by calling the `addAuthInfo` -method of a `CuratorFramework` bean. One way to accomplish this is to provide your own -`CuratorFramework` bean, as shown in the following example: - -[source,java,indent=0] ----- -@BoostrapConfiguration -public class CustomCuratorFrameworkConfig { - - @Bean - public CuratorFramework curatorFramework() { - CuratorFramework curator = new CuratorFramework(); - curator.addAuthInfo("digest", "user:password".getBytes()); - return curator; - } - -} ----- -Consult -https://github.com/spring-cloud/spring-cloud-zookeeper/blob/master/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfiguration.java[the ZookeeperAutoConfiguration class] -to see how the `CuratorFramework` bean's default configuration. - -Alternatively, you can add your credentials from a class that depends on the existing -`CuratorFramework` bean, as shown in the following example: - -[source,java,indent=0] ----- -@BoostrapConfiguration -public class DefaultCuratorFrameworkConfig { - - public ZookeeperConfig(CuratorFramework curator) { - curator.addAuthInfo("digest", "user:password".getBytes()); - } - -} ----- - -The creation of this bean must occur during the boostrapping phase. You can register -configuration classes to run during this phase by annotating them with -`@BootstrapConfiguration` and including them in a comma-separated list that you set as the -value of the `org.springframework.cloud.bootstrap.BootstrapConfiguration` property in the -`resources/META-INF/spring.factories` file, as shown in the following example: - -.resources/META-INF/spring.factories ----- -org.springframework.cloud.bootstrap.BootstrapConfiguration=\ -my.project.CustomCuratorFrameworkConfig,\ -my.project.DefaultCuratorFrameworkConfig ----- diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper/dependencies.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper/dependencies.adoc deleted file mode 100644 index 9c6606b66..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper/dependencies.adoc +++ /dev/null @@ -1,208 +0,0 @@ -[[spring-cloud-zookeeper-dependencies]] -= Zookeeper Dependencies - -The following topics cover how to work with Spring Cloud Zookeeper dependencies: - -* xref:spring-cloud-zookeeper/dependencies.adoc#spring-cloud-zookeeper-dependencies-using[Using the Zookeeper Dependencies] -* xref:spring-cloud-zookeeper/dependencies.adoc#spring-cloud-zookeeper-dependencies-activating[Activating Zookeeper Dependencies] -* xref:spring-cloud-zookeeper/dependencies.adoc#spring-cloud-zookeeper-dependencies-setting-up[Setting up Zookeeper Dependencies] -* xref:spring-cloud-zookeeper/dependencies.adoc#spring-cloud-zookeeper-dependencies-configuring[Configuring Spring Cloud Zookeeper Dependencies] - -[[spring-cloud-zookeeper-dependencies-using]] -== Using the Zookeeper Dependencies - -Spring Cloud Zookeeper gives you a possibility to provide dependencies of your application -as properties. As dependencies, you can understand other applications that are registered -in Zookeeper and which you would like to call through -https://github.com/spring-cloud/spring-cloud-netflix/blob/master/docs/src/main/asciidoc/spring-cloud-netflix.adoc#spring-cloud-feign[Feign] -(a REST client builder), -https://github.com/spring-cloud/spring-cloud-netflix/blob/master/docs/src/main/ascii[Spring -`RestTemplate`] and -https://cloud.spring.io/spring-cloud-commons/reference/html/#loadbalanced-webclient[Spring WebFlux]. - -You can also use the Zookeeper Dependency Watchers functionality to control and monitor -the state of your dependencies. - -[[spring-cloud-zookeeper-dependencies-activating]] -== Activating Zookeeper Dependencies - -Including a dependency on -`org.springframework.cloud:spring-cloud-starter-zookeeper-discovery` enables -autoconfiguration that sets up Spring Cloud Zookeeper Dependencies. Even if you provide -the dependencies in your properties, you can turn off the dependencies. To do so, set the -`spring.cloud.zookeeper.dependency.enabled` property to false (it defaults to `true`). - -[[spring-cloud-zookeeper-dependencies-setting-up]] -== Setting up Zookeeper Dependencies - -Consider the following example of dependency representation: - -[source,yml,indent=0] -.application.yml ----- -spring.application.name: yourServiceName -spring.cloud.zookeeper: - dependencies: - newsletter: - path: /path/where/newsletter/has/registered/in/zookeeper - loadBalancerType: ROUND_ROBIN - contentTypeTemplate: application/vnd.newsletter.$version+json - version: v1 - headers: - header1: - - value1 - header2: - - value2 - required: false - stubs: org.springframework:foo:stubs - mailing: - path: /path/where/mailing/has/registered/in/zookeeper - loadBalancerType: ROUND_ROBIN - contentTypeTemplate: application/vnd.mailing.$version+json - version: v1 - required: true ----- - -The next few sections go through each part of the dependency one by one. The root property -name is `spring.cloud.zookeeper.dependencies`. - -[[spring-cloud-zookeeper-dependencies-setting-up-aliases]] -=== Aliases - -Below the root property you have to represent each dependency as an alias. -This is due to the constraints of Spring Cloud LoadBalancer, which requires that the application ID be placed in the URL. -Consequently, you cannot pass any complex path, suchas `/myApp/myRoute/name`). -The alias is the name you use instead of the `serviceId` for `DiscoveryClient`, `Feign`, or -`RestTemplate`. - -In the previous examples, the aliases are `newsletter` and `mailing`. -The following example shows Feign usage with a `newsletter` alias: - -[source,java,indent=0] ----- -@FeignClient("newsletter") -public interface NewsletterService { - @RequestMapping(method = RequestMethod.GET, value = "/newsletter") - String getNewsletters(); -} ----- - -[[path]] -=== Path - -The path is represented by the `path` YAML property and is the path under which the dependency is registered under Zookeeper. -As described in the -xref:spring-cloud-zookeeper/dependencies.adoc#spring-cloud-zookeeper-dependencies-setting-up-aliases[previous section], Spring Cloud LoadBalancer operates on URLs. -As a result, this path is not compliant with its requirement. -That is why Spring Cloud Zookeeper maps the alias to the proper path. - -[[load-balancer-type]] -=== Load Balancer Type - -The load balancer type is represented by `loadBalancerType` YAML property. - -If you know what kind of load-balancing strategy has to be applied when calling this particular dependency, you can provide it in the YAML file, and it is automatically applied. -You can choose one of the following load balancing strategies: - -* STICKY: Once chosen, the instance is always called. -* RANDOM: Picks an instance randomly. -* ROUND_ROBIN: Iterates over instances over and over again. - -[[content-type-template-and-version]] -=== `Content-Type` Template and Version - -The `Content-Type` template and version are represented by the `contentTypeTemplate` and -`version` YAML properties. - -If you version your API in the `Content-Type` header, you do not want to add this header -to each of your requests. Also, if you want to call a new version of the API, you do not -want to roam around your code to bump up the API version. That is why you can provide a -`contentTypeTemplate` with a special `$version` placeholder. That placeholder will be filled by the value of the -`version` YAML property. Consider the following example of a `contentTypeTemplate`: - ----- -application/vnd.newsletter.$version+json ----- - -Further consider the following `version`: - ----- -v1 ----- - -The combination of `contentTypeTemplate` and version results in the creation of a -`Content-Type` header for each request, as follows: - ----- -application/vnd.newsletter.v1+json ----- - -[[default-headers]] -=== Default Headers - -Default headers are represented by the `headers` map in YAML. - -Sometimes, each call to a dependency requires setting up of some default headers. To not -do that in code, you can set them up in the YAML file, as shown in the following example -`headers` section: - -[source,yml,indent=0] ----- -headers: - Accept: - - text/html - - application/xhtml+xml - Cache-Control: - - no-cache ----- - -That `headers` section results in adding the `Accept` and `Cache-Control` headers with -appropriate list of values in your HTTP request. - -[[required-dependencies]] -=== Required Dependencies - -Required dependencies are represented by `required` property in YAML. - -If one of your dependencies is required to be up when your application boots, you can set -the `required: true` property in the YAML file. - -If your application cannot localize the required dependency during boot time, it throws an -exception, and the Spring Context fails to set up. In other words, your application cannot -start if the required dependency is not registered in Zookeeper. - -You can read more about Spring Cloud Zookeeper Presence Checker -xref:spring-cloud-zookeeper/dependency-watcher.adoc#spring-cloud-zookeeper-dependency-watcher-presence-checker[later in this document]. - -[[stubs]] -=== Stubs - -You can provide a colon-separated path to the JAR containing stubs of the dependency, as -shown in the following example: - -`stubs: org.springframework:myApp:stubs` - -where: - -* `org.springframework` is the `groupId`. -* `myApp` is the `artifactId`. -* `stubs` is the classifier. (Note that `stubs` is the default value.) - -Because `stubs` is the default classifier, the preceding example is equal to the following -example: - -`stubs: org.springframework:myApp` - -[[spring-cloud-zookeeper-dependencies-configuring]] -== Configuring Spring Cloud Zookeeper Dependencies - -You can set the following properties to enable or disable parts of Zookeeper Dependencies functionalities: - -* `spring.cloud.zookeeper.dependencies`: If you do not set this property, you cannot use Zookeeper Dependencies. -* `spring.cloud.zookeeper.dependency.loadbalancer.enabled` (enabled by default): Turns on Zookeeper-specific custom load-balancing strategies, including `ZookeeperServiceInstanceListSupplier` and dependency-based load-balanced `RestTemplate` setup. -* `spring.cloud.zookeeper.dependency.headers.enabled` (enabled by default): This property registers a `FeignBlockingLoadBalancerClient` that automatically appends appropriate headers and content types with their versions, as presented in the Dependency configuration. -Without this setting, those two parameters do not work. -* `spring.cloud.zookeeper.dependency.resttemplate.enabled` (enabled by default): When enabled, this property modifies the request headers of a `@LoadBalanced`-annotated -`RestTemplate` such that it passes headers and content type with the version set in dependency configuration. -Without this setting, those two parameters do not work. - diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper/dependency-watcher.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper/dependency-watcher.adoc deleted file mode 100644 index 24017e101..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper/dependency-watcher.adoc +++ /dev/null @@ -1,53 +0,0 @@ -[[spring-cloud-zookeeper-dependency-watcher]] -= Spring Cloud Zookeeper Dependency Watcher - -The Dependency Watcher mechanism lets you register listeners to your dependencies. The -functionality is, in fact, an implementation of the `Observator` pattern. When a -dependency changes, its state (to either UP or DOWN), some custom logic can be applied. - -[[activating]] -== Activating - -Spring Cloud Zookeeper Dependencies functionality needs to be enabled for you to use the -Dependency Watcher mechanism. -// TODO: How can the reader do that? - -[[registering-a-listener]] -== Registering a Listener - -To register a listener, you must implement an interface called -`org.springframework.cloud.zookeeper.discovery.watcher.DependencyWatcherListener` and -register it as a bean. The interface gives you one method: - -[source,java,indent=0] ----- -void stateChanged(String dependencyName, DependencyState newState); ----- - -If you want to register a listener for a particular dependency, the `dependencyName` would -be the discriminator for your concrete implementation. `newState` provides you with -information about whether your dependency has changed to `CONNECTED` or `DISCONNECTED`. - -[[spring-cloud-zookeeper-dependency-watcher-presence-checker]] -== Using the Presence Checker - -Bound with the Dependency Watcher is the functionality called Presence Checker. It lets -you provide custom behavior when your application boots, to react according to the state -of your dependencies. - -The default implementation of the abstract -`org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier` -class is the -`org.springframework.cloud.zookeeper.discovery.watcher.presence.DefaultDependencyPresenceOnStartupVerifier`, -which works in the following way. - -. If the dependency is marked us `required` and is not in Zookeeper, when your application -boots, it throws an exception and shuts down. -. If the dependency is not `required`, the -`org.springframework.cloud.zookeeper.discovery.watcher.presence.LogMissingDependencyChecker` -logs that the dependency is missing at the `WARN` level. - -Because the `DefaultDependencyPresenceOnStartupVerifier` is registered only when there is -no bean of type `DependencyPresenceOnStartupVerifier`, this functionality can be -overridden. - diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper/discovery.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper/discovery.adoc deleted file mode 100644 index 47d3a51b3..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper/discovery.adoc +++ /dev/null @@ -1,105 +0,0 @@ -[[spring-cloud-zookeeper-discovery]] -= Service Discovery with Zookeeper - -Service Discovery is one of the key tenets of a microservice based architecture. Trying to -hand-configure each client or some form of convention can be difficult to do and can be -brittle. https://curator.apache.org[Curator](A Java library for Zookeeper) provides Service -Discovery through a https://curator.apache.org/curator-x-discovery/[Service Discovery -Extension]. Spring Cloud Zookeeper uses this extension for service registration and -discovery. - -[[activating]] -== Activating - -Including a dependency on -`org.springframework.cloud:spring-cloud-starter-zookeeper-discovery` enables -autoconfiguration that sets up Spring Cloud Zookeeper Discovery. - -NOTE: For web functionality, you still need to include -`org.springframework.boot:spring-boot-starter-web`. - -CAUTION: When working with version 3.4 of Zookeeper you need to change -the way you include the dependency as described xref:spring-cloud-zookeeper/install.adoc[here]. - -[[registering-with-zookeeper]] -== Registering with Zookeeper - -When a client registers with Zookeeper, it provides metadata (such as host and port, ID, -and name) about itself. - -The following example shows a Zookeeper client: - -[source,java,indent=0] ----- -@SpringBootApplication -@RestController -public class Application { - - @RequestMapping("/") - public String home() { - return "Hello world"; - } - - public static void main(String[] args) { - new SpringApplicationBuilder(Application.class).web(true).run(args); - } - -} ----- - -NOTE: The preceding example is a normal Spring Boot application. - -If Zookeeper is located somewhere other than `localhost:2181`, the configuration must -provide the location of the server, as shown in the following example: - -[source,yml,indent=0] -.application.yml ----- -spring: - cloud: - zookeeper: - connect-string: localhost:2181 ----- - -CAUTION: If you use xref:spring-cloud-zookeeper/config.adoc[Spring Cloud Zookeeper Config], the -values shown in the preceding example need to be in `bootstrap.yml` instead of -`application.yml`. - -The default service name, instance ID, and port (taken from the `Environment`) are -`${spring.application.name}`, the Spring Context ID, and `${server.port}`, respectively. - -Having `spring-cloud-starter-zookeeper-discovery` on the classpath makes the app into both -a Zookeeper "`service`" (that is, it registers itself) and a "`client`" (that is, it can -query Zookeeper to locate other services). - -If you would like to disable the Zookeeper Discovery Client, you can set -`spring.cloud.zookeeper.discovery.enabled` to `false`. - -[[using-the-discoveryclient]] -== Using the DiscoveryClient - -Spring Cloud has support for -https://github.com/spring-cloud/spring-cloud-netflix/blob/master/docs/src/main/asciidoc/spring-cloud-netflix.adoc#spring-cloud-feign[Feign] -(a REST client builder), -https://github.com/spring-cloud/spring-cloud-netflix/blob/master/docs/src/main/ascii[Spring -`RestTemplate`] and -https://cloud.spring.io/spring-cloud-commons/reference/html/#loadbalanced-webclient[Spring WebFlux], using logical service names instead of physical URLs. - -You can also use the `org.springframework.cloud.client.discovery.DiscoveryClient`, which -provides a simple API for discovery clients that is not specific to Netflix, as shown in -the following example: - -[source,java,indent=0] ----- -@Autowired -private DiscoveryClient discoveryClient; - -public String serviceUrl() { - List list = discoveryClient.getInstances("STORES"); - if (list != null && list.size() > 0 ) { - return list.get(0).getUri().toString(); - } - return null; -} ----- - diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper/install.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper/install.adoc deleted file mode 100644 index d34003d75..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper/install.adoc +++ /dev/null @@ -1,54 +0,0 @@ -[[spring-cloud-zookeeper-install]] -= Install Zookeeper - -See the https://zookeeper.apache.org/doc/current/zookeeperStarted.html[installation -documentation] for instructions on how to install Zookeeper. - -Spring Cloud Zookeeper uses Apache Curator behind the scenes. -While Zookeeper 3.5.x is still considered "beta" by the Zookeeper development team, -the reality is that it is used in production by many users. -However, Zookeeper 3.4.x is also used in production. -Prior to Apache Curator 4.0, both versions of Zookeeper were supported via two versions of Apache Curator. -Starting with Curator 4.0 both versions of Zookeeper are supported via the same Curator libraries. - -In case you are integrating with version 3.4 you need to change the Zookeeper dependency -that comes shipped with `curator`, and thus `spring-cloud-zookeeper`. -To do so simply exclude that dependency and add the 3.4.x version like shown below. - -.maven -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-starter-zookeeper-all - - - org.apache.zookeeper - zookeeper - - - - - org.apache.zookeeper - zookeeper - 3.4.12 - - - org.slf4j - slf4j-log4j12 - - - ----- - -.gradle -[source,groovy,indent=0] ----- -compile('org.springframework.cloud:spring-cloud-starter-zookeeper-all') { - exclude group: 'org.apache.zookeeper', module: 'zookeeper' -} -compile('org.apache.zookeeper:zookeeper:3.4.12') { - exclude group: 'org.slf4j', module: 'slf4j-log4j12' -} ----- - diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper/other-componentes.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper/other-componentes.adoc deleted file mode 100644 index 5de6f8c2e..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper/other-componentes.adoc +++ /dev/null @@ -1,16 +0,0 @@ -[[spring-cloud-zookeeper-other-componentes]] -= Using Spring Cloud Zookeeper with Spring Cloud Components -:page-section-summary-toc: 1 - -Feign, Spring Cloud Gateway and Spring Cloud LoadBalancer all work with Spring Cloud Zookeeper. - -[[spring-cloud-loadbalancer-with-zookeeper]] -== Spring Cloud LoadBalancer with Zookeeper - -Spring Cloud Zookeeper provides an implementation of Spring Cloud LoadBalancer `ServiceInstanceListSupplier`. -When you use the `spring-cloud-starter-zookeeper-discovery`, Spring Cloud LoadBalancer is autoconfigured to use the -`ZookeeperServiceInstanceListSupplier` by default. - -TIP: If you were previously using the StickyRule in Zookeeper, its replacement in the current stack -is the `SameInstancePreferenceServiceInstanceListSupplier` in SC LoadBalancer. You can read on how to set it up in the https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#spring-cloud-loadbalancer[Spring Cloud Commons documentation]. - diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper/quick-start.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper/quick-start.adoc deleted file mode 100644 index 59e051393..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper/quick-start.adoc +++ /dev/null @@ -1,6 +0,0 @@ -[[quick-start]] -= Quick Start -:page-section-summary-toc: 1 - -include:../:quickstart.adoc[] - diff --git a/docs/modules/ROOT/pages/spring-cloud-zookeeper/service-registry.adoc b/docs/modules/ROOT/pages/spring-cloud-zookeeper/service-registry.adoc deleted file mode 100644 index 88e56c060..000000000 --- a/docs/modules/ROOT/pages/spring-cloud-zookeeper/service-registry.adoc +++ /dev/null @@ -1,45 +0,0 @@ -[[spring-cloud-zookeeper-service-registry]] -= Spring Cloud Zookeeper and Service Registry - -Spring Cloud Zookeeper implements the `ServiceRegistry` interface, letting developers -register arbitrary services in a programmatic way. - -The `ServiceInstanceRegistration` class offers a `builder()` method to create a -`Registration` object that can be used by the `ServiceRegistry`, as shown in the following -example: - -[source,java,indent=0] ----- -@Autowired -private ZookeeperServiceRegistry serviceRegistry; - -public void registerThings() { - ZookeeperRegistration registration = ServiceInstanceRegistration.builder() - .defaultUriSpec() - .address("anyUrl") - .port(10) - .name("/a/b/c/d/anotherservice") - .build(); - this.serviceRegistry.register(registration); -} ----- - -[[instance-status]] -== Instance Status - -Netflix Eureka supports having instances that are `OUT_OF_SERVICE` registered with the server. -These instances are not returned as active service instances. -This is useful for behaviors such as blue/green deployments. -(Note that the Curator Service Discovery recipe does not support this behavior.) Taking advantage of the flexible payload has let Spring Cloud Zookeeper implement `OUT_OF_SERVICE` by updating some specific metadata and then filtering on that metadata in the Spring Cloud LoadBalancer `ZookeeperServiceInstanceListSupplier`. -The `ZookeeperServiceInstanceListSupplier` filters out all non-null instance statuses that do not equal `UP`. -If the instance status field is empty, it is considered to be `UP` for backwards compatibility. -To change the status of an instance, make a `POST` with `OUT_OF_SERVICE` to the `ServiceRegistry` -instance status actuator endpoint, as shown in the following example: - -[source,sh,indent=0] ----- -$ http POST http://localhost:8081/service-registry status=OUT_OF_SERVICE ----- - -NOTE: The preceding example uses the `http` command from https://httpie.org. - diff --git a/docs/pom.xml b/docs/pom.xml deleted file mode 100644 index ebceb1862..000000000 --- a/docs/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - - spring-cloud-zookeeper-docs - jar - Spring Cloud Zookeeper Docs - Spring Cloud Docs - - spring-cloud-zookeeper - ${basedir}/.. - spring.cloud.zookeeper.*| - - deploy - - none - - - - ${project.groupId} - spring-cloud-starter-zookeeper-all - - - - src/main/asciidoc - - - - docs - - - - pl.project13.maven - git-commit-id-plugin - - - maven-dependency-plugin - - - maven-resources-plugin - - - org.codehaus.mojo - exec-maven-plugin - - - org.asciidoctor - asciidoctor-maven-plugin - - - maven-antrun-plugin - - - maven-deploy-plugin - - - - - - diff --git a/docs/src/main/asciidoc/ghpages.sh b/docs/src/main/asciidoc/ghpages.sh deleted file mode 100755 index d18aa88d3..000000000 --- a/docs/src/main/asciidoc/ghpages.sh +++ /dev/null @@ -1,330 +0,0 @@ -#!/bin/bash -x - -set -e - -# Set default props like MAVEN_PATH, ROOT_FOLDER etc. -function set_default_props() { - # The script should be run from the root folder - ROOT_FOLDER=`pwd` - echo "Current folder is ${ROOT_FOLDER}" - - if [[ ! -e "${ROOT_FOLDER}/.git" ]]; then - echo "You're not in the root folder of the project!" - exit 1 - fi - - # Prop that will let commit the changes - COMMIT_CHANGES="no" - MAVEN_PATH=${MAVEN_PATH:-} - echo "Path to Maven is [${MAVEN_PATH}]" - REPO_NAME=${PWD##*/} - echo "Repo name is [${REPO_NAME}]" - SPRING_CLOUD_STATIC_REPO=${SPRING_CLOUD_STATIC_REPO:-git@github.com:spring-cloud/spring-cloud-static.git} - echo "Spring Cloud Static repo is [${SPRING_CLOUD_STATIC_REPO}" -} - -# Check if gh-pages exists and docs have been built -function check_if_anything_to_sync() { - git remote set-url --push origin `git config remote.origin.url | sed -e 's/^git:/https:/'` - - if ! (git remote set-branches --add origin gh-pages && git fetch -q); then - echo "No gh-pages, so not syncing" - exit 0 - fi - - if ! [ -d docs/target/generated-docs ] && ! [ "${BUILD}" == "yes" ]; then - echo "No gh-pages sources in docs/target/generated-docs, so not syncing" - exit 0 - fi -} - -function retrieve_current_branch() { - # Code getting the name of the current branch. For master we want to publish as we did until now - # https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch - # If there is a branch already passed will reuse it - otherwise will try to find it - CURRENT_BRANCH=${BRANCH} - if [[ -z "${CURRENT_BRANCH}" ]] ; then - CURRENT_BRANCH=$(git symbolic-ref -q HEAD) - CURRENT_BRANCH=${CURRENT_BRANCH##refs/heads/} - CURRENT_BRANCH=${CURRENT_BRANCH:-HEAD} - fi - echo "Current branch is [${CURRENT_BRANCH}]" - git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script" -} - -# Switches to the provided value of the release version. We always prefix it with `v` -function switch_to_tag() { - git checkout v${VERSION} -} - -# Build the docs if switch is on -function build_docs_if_applicable() { - if [[ "${BUILD}" == "yes" ]] ; then - ./mvnw clean install -P docs -pl docs -DskipTests - fi -} - -# Get the name of the `docs.main` property -# Get allowed branches - assumes that a `docs` module is available under `docs` profile -function retrieve_doc_properties() { - MAIN_ADOC_VALUE=$("${MAVEN_PATH}"mvn -q \ - -Dexec.executable="echo" \ - -Dexec.args='${docs.main}' \ - --non-recursive \ - org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo "Extracted 'main.adoc' from Maven build [${MAIN_ADOC_VALUE}]" - - - ALLOW_PROPERTY=${ALLOW_PROPERTY:-"docs.allowed.branches"} - ALLOWED_BRANCHES_VALUE=$("${MAVEN_PATH}"mvn -q \ - -Dexec.executable="echo" \ - -Dexec.args="\${${ALLOW_PROPERTY}}" \ - org.codehaus.mojo:exec-maven-plugin:1.3.1:exec \ - -P docs \ - -pl docs) - echo "Extracted '${ALLOW_PROPERTY}' from Maven build [${ALLOWED_BRANCHES_VALUE}]" -} - -# Stash any outstanding changes -function stash_changes() { - git diff-index --quiet HEAD && dirty=$? || (echo "Failed to check if the current repo is dirty. Assuming that it is." && dirty="1") - if [ "$dirty" != "0" ]; then git stash; fi -} - -# Switch to gh-pages branch to sync it with current branch -function add_docs_from_target() { - local DESTINATION_REPO_FOLDER - if [[ -z "${DESTINATION}" && -z "${CLONE}" ]] ; then - DESTINATION_REPO_FOLDER=${ROOT_FOLDER} - elif [[ "${CLONE}" == "yes" ]]; then - mkdir -p ${ROOT_FOLDER}/target - local clonedStatic=${ROOT_FOLDER}/target/spring-cloud-static - if [[ ! -e "${clonedStatic}/.git" ]]; then - echo "Cloning Spring Cloud Static to target" - git clone ${SPRING_CLOUD_STATIC_REPO} ${clonedStatic} && git checkout gh-pages - else - echo "Spring Cloud Static already cloned - will pull changes" - cd ${clonedStatic} && git checkout gh-pages && git pull origin gh-pages - fi - DESTINATION_REPO_FOLDER=${clonedStatic}/${REPO_NAME} - mkdir -p ${DESTINATION_REPO_FOLDER} - else - if [[ ! -e "${DESTINATION}/.git" ]]; then - echo "[${DESTINATION}] is not a git repository" - exit 1 - fi - DESTINATION_REPO_FOLDER=${DESTINATION}/${REPO_NAME} - mkdir -p ${DESTINATION_REPO_FOLDER} - echo "Destination was provided [${DESTINATION}]" - fi - cd ${DESTINATION_REPO_FOLDER} - git checkout gh-pages - git pull origin gh-pages - - # Add git branches - ################################################################### - if [[ -z "${VERSION}" ]] ; then - copy_docs_for_current_version - else - copy_docs_for_provided_version - fi - commit_changes_if_applicable -} - - -# Copies the docs by using the retrieved properties from Maven build -function copy_docs_for_current_version() { - if [[ "${CURRENT_BRANCH}" == "master" ]] ; then - echo -e "Current branch is master - will copy the current docs only to the root folder" - for f in docs/target/generated-docs/*; do - file=${f#docs/target/generated-docs/*} - if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then - # Not ignored... - cp -rf $f ${ROOT_FOLDER}/ - git add -A ${ROOT_FOLDER}/$file - fi - done - COMMIT_CHANGES="yes" - else - echo -e "Current branch is [${CURRENT_BRANCH}]" - # https://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin - if [[ ",${ALLOWED_BRANCHES_VALUE}," = *",${CURRENT_BRANCH},"* ]] ; then - mkdir -p ${ROOT_FOLDER}/${CURRENT_BRANCH} - echo -e "Branch [${CURRENT_BRANCH}] is allowed! Will copy the current docs to the [${CURRENT_BRANCH}] folder" - for f in docs/target/generated-docs/*; do - file=${f#docs/target/generated-docs/*} - if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then - # Not ignored... - # We want users to access 1.0.0.RELEASE/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html - if [[ "${file}" == "${MAIN_ADOC_VALUE}.html" ]] ; then - # We don't want to copy the spring-cloud-sleuth.html - # we want it to be converted to index.html - cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html - git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html - else - cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH} - git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/$file - fi - fi - done - COMMIT_CHANGES="yes" - else - echo -e "Branch [${CURRENT_BRANCH}] is not on the allow list! Check out the Maven [${ALLOW_PROPERTY}] property in - [docs] module available under [docs] profile. Won't commit any changes to gh-pages for this branch." - fi - fi -} - -# Copies the docs by using the explicitly provided version -function copy_docs_for_provided_version() { - local FOLDER=${DESTINATION_REPO_FOLDER}/${VERSION} - mkdir -p ${FOLDER} - echo -e "Current tag is [v${VERSION}] Will copy the current docs to the [${FOLDER}] folder" - for f in ${ROOT_FOLDER}/docs/target/generated-docs/*; do - file=${f#${ROOT_FOLDER}/docs/target/generated-docs/*} - copy_docs_for_branch ${file} ${FOLDER} - done - COMMIT_CHANGES="yes" - CURRENT_BRANCH="v${VERSION}" -} - -# Copies the docs from target to the provided destination -# Params: -# $1 - file from target -# $2 - destination to which copy the files -function copy_docs_for_branch() { - local file=$1 - local destination=$2 - if ! git ls-files -i -o --exclude-standard --directory | grep -q ^${file}$; then - # Not ignored... - # We want users to access 1.0.0.RELEASE/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html - if [[ ("${file}" == "${MAIN_ADOC_VALUE}.html") || ("${file}" == "${REPO_NAME}.html") ]] ; then - # We don't want to copy the spring-cloud-sleuth.html - # we want it to be converted to index.html - cp -rf $f ${destination}/index.html - git add -A ${destination}/index.html - else - cp -rf $f ${destination} - git add -A ${destination}/$file - fi - fi -} - -function commit_changes_if_applicable() { - if [[ "${COMMIT_CHANGES}" == "yes" ]] ; then - COMMIT_SUCCESSFUL="no" - git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes" - - # Uncomment the following push if you want to auto push to - # the gh-pages branch whenever you commit to master locally. - # This is a little extreme. Use with care! - ################################################################### - if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then - git push origin gh-pages - fi - fi -} - -# Switch back to the previous branch and exit block -function checkout_previous_branch() { - # If -version was provided we need to come back to root project - cd ${ROOT_FOLDER} - git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script" - if [ "$dirty" != "0" ]; then git stash pop; fi - exit 0 -} - -# Assert if properties have been properly passed -function assert_properties() { -echo "VERSION [${VERSION}], DESTINATION [${DESTINATION}], CLONE [${CLONE}]" -if [[ "${VERSION}" != "" && (-z "${DESTINATION}" && -z "${CLONE}") ]] ; then echo "Version was set but destination / clone was not!"; exit 1;fi -if [[ ("${DESTINATION}" != "" && "${CLONE}" != "") && -z "${VERSION}" ]] ; then echo "Destination / clone was set but version was not!"; exit 1;fi -if [[ "${DESTINATION}" != "" && "${CLONE}" == "yes" ]] ; then echo "Destination and clone was set. Pick one!"; exit 1;fi -} - -# Prints the usage -function print_usage() { -cat </` -- if the destination switch is passed (-d) then the script will check if the provided dir is a git repo and then will - switch to gh-pages of that repo and copy the generated docs to `docs//` - -USAGE: - -You can use the following options: - --v|--version - the script will apply the whole procedure for a particular library version --d|--destination - the root of destination folder where the docs should be copied. You have to use the full path. - E.g. point to spring-cloud-static folder. Can't be used with (-c) --b|--build - will run the standard build process after checking out the branch --c|--clone - will automatically clone the spring-cloud-static repo instead of providing the destination. - Obviously can't be used with (-d) - -EOF -} - - -# ========================================== -# ____ ____ _____ _____ _____ _______ -# / ____|/ ____| __ \|_ _| __ \__ __| -# | (___ | | | |__) | | | | |__) | | | -# \___ \| | | _ / | | | ___/ | | -# ____) | |____| | \ \ _| |_| | | | -# |_____/ \_____|_| \_\_____|_| |_| -# -# ========================================== - -while [[ $# > 0 ]] -do -key="$1" -case ${key} in - -v|--version) - VERSION="$2" - shift # past argument - ;; - -d|--destination) - DESTINATION="$2" - shift # past argument - ;; - -b|--build) - BUILD="yes" - ;; - -c|--clone) - CLONE="yes" - ;; - -h|--help) - print_usage - exit 0 - ;; - *) - echo "Invalid option: [$1]" - print_usage - exit 1 - ;; -esac -shift # past argument or value -done - -assert_properties -set_default_props -check_if_anything_to_sync -if [[ -z "${VERSION}" ]] ; then - retrieve_current_branch -else - switch_to_tag -fi -build_docs_if_applicable -retrieve_doc_properties -stash_changes -add_docs_from_target -checkout_previous_branch diff --git a/docs/src/main/asciidoc/images/.gitkeep b/docs/src/main/asciidoc/images/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/mvnw b/mvnw index a08b219e3..41c0f0c23 100755 --- a/mvnw +++ b/mvnw @@ -8,7 +8,7 @@ # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script +# Maven Start Up Batch script # # Required ENV vars: # ------------------ @@ -54,38 +54,16 @@ case "`uname`" in CYGWIN*) cygwin=true ;; MINGW*) mingw=true;; Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; esac if [ -z "$JAVA_HOME" ] ; then @@ -130,13 +108,12 @@ if $cygwin ; then CLASSPATH=`cygpath --path --unix "$CLASSPATH"` fi -# For Migwn, ensure paths are in UNIX format before anything is touched +# For Mingw, ensure paths are in UNIX format before anything is touched if $mingw ; then [ -n "$M2_HOME" ] && M2_HOME="`(cd "$M2_HOME"; pwd)`" [ -n "$JAVA_HOME" ] && JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? fi if [ -z "$JAVA_HOME" ]; then @@ -184,27 +161,28 @@ fi CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - # traverses directory structure from process work directory to filesystem root # first directory with .mvn subdirectory is considered project base directory find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" while [ "$wdir" != '/' ] ; do if [ -d "$wdir"/.mvn ] ; then basedir=$wdir break fi - wdir=$(cd "$wdir/.."; pwd) + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround done echo "${basedir}" } @@ -216,9 +194,108 @@ concat_lines() { fi } -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + # Provide a "standardized" way to retrieve the CLI args that will # work with both Windows and non-Windows executions. MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" @@ -226,28 +303,8 @@ export MAVEN_CMD_LINE_ARGS WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain -echo "Running version check" -VERSION=$( sed '\!//' -e 's!.*$!!' ) -echo "The found version is [${VERSION}]" - -if echo $VERSION | egrep -q 'M|RC'; then - echo Activating \"milestone\" profile for version=\"$VERSION\" - echo $MAVEN_ARGS | grep -q milestone || MAVEN_ARGS="$MAVEN_ARGS -Pmilestone" -else - echo Deactivating \"milestone\" profile for version=\"$VERSION\" - echo $MAVEN_ARGS | grep -q milestone && MAVEN_ARGS=$(echo $MAVEN_ARGS | sed -e 's/-Pmilestone//') -fi - -if echo $VERSION | egrep -q 'RELEASE'; then - echo Activating \"central\" profile for version=\"$VERSION\" - echo $MAVEN_ARGS | grep -q milestone || MAVEN_ARGS="$MAVEN_ARGS -Pcentral" -else - echo Deactivating \"central\" profile for version=\"$VERSION\" - echo $MAVEN_ARGS | grep -q central && MAVEN_ARGS=$(echo $MAVEN_ARGS | sed -e 's/-Pcentral//') -fi - exec "$JAVACMD" \ $MAVEN_OPTS \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} ${MAVEN_ARGS} "$@" + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd index 7ecd01d80..86115719e 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -7,7 +7,7 @@ @REM "License"); you may not use this file except in compliance @REM with the License. You may obtain a copy of the License at @REM -@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM http://www.apache.org/licenses/LICENSE-2.0 @REM @REM Unless required by applicable law or agreed to in writing, @REM software distributed under the License is distributed on an @@ -18,7 +18,7 @@ @REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script +@REM Maven Start Up Batch script @REM @REM Required ENV vars: @REM JAVA_HOME - location of a JDK home dir @@ -26,7 +26,7 @@ @REM Optional ENV vars @REM M2_HOME - location of maven2's installed home dir @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven @REM e.g. to debug Maven itself, use @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 @@ -35,7 +35,9 @@ @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' @echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% @REM set %HOME% to equivalent of $HOME @@ -80,8 +82,6 @@ goto error :init -set MAVEN_CMD_LINE_ARGS=%* - @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". @REM Fallback to current working directory if not found. @@ -117,11 +117,48 @@ for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do s :endReadAdditionalConfig SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* if ERRORLEVEL 1 goto error goto end diff --git a/pom.xml b/pom.xml index 46a35adda..809d30022 100644 --- a/pom.xml +++ b/pom.xml @@ -1,225 +1,70 @@ - - - 4.0.0 + + - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - pom - Spring Cloud Zookeeper - Spring Cloud Zookeeper + 4.0.0 - - org.springframework.cloud - spring-cloud-build - 4.1.0-SNAPSHOT - - - + org.springframework.cloud + spring-cloud-zookeeper-docs-build + 0.0.1-SNAPSHOT + Spring Cloud Zookeeper Docs Build + Builds Spring Cloud Zookeeper Docs. + https://spring.io/projects/spring-cloud-zookeeper - https://github.com/spring-cloud/spring-cloud-zookeeper - - scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git + scm:git:https://github.com/spring-cloud/spring-cloud-zookeeper.git - scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git + scm:git:git@github.com:spring-cloud/spring-cloud-zookeeper.git - HEAD + https://github.com/spring-cloud/spring-cloud-zookeeper + + https://github.com/spring-cloud/spring-cloud-zookeeper/issues + + + + 0.0.3 + - - spring-cloud-zookeeper-dependencies - spring-cloud-zookeeper-core - spring-cloud-zookeeper-config - spring-cloud-zookeeper-discovery - spring-cloud-starter-zookeeper - spring-cloud-starter-zookeeper-config - spring-cloud-starter-zookeeper-discovery - spring-cloud-starter-zookeeper-all - spring-cloud-zookeeper-sample - docs - - - - - maven-surefire-plugin - - false - - **/*Spec.* - **/*Tests.* - **/*Test.* - - - **/Abstract*Spec.* - **/Abstract*Tests.* - **/Abstract*Test.* - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - - org.codehaus.mojo - flatten-maven-plugin - - - org.apache.maven.plugins - maven-checkstyle-plugin + io.spring.maven.antora + antora-maven-plugin + ${io.spring.maven.antora-version} + true + + + + + + + + 9d489079e5ec46dbb238909fee5c9c29 + WB1FQYI187 + springcloudzookeeper + + - - - - org.springframework.cloud - spring-cloud-zookeeper-dependencies - ${project.version} - pom - import - - - com.jayway.awaitility - awaitility - 1.7.0 - test - - - com.toomuchcoding.jsonassert - jsonassert - 0.4.14 - test - - - org.springframework.cloud - spring-cloud-commons-dependencies - ${spring-cloud-commons.version} - pom - import - - - org.springframework.cloud - spring-cloud-config-dependencies - ${spring-cloud-config.version} - pom - import - - - org.springframework.cloud - spring-cloud-openfeign-dependencies - ${spring-cloud-openfeign.version} - pom - import - - - org.springframework.cloud - spring-cloud-test-support - ${spring-cloud-commons.version} - - - org.testcontainers - testcontainers - ${testcontainers.version} - - - org.testcontainers - mockserver - ${testcontainers.version} - - - org.testcontainers - junit-jupiter - ${testcontainers.version} - - - org.mock-server - mockserver-client-java - ${mockserverclient.version} - - - - - - 4.1.0-SNAPSHOT - 4.1.0-SNAPSHOT - 4.1.0-SNAPSHOT - 4.1.0-SNAPSHOT - 1.17.6 - 5.15.0 - - - - - spring - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - false - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - spring-releases - Spring Releases - https://repo.spring.io/release - - false - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - false - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - spring-releases - Spring Releases - https://repo.spring.io/release - - false - - - - - + + + spring-snapshot + https://repo.spring.io/snapshot + + true + + + false + + + + spring-milestone + https://repo.spring.io/milestone + + diff --git a/scripts/runAcceptanceTests.sh b/scripts/runAcceptanceTests.sh deleted file mode 100755 index ee0dbc701..000000000 --- a/scripts/runAcceptanceTests.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -set -o errexit - -SCRIPT_URL="https://raw.githubusercontent.com/spring-cloud-samples/brewery/2021.0.x/runAcceptanceTests.sh" -AT_WHAT_TO_TEST="ZOOKEEPER" - -curl "${SCRIPT_URL}" --output runAcceptanceTests.sh - -chmod +x runAcceptanceTests.sh - -./runAcceptanceTests.sh --whattotest "${AT_WHAT_TO_TEST}" --killattheend diff --git a/spring-cloud-starter-zookeeper-all/.flattened-pom.xml b/spring-cloud-starter-zookeeper-all/.flattened-pom.xml new file mode 100644 index 000000000..ae2f8fc41 --- /dev/null +++ b/spring-cloud-starter-zookeeper-all/.flattened-pom.xml @@ -0,0 +1,113 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + .. + + org.springframework.cloud + spring-cloud-starter-zookeeper-all + 4.1.0-SNAPSHOT + Spring Cloud Starter Zookeeper All + Spring Cloud Starter Zookeeper All + https://projects.spring.io/spring-cloud + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-starter-zookeeper-all + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-starter-zookeeper-all + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-starter-zookeeper-all + + + + org.springframework.cloud + spring-cloud-starter-zookeeper-config + 4.1.0-SNAPSHOT + compile + + + org.springframework.cloud + spring-cloud-starter-zookeeper-discovery + 4.1.0-SNAPSHOT + compile + + + diff --git a/spring-cloud-starter-zookeeper-all/pom.xml b/spring-cloud-starter-zookeeper-all/pom.xml deleted file mode 100644 index 1454d676c..000000000 --- a/spring-cloud-starter-zookeeper-all/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - .. - - spring-cloud-starter-zookeeper-all - Spring Cloud Starter Zookeeper All - Spring Cloud Starter Zookeeper All - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../.. - - - - org.springframework.cloud - spring-cloud-starter-zookeeper-config - - - org.springframework.cloud - spring-cloud-starter-zookeeper-discovery - - - diff --git a/spring-cloud-starter-zookeeper-config/.flattened-pom.xml b/spring-cloud-starter-zookeeper-config/.flattened-pom.xml new file mode 100644 index 000000000..124ebf4a4 --- /dev/null +++ b/spring-cloud-starter-zookeeper-config/.flattened-pom.xml @@ -0,0 +1,129 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + .. + + org.springframework.cloud + spring-cloud-starter-zookeeper-config + 4.1.0-SNAPSHOT + Spring Cloud Starter Zookeeper Config + Spring Cloud Starter Zookeeper Config + https://projects.spring.io/spring-cloud + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-starter-zookeeper-config + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-starter-zookeeper-config + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-starter-zookeeper-config + + + + org.springframework.cloud + spring-cloud-starter-zookeeper + 4.1.0-SNAPSHOT + compile + + + org.springframework.cloud + spring-cloud-zookeeper-config + 4.1.0-SNAPSHOT + compile + + + org.apache.curator + curator-recipes + 5.1.0 + compile + + + log4j + log4j + + + io.netty + netty + + + + + diff --git a/spring-cloud-starter-zookeeper-config/pom.xml b/spring-cloud-starter-zookeeper-config/pom.xml deleted file mode 100644 index 35ed72dd4..000000000 --- a/spring-cloud-starter-zookeeper-config/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - .. - - spring-cloud-starter-zookeeper-config - Spring Cloud Starter Zookeeper Config - Spring Cloud Starter Zookeeper Config - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../.. - - - - org.springframework.cloud - spring-cloud-starter-zookeeper - - - org.springframework.cloud - spring-cloud-zookeeper-config - - - org.apache.curator - curator-recipes - - - diff --git a/spring-cloud-starter-zookeeper-discovery/.flattened-pom.xml b/spring-cloud-starter-zookeeper-discovery/.flattened-pom.xml new file mode 100644 index 000000000..92ec9af1b --- /dev/null +++ b/spring-cloud-starter-zookeeper-discovery/.flattened-pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + .. + + org.springframework.cloud + spring-cloud-starter-zookeeper-discovery + 4.1.0-SNAPSHOT + Spring Cloud Starter Zookeeper Discovery + Spring Cloud Starter Zookeeper Discovery + https://projects.spring.io/spring-cloud + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-starter-zookeeper-discovery + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-starter-zookeeper-discovery + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-starter-zookeeper-discovery + + + + org.springframework.cloud + spring-cloud-starter-zookeeper + 4.1.0-SNAPSHOT + compile + + + org.springframework.cloud + spring-cloud-zookeeper-discovery + 4.1.0-SNAPSHOT + compile + + + org.apache.curator + curator-x-discovery + 5.1.0 + compile + + + log4j + log4j + + + io.netty + netty + + + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + 4.1.0-SNAPSHOT + compile + + + diff --git a/spring-cloud-starter-zookeeper-discovery/pom.xml b/spring-cloud-starter-zookeeper-discovery/pom.xml deleted file mode 100644 index 8ed4e382d..000000000 --- a/spring-cloud-starter-zookeeper-discovery/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - .. - - spring-cloud-starter-zookeeper-discovery - Spring Cloud Starter Zookeeper Discovery - Spring Cloud Starter Zookeeper Discovery - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../.. - - - - org.springframework.cloud - spring-cloud-starter-zookeeper - - - org.springframework.cloud - spring-cloud-zookeeper-discovery - - - org.apache.curator - curator-x-discovery - - - org.springframework.cloud - spring-cloud-starter-loadbalancer - - - diff --git a/spring-cloud-starter-zookeeper/.flattened-pom.xml b/spring-cloud-starter-zookeeper/.flattened-pom.xml new file mode 100644 index 000000000..6aed6ac91 --- /dev/null +++ b/spring-cloud-starter-zookeeper/.flattened-pom.xml @@ -0,0 +1,113 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + .. + + org.springframework.cloud + spring-cloud-starter-zookeeper + 4.1.0-SNAPSHOT + Spring Cloud Starter Zookeeper + Spring Cloud Starter Zookeeper + https://projects.spring.io/spring-cloud + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-starter-zookeeper + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-starter-zookeeper + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-starter-zookeeper + + + + org.springframework.cloud + spring-cloud-starter + 4.1.0-SNAPSHOT + compile + + + org.springframework.cloud + spring-cloud-zookeeper-core + 4.1.0-SNAPSHOT + compile + + + diff --git a/spring-cloud-starter-zookeeper/pom.xml b/spring-cloud-starter-zookeeper/pom.xml deleted file mode 100644 index aee3ec6a7..000000000 --- a/spring-cloud-starter-zookeeper/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - .. - - spring-cloud-starter-zookeeper - Spring Cloud Starter Zookeeper - Spring Cloud Starter Zookeeper - https://projects.spring.io/spring-cloud - - Pivotal Software, Inc. - https://www.spring.io - - - ${basedir}/../.. - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-zookeeper-core - - - diff --git a/spring-cloud-zookeeper-config/.flattened-pom.xml b/spring-cloud-zookeeper-config/.flattened-pom.xml new file mode 100644 index 000000000..18d1c6050 --- /dev/null +++ b/spring-cloud-zookeeper-config/.flattened-pom.xml @@ -0,0 +1,181 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + .. + + org.springframework.cloud + spring-cloud-zookeeper-config + 4.1.0-SNAPSHOT + Spring Cloud Zookeeper Config + Spring Cloud Zookeeper Config + https://spring.io/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-config + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-config + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-config + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-config + + + + org.springframework.cloud + spring-cloud-zookeeper-core + 4.1.0-SNAPSHOT + compile + + + org.apache.curator + curator-x-discovery + 5.1.0 + compile + + + log4j + log4j + + + io.netty + netty + + + + + org.springframework.cloud + spring-cloud-commons + 4.1.0-SNAPSHOT + compile + + + org.springframework.cloud + spring-cloud-context + 4.1.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-starter-web + 3.2.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-starter-actuator + 3.2.0-SNAPSHOT + compile + true + + + org.apache.curator + curator-recipes + 5.1.0 + compile + + + log4j + log4j + + + io.netty + netty + + + true + + + org.springframework.boot + spring-boot-autoconfigure-processor + 3.2.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-configuration-processor + 3.2.0-SNAPSHOT + compile + true + + + diff --git a/spring-cloud-zookeeper-config/pom.xml b/spring-cloud-zookeeper-config/pom.xml deleted file mode 100644 index f8e3274fc..000000000 --- a/spring-cloud-zookeeper-config/pom.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - 4.0.0 - - spring-cloud-zookeeper-config - jar - Spring Cloud Zookeeper Config - Spring Cloud Zookeeper Config - - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - .. - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - - - - org.springframework.cloud - spring-cloud-zookeeper-core - - - org.apache.curator - curator-x-discovery - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.cloud - spring-cloud-context - true - - - org.springframework.boot - spring-boot-starter-web - true - - - org.springframework.boot - spring-boot-starter-actuator - true - - - org.apache.curator - curator-recipes - true - - - org.springframework.boot - spring-boot-autoconfigure-processor - true - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - test - - - org.springframework.cloud - spring-cloud-zookeeper-core - ${project.version} - test-jar - test - - - org.apache.curator - curator-test - test - - - - diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/AbstractZookeeperPropertySource.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/AbstractZookeeperPropertySource.java deleted file mode 100644 index 10b3bf699..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/AbstractZookeeperPropertySource.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.core.env.EnumerablePropertySource; - -/** - * A {@link EnumerablePropertySource} that has a notion of a context which is the root - * folder in Zookeeper. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public abstract class AbstractZookeeperPropertySource - extends EnumerablePropertySource { - - private String context; - - public AbstractZookeeperPropertySource(String context, CuratorFramework source) { - super(context, source); - this.context = context; - if (!this.context.startsWith("/")) { - this.context = "/" + this.context; - } - } - - protected String sanitizeKey(String path) { - return path.replace(this.context + "/", "").replace('/', '.'); - } - - public String getContext() { - return this.context; - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ConfigWatcher.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ConfigWatcher.java deleted file mode 100644 index f9411ee6d..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ConfigWatcher.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.io.Closeable; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -import jakarta.annotation.PostConstruct; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.cache.TreeCache; -import org.apache.curator.framework.recipes.cache.TreeCacheEvent; -import org.apache.curator.framework.recipes.cache.TreeCacheListener; -import org.apache.zookeeper.KeeperException; - -import org.springframework.cloud.endpoint.event.RefreshEvent; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.ApplicationEventPublisherAware; - -import static org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type.NODE_ADDED; -import static org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type.NODE_REMOVED; -import static org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type.NODE_UPDATED; - -/** - * Class that registers a {@link TreeCache} for each context. It publishes events upon - * element change in Zookeeper. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class ConfigWatcher - implements Closeable, TreeCacheListener, ApplicationEventPublisherAware { - - private static final Log log = LogFactory.getLog(ConfigWatcher.class); - - private AtomicBoolean running = new AtomicBoolean(false); - - private List contexts; - - private CuratorFramework source; - - private ApplicationEventPublisher publisher; - - private HashMap caches; - - public ConfigWatcher(List contexts, CuratorFramework source) { - this.contexts = contexts; - this.source = source; - } - - @Override - public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { - this.publisher = publisher; - } - - @PostConstruct - public void start() { - if (this.running.compareAndSet(false, true)) { - this.caches = new HashMap<>(); - for (String context : this.contexts) { - if (!context.startsWith("/")) { - context = "/" + context; - } - try { - TreeCache cache = TreeCache.newBuilder(this.source, context).build(); - cache.getListenable().addListener(this); - cache.start(); - this.caches.put(context, cache); - // no race condition since ZookeeperAutoConfiguration.curatorFramework - // calls curator.blockUntilConnected - } - catch (KeeperException.NoNodeException e) { - // no node, ignore - } - catch (Exception e) { - log.error("Error initializing listener for context " + context, e); - } - } - } - } - - @Override - public void close() { - if (this.running.compareAndSet(true, false)) { - for (TreeCache cache : this.caches.values()) { - cache.close(); - } - this.caches = null; - } - } - - @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) - throws Exception { - TreeCacheEvent.Type eventType = event.getType(); - if (eventType == NODE_ADDED || eventType == NODE_REMOVED - || eventType == NODE_UPDATED) { - this.publisher - .publishEvent(new RefreshEvent(this, event, getEventDesc(event))); - } - } - - public String getEventDesc(TreeCacheEvent event) { - StringBuilder out = new StringBuilder(); - out.append("type=").append(event.getType()); - out.append(", path=").append(event.getData().getPath()); - byte[] data = event.getData().getData(); - if (data != null && data.length > 0) { - out.append(", data=").append(new String(data, Charset.forName("UTF-8"))); - } - return out.toString(); - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperBootstrapper.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperBootstrapper.java deleted file mode 100644 index a92211b93..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperBootstrapper.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.function.Function; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.drivers.TracerDriver; -import org.apache.curator.ensemble.EnsembleProvider; -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.boot.BootstrapContext; -import org.springframework.boot.BootstrapRegistry; -import org.springframework.boot.BootstrapRegistryInitializer; -import org.springframework.cloud.zookeeper.CuratorFrameworkCustomizer; - -public class ZookeeperBootstrapper implements BootstrapRegistryInitializer { - - private Function retryPolicy; - - private Function ensembleProvider; - - private Function tracerDriver; - - private Function curatorFrameworkCustomizer; - - static BootstrapRegistryInitializer fromBootstrapContext(Function factory) { - return registry -> registry.register(CuratorFramework.class, factory::apply); - } - - static ZookeeperBootstrapper create() { - return new ZookeeperBootstrapper(); - } - - public ZookeeperBootstrapper retryPolicy(Function retryPolicy) { - this.retryPolicy = retryPolicy; - return this; - } - - public ZookeeperBootstrapper ensembleProvider(Function ensembleProvider) { - this.ensembleProvider = ensembleProvider; - return this; - } - - public ZookeeperBootstrapper tracerDriver(Function tracerDriver) { - this.tracerDriver = tracerDriver; - return this; - } - - public ZookeeperBootstrapper curatorFrameworkCustomizer(Function curatorFrameworkCustomizer) { - this.curatorFrameworkCustomizer = curatorFrameworkCustomizer; - return this; - } - - @Override - public void initialize(BootstrapRegistry registry) { - register(registry, RetryPolicy.class, retryPolicy); - register(registry, EnsembleProvider.class, ensembleProvider); - register(registry, TracerDriver.class, tracerDriver); - register(registry, CuratorFrameworkCustomizer.class, curatorFrameworkCustomizer); - } - - private void register(BootstrapRegistry registry, Class type, Function factory) { - if (this.retryPolicy != null) { - registry.register(type, factory::apply); - } - } -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfiguration.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfiguration.java deleted file mode 100644 index 38b33d510..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfiguration.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.Collections; -import java.util.List; - -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.endpoint.RefreshEndpoint; -import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** - * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration - * Auto-configuration} that registers a Zookeeper configuration watcher. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnZookeeperEnabled -@ConditionalOnProperty(value = "spring.cloud.zookeeper.config.enabled", matchIfMissing = true) -public class ZookeeperConfigAutoConfiguration { - - @Configuration(proxyBeanMethods = false) - @ConditionalOnClass(RefreshEndpoint.class) - @ConditionalOnProperty(name = "spring.cloud.zookeeper.config.watcher.enabled", matchIfMissing = true) - protected static class ZkRefreshConfiguration { - - @Bean - @ConditionalOnBean(ZookeeperPropertySourceLocator.class) - public ConfigWatcher propertySourceLocatorConfigWatcher(ZookeeperPropertySourceLocator locator, - CuratorFramework curator) { - return new ConfigWatcher(locator.getContexts(), curator); - } - - @Bean - @ConditionalOnMissingBean(ZookeeperPropertySourceLocator.class) - public ConfigWatcher configDataConfigWatcher(CuratorFramework curator, Environment env) { - List contexts = env.getProperty("spring.cloud.zookeeper.config.property-source-contexts", - List.class, Collections.emptyList()); - return new ConfigWatcher(contexts, curator); - } - - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigBootstrapConfiguration.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigBootstrapConfiguration.java deleted file mode 100644 index b50fb5bce..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigBootstrapConfiguration.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; -import org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; - -/** - * Bootstrap Configuration for Zookeeper Configuration. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnZookeeperEnabled -@Import(ZookeeperAutoConfiguration.class) -public class ZookeeperConfigBootstrapConfiguration { - - @Bean - @ConditionalOnMissingBean - public ZookeeperPropertySourceLocator zookeeperPropertySourceLocator( - CuratorFramework curator, ZookeeperConfigProperties properties) { - return new ZookeeperPropertySourceLocator(curator, properties); - } - - @Bean - @ConditionalOnMissingBean - public ZookeeperConfigProperties zookeeperConfigProperties(Environment env) { - ZookeeperConfigProperties properties = new ZookeeperConfigProperties(); - if (!StringUtils.hasLength(properties.getName())) { - properties.setName(env.getProperty("spring.application.name", "application")); - } - return properties; - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLoader.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLoader.java deleted file mode 100644 index 06501a809..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLoader.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.boot.context.config.ConfigData; -import org.springframework.boot.context.config.ConfigDataLoader; -import org.springframework.boot.context.config.ConfigDataLoaderContext; -import org.springframework.boot.context.config.ConfigDataResourceNotFoundException; -import org.springframework.boot.logging.DeferredLogFactory; -import org.springframework.util.StringUtils; - -public class ZookeeperConfigDataLoader implements ConfigDataLoader { - - private final Log log; - - public ZookeeperConfigDataLoader(DeferredLogFactory logFactory) { - this.log = logFactory.getLog(ZookeeperConfigDataLoader.class); - } - - @Override - public ConfigData load(ConfigDataLoaderContext context, ZookeeperConfigDataResource resource) { - try { - CuratorFramework curator = context.getBootstrapContext().get(CuratorFramework.class); - if (curator == null) { - // this can happen if certain conditions are met - return null; - } - ZookeeperPropertySource propertySource = new ZookeeperPropertySource(resource.getContext(), - curator); - List propertySources = Collections.singletonList(propertySource); - - return new ConfigData(propertySources, source -> { - List options = new ArrayList<>(); - options.add(ConfigData.Option.IGNORE_IMPORTS); - options.add(ConfigData.Option.IGNORE_PROFILES); - if (StringUtils.hasText(resource.getProfile())) { - options.add(ConfigData.Option.PROFILE_SPECIFIC); - } - return ConfigData.Options.of(options.toArray(new ConfigData.Option[0])); - }); - - } - catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Error getting properties from zookeeper: " + resource, e); - } - throw new ConfigDataResourceNotFoundException(resource, e); - } - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLocationResolver.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLocationResolver.java deleted file mode 100644 index 2c4a119ab..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLocationResolver.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.stream.Collectors; - -import org.apache.commons.logging.Log; - -import org.springframework.boot.BootstrapRegistry.InstanceSupplier; -import org.springframework.boot.context.config.ConfigDataLocation; -import org.springframework.boot.context.config.ConfigDataLocationNotFoundException; -import org.springframework.boot.context.config.ConfigDataLocationResolver; -import org.springframework.boot.context.config.ConfigDataLocationResolverContext; -import org.springframework.boot.context.config.Profiles; -import org.springframework.boot.context.properties.bind.BindHandler; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.logging.DeferredLogFactory; -import org.springframework.cloud.zookeeper.CuratorFactory; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.cloud.zookeeper.config.ZookeeperPropertySources.Context; -import org.springframework.core.env.MapPropertySource; -import org.springframework.lang.Nullable; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.util.UriComponents; -import org.springframework.web.util.UriComponentsBuilder; - -public class ZookeeperConfigDataLocationResolver implements ConfigDataLocationResolver { - - /** - * Zookeeper Config Data prefix. - */ - public static final String PREFIX = "zookeeper:"; - - private final Log log; - - public ZookeeperConfigDataLocationResolver(DeferredLogFactory logFactory) { - this.log = logFactory.getLog(ZookeeperConfigDataLocationResolver.class); - } - - @Override - public boolean isResolvable(ConfigDataLocationResolverContext context, ConfigDataLocation location) { - if (!location.hasPrefix(PREFIX)) { - return false; - } - // only bind on correct prefix - boolean zkEnabled = context.getBinder().bind(ZookeeperProperties.PREFIX + ".enabled", Boolean.class) - .orElse(true); - boolean zkConfigEnabled = context.getBinder().bind(ZookeeperConfigProperties.PREFIX + ".enabled", Boolean.class) - .orElse(true); - return zkConfigEnabled && zkEnabled; - } - - @Override - public List resolve(ConfigDataLocationResolverContext context, ConfigDataLocation location) - throws ConfigDataLocationNotFoundException { - return Collections.emptyList(); - } - - @Override - public List resolveProfileSpecific(ConfigDataLocationResolverContext context, - ConfigDataLocation location, Profiles profiles) throws ConfigDataLocationNotFoundException { - UriComponents locationUri = parseLocation(location); - - // create curator - CuratorFactory.registerCurator(context.getBootstrapContext(), locationUri, location.isOptional()); - - // create locations - ZookeeperConfigProperties properties = loadConfigProperties(context); - context.getBootstrapContext().register(ZookeeperConfigProperties.class, InstanceSupplier.of(properties)); - - ZookeeperPropertySources sources = new ZookeeperPropertySources(properties, log); - - List contexts = (locationUri == null || CollectionUtils.isEmpty(locationUri.getPathSegments())) - ? sources.generateAutomaticContexts(profiles.getAccepted(), false) : getCustomContexts(locationUri); - - // promote beans to context - context.getBootstrapContext().addCloseListener(event -> { - HashMap source = new HashMap<>(); - source.put("spring.cloud.zookeeper.config.property-source-contexts", contexts.stream().map(Context::getPath).collect(Collectors.toList())); - MapPropertySource propertySource = new MapPropertySource("zookeeperConfigData", source); - event.getApplicationContext().getEnvironment().getPropertySources().addFirst(propertySource); - }); - - ArrayList locations = new ArrayList<>(); - contexts.forEach(propertySourceContext -> locations - .add(new ZookeeperConfigDataResource(propertySourceContext.getPath(), location.isOptional(), propertySourceContext - .getProfile()))); - - return locations; - } - - private BindHandler getBindHandler(ConfigDataLocationResolverContext context) { - return context.getBootstrapContext().getOrElse(BindHandler.class, null); - } - - protected List getCustomContexts(UriComponents uriComponents) { - if (!StringUtils.hasLength(uriComponents.getPath())) { - return Collections.emptyList(); - } - - return Arrays.stream(uriComponents.getPath().split(";")).map(Context::new).collect(Collectors.toList()); - } - - @Nullable - protected UriComponents parseLocation(ConfigDataLocation location) { - String originalUri = location.getNonPrefixedValue(PREFIX); - if (!StringUtils.hasText(originalUri)) { - return null; - } - String uri; - if (!originalUri.startsWith("//")) { - uri = PREFIX + "//" + originalUri; - } - else { - uri = originalUri; - } - return UriComponentsBuilder.fromUriString(uri).build(); - } - - protected ZookeeperConfigProperties loadConfigProperties(ConfigDataLocationResolverContext context) { - Binder binder = context.getBinder(); - BindHandler bindHandler = getBindHandler(context); - ZookeeperConfigProperties properties = binder - .bind(ZookeeperConfigProperties.PREFIX, Bindable.of(ZookeeperConfigProperties.class), bindHandler) - .orElseGet(ZookeeperConfigProperties::new); - - if (!StringUtils.hasLength(properties.getName())) { - properties.setName(binder.bind("spring.application.name", Bindable.of(String.class), bindHandler).orElse("application")); - } - - return properties; - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataMissingEnvironmentPostProcessor.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataMissingEnvironmentPostProcessor.java deleted file mode 100644 index afe0a8c5a..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataMissingEnvironmentPostProcessor.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015-2021 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor; -import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; -import org.springframework.boot.diagnostics.FailureAnalysis; -import org.springframework.cloud.commons.ConfigDataMissingEnvironmentPostProcessor; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.core.env.Environment; - -import static org.springframework.cloud.util.PropertyUtils.bootstrapEnabled; -import static org.springframework.cloud.util.PropertyUtils.useLegacyProcessing; -import static org.springframework.cloud.zookeeper.config.ZookeeperConfigDataLocationResolver.PREFIX; - -public class ZookeeperConfigDataMissingEnvironmentPostProcessor extends ConfigDataMissingEnvironmentPostProcessor { - - /** - * Order of post processor, set to run after - * {@link ConfigDataEnvironmentPostProcessor}. - */ - public static final int ORDER = ConfigDataEnvironmentPostProcessor.ORDER + 1000; - - @Override - public int getOrder() { - return ORDER; - } - - @Override - protected boolean shouldProcessEnvironment(Environment environment) { - // don't run if using bootstrap or legacy processing - if (bootstrapEnabled(environment) || useLegacyProcessing(environment)) { - return false; - } - boolean coreEnabled = environment.getProperty(ZookeeperProperties.PREFIX + ".enabled", Boolean.class, - true); - boolean configEnabled = environment.getProperty(ZookeeperConfigProperties.PREFIX + ".enabled", Boolean.class, - true); - boolean importCheckEnabled = environment.getProperty(ZookeeperConfigProperties.PREFIX + ".import-check.enabled", - Boolean.class, true); - if (!coreEnabled || !configEnabled || !importCheckEnabled) { - return false; - } - return true; - } - - @Override - protected String getPrefix() { - return PREFIX; - } - - static class ImportExceptionFailureAnalyzer extends AbstractFailureAnalyzer { - - @Override - protected FailureAnalysis analyze(Throwable rootFailure, ImportException cause) { - String description; - if (cause.missingPrefix) { - description = "The spring.config.import property is missing a " + PREFIX + " entry"; - } - else { - description = "No spring.config.import property has been defined"; - } - String action = "Add a spring.config.import=zookeeper: property to your configuration.\n" - + "\tIf configuration is not required add spring.config.import=optional:zookeeper: instead.\n" - + "\tTo disable this check, set spring.cloud.zookeeper.config.enabled=false or \n" - + "\tspring.cloud.zookeeper.config.import-check.enabled=false."; - return new FailureAnalysis(description, action, cause); - } - - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataResource.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataResource.java deleted file mode 100644 index abb58500e..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataResource.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.Objects; - -import org.springframework.boot.context.config.ConfigDataResource; -import org.springframework.core.style.ToStringCreator; - -public class ZookeeperConfigDataResource extends ConfigDataResource { - - private final String context; - private final boolean optional; - private final String profile; - - public ZookeeperConfigDataResource(String context, boolean optional, String profile) { - this.context = context; - this.optional = optional; - this.profile = profile; - } - - @Deprecated - public ZookeeperConfigDataResource(String context, boolean optional) { - this(context, optional, null); - } - - public String getContext() { - return this.context; - } - - public boolean isOptional() { - return this.optional; - } - - public String getProfile() { - return this.profile; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ZookeeperConfigDataResource that = (ZookeeperConfigDataResource) o; - return this.optional == that.optional && this.context.equals(that.context) && Objects.equals(this.profile, that.profile); - } - - @Override - public int hashCode() { - return Objects.hash(this.optional, this.context, this.profile); - } - - @Override - public String toString() { - return new ToStringCreator(this) - .append("context", context) - .append("optional", optional) - .append("profile", profile) - .toString(); - - } -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigProperties.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigProperties.java deleted file mode 100644 index ae55f1c1e..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigProperties.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.core.style.ToStringCreator; -import org.springframework.util.Assert; - -/** - * Properties related to keeping configuration in Zookeeper. - * - * @author Spencer Gibb - * @since 1.0.0 - * @see ZookeeperPropertySourceLocator - */ -@ConfigurationProperties(ZookeeperConfigProperties.PREFIX) -public class ZookeeperConfigProperties { - - /** - * Configuration prefix for config properties. - */ - public static final String PREFIX = "spring.cloud.zookeeper.config"; - - private boolean enabled = true; - - /** - * Root folder where the configuration for Zookeeper is kept. - */ - private String root = "config"; - - /** - * Alternative to spring.application.name to use in looking up values in zookeeper. - */ - private String name; - - /** - * The name of the default context. - */ - private String defaultContext = "application"; - - /** - * Separator for profile appended to the application name. - */ - private String profileSeparator = ","; - - /** - * Throw exceptions during config lookup if true, otherwise, log warnings. - */ - private boolean failFast = true; - - public boolean isEnabled() { - return this.enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getRoot() { - return this.root; - } - - public void setRoot(String root) { - this.root = root; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDefaultContext() { - return this.defaultContext; - } - - public void setDefaultContext(String defaultContext) { - Assert.hasText(defaultContext, "spring.cloud.zookeeper.config.default-context may not be empty"); - this.defaultContext = defaultContext; - } - - public String getProfileSeparator() { - return this.profileSeparator; - } - - public void setProfileSeparator(String profileSeparator) { - Assert.hasText(profileSeparator, "spring.cloud.zookeeper.config.profile-separator may not be empty"); - this.profileSeparator = profileSeparator; - } - - public boolean isFailFast() { - return this.failFast; - } - - public void setFailFast(boolean failFast) { - this.failFast = failFast; - } - - @Override - public String toString() { - return new ToStringCreator(this) - .append("enabled", enabled) - .append("root", root) - .append("name", name) - .append("defaultContext", defaultContext) - .append("profileSeparator", profileSeparator) - .append("failFast", failFast) - .toString(); - - } -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySource.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySource.java deleted file mode 100644 index 4cd6c03a7..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySource.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.nio.charset.Charset; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.apache.zookeeper.KeeperException; - -import org.springframework.util.ReflectionUtils; - -/** - * {@link org.springframework.core.env.PropertySource} that stores properties from - * Zookeeper inside a map. Properties are loaded upon class initialization. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class ZookeeperPropertySource extends AbstractZookeeperPropertySource { - - private static final Log log = LogFactory.getLog(ZookeeperPropertySource.class); - - private Map properties = new LinkedHashMap<>(); - - public ZookeeperPropertySource(String context, CuratorFramework source) { - super(context, source); - findProperties(this.getContext(), null); - } - - @Override - public Object getProperty(String name) { - return this.properties.get(name); - } - - private byte[] getPropertyBytes(String fullPath) { - try { - byte[] bytes = null; - try { - bytes = this.getSource().getData().forPath(fullPath); - } - catch (KeeperException e) { - if (e.code() != KeeperException.Code.NONODE) { // not found - throw e; - } - } - return bytes; - } - catch (Exception exception) { - ReflectionUtils.rethrowRuntimeException(exception); - } - return null; - } - - @Override - public String[] getPropertyNames() { - Set strings = this.properties.keySet(); - return strings.toArray(new String[strings.size()]); - } - - private void findProperties(String path, List children) { - try { - log.trace("entering findProperties for path: " + path); - if (children == null) { - children = getChildren(path); - } - if (children == null || children.isEmpty()) { - return; - } - for (String child : children) { - String childPath = path + "/" + child; - List childPathChildren = getChildren(childPath); - - byte[] bytes = getPropertyBytes(childPath); - if (bytes == null || bytes.length == 0) { - if (childPathChildren == null || childPathChildren.isEmpty()) { - registerKeyValue(childPath, ""); - } - } - else { - registerKeyValue(childPath, - new String(bytes, Charset.forName("UTF-8"))); - } - - // Check children even if we have found a value for the current znode - findProperties(childPath, childPathChildren); - } - log.trace("leaving findProperties for path: " + path); - } - catch (Exception exception) { - ReflectionUtils.rethrowRuntimeException(exception); - } - } - - private void registerKeyValue(String path, String value) { - String key = sanitizeKey(path); - this.properties.put(key, value); - } - - private List getChildren(String path) throws Exception { - List children = null; - try { - children = this.getSource().getChildren().forPath(path); - } - catch (KeeperException e) { - if (e.code() != KeeperException.Code.NONODE) { // not found - throw e; - } - } - return children; - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocator.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocator.java deleted file mode 100644 index 8c184acd8..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocator.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.Arrays; -import java.util.List; - -import jakarta.annotation.PreDestroy; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.cloud.bootstrap.config.PropertySourceLocator; -import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.Environment; -import org.springframework.core.env.PropertySource; -import org.springframework.util.Assert; - -/** - * Zookeeper provides a hierarchical - * namespace that allows clients to store arbitrary data, such as configuration data. - * Spring Cloud Zookeeper Config is an alternative to the - * Config Server and - * Client. Configuration is loaded into the Spring Environment during the special - * "bootstrap" phase. Configuration is stored in the {@code /config} namespace by default. - * Multiple {@code PropertySource} instances are created based on the application's name - * and the active profiles that mimicks the Spring Cloud Config order of resolving - * properties. For example, an application with the name "testApp" and with the "dev" - * profile will have the following property sources created: - * - *
{@code
- * config/testApp,dev
- * config/testApp
- * config/application,dev
- * config/application
- * }
- * - * The most specific property source is at the top, with the least specific at the bottom. - * Properties is the {@code config/application} namespace are applicable to all - * applications using zookeeper for configuration. Properties in the - * {@code config/testApp} namespace are only available to the instances of the service - * named "testApp". - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class ZookeeperPropertySourceLocator implements PropertySourceLocator { - - private ZookeeperConfigProperties properties; - - private CuratorFramework curator; - - private List contexts; - - private static final Log log = LogFactory - .getLog(ZookeeperPropertySourceLocator.class); - - public ZookeeperPropertySourceLocator(CuratorFramework curator, - ZookeeperConfigProperties properties) { - this.curator = curator; - Assert.hasText(properties.getName(), ZookeeperConfigProperties.PREFIX + ".name must not be empty"); - this.properties = properties; - } - - public List getContexts() { - return this.contexts; - } - - @Override - public PropertySource locate(Environment environment) { - if (environment instanceof ConfigurableEnvironment) { - ConfigurableEnvironment env = (ConfigurableEnvironment) environment; - - List profiles = Arrays.asList(env.getActiveProfiles()); - - ZookeeperPropertySources sources = new ZookeeperPropertySources(properties, log); - this.contexts = sources.getAutomaticContexts(profiles); - - CompositePropertySource composite = new CompositePropertySource("zookeeper"); - - for (String propertySourceContext : this.contexts) { - PropertySource propertySource = sources.createPropertySource(propertySourceContext, true, this.curator); - composite.addPropertySource(propertySource); - } - - return composite; - } - return null; - } - - @PreDestroy - public void destroy() { - } - - private PropertySource create(String context) { - return new ZookeeperPropertySource(context, this.curator); - } - - private void addProfiles(List contexts, String baseContext, - List profiles) { - for (String profile : profiles) { - contexts.add(baseContext + this.properties.getProfileSeparator() + profile); - } - } - -} diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySources.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySources.java deleted file mode 100644 index 0730ff1b5..000000000 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySources.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import org.apache.commons.logging.Log; -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.core.style.ToStringCreator; - -public class ZookeeperPropertySources { - private final ZookeeperConfigProperties properties; - private final Log log; - - public ZookeeperPropertySources(ZookeeperConfigProperties properties, Log log) { - this.properties = properties; - this.log = log; - } - - public List getAutomaticContexts(List profiles) { - return getAutomaticContexts(profiles, true); - } - - public List getAutomaticContexts(List profiles, boolean reverse) { - return generateAutomaticContexts(profiles, reverse).stream().map(Context::getPath).collect(Collectors.toList()); - } - - public List generateAutomaticContexts(List profiles, boolean reverse) { - List contexts = new ArrayList<>(); - String root = properties.getRoot(); - - String defaultContext = root + "/" + properties.getDefaultContext(); - contexts.add(new Context(defaultContext)); - addProfiles(contexts, defaultContext, profiles); - - StringBuilder baseContext = new StringBuilder(root); - if (!properties.getName().startsWith("/")) { - baseContext.append("/"); - } - // getName() defaults to ${spring.application.name} or application - baseContext.append(properties.getName()); - contexts.add(new Context(baseContext.toString())); - addProfiles(contexts, baseContext.toString(), profiles); - - if (reverse) { - Collections.reverse(contexts); - } - return contexts; - } - - private void addProfiles(List contexts, String baseContext, List profiles) { - for (String profile : profiles) { - String path = baseContext + properties.getProfileSeparator() + profile; - contexts.add(new Context(path, profile)); - } - } - - public ZookeeperPropertySource createPropertySource(String context, boolean optional, CuratorFramework curator) { - try { - return new ZookeeperPropertySource(context, curator); - // TODO: howto call close when /refresh - } - catch (Exception e) { - if (this.properties.isFailFast() || !optional) { - throw new ZookeeperPropertySourceNotFoundException(e); - } - else { - log.warn("Unable to load zookeeper config from " + context, e); - } - } - return null; - } - public static class Context { - - private final String path; - - private final String profile; - - public Context(String path) { - this.path = path; - this.profile = null; - } - - public Context(String path, String profile) { - this.path = path; - this.profile = profile; - } - - public String getPath() { - return this.path; - } - - public String getProfile() { - return this.profile; - } - - @Override - public String toString() { - return new ToStringCreator(this).append("path", path).append("profile", profile).toString(); - - } - - } - - - static class ZookeeperPropertySourceNotFoundException extends RuntimeException { - - ZookeeperPropertySourceNotFoundException(Exception source) { - super(source); - } - } -} diff --git a/spring-cloud-zookeeper-config/src/main/resources/META-INF/spring.factories b/spring-cloud-zookeeper-config/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 9d939ce80..000000000 --- a/spring-cloud-zookeeper-config/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,18 +0,0 @@ -# Bootstrap Configuration -org.springframework.cloud.bootstrap.BootstrapConfiguration=\ -org.springframework.cloud.zookeeper.config.ZookeeperConfigBootstrapConfiguration - -# Environment PostProcessor -org.springframework.boot.env.EnvironmentPostProcessor=\ -org.springframework.cloud.zookeeper.config.ZookeeperConfigDataMissingEnvironmentPostProcessor - -org.springframework.boot.diagnostics.FailureAnalyzer=\ -org.springframework.cloud.zookeeper.config.ZookeeperConfigDataMissingEnvironmentPostProcessor.ImportExceptionFailureAnalyzer - -# ConfigData Location Resolvers -org.springframework.boot.context.config.ConfigDataLocationResolver=\ -org.springframework.cloud.zookeeper.config.ZookeeperConfigDataLocationResolver - -# ConfigData Loaders -org.springframework.boot.context.config.ConfigDataLoader=\ -org.springframework.cloud.zookeeper.config.ZookeeperConfigDataLoader diff --git a/spring-cloud-zookeeper-config/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/spring-cloud-zookeeper-config/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports deleted file mode 100644 index b7fc39f7c..000000000 --- a/spring-cloud-zookeeper-config/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ /dev/null @@ -1 +0,0 @@ -org.springframework.cloud.zookeeper.config.ZookeeperConfigAutoConfiguration diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfigurationTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfigurationTests.java deleted file mode 100644 index 15733a8ad..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfigurationTests.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.apache.zookeeper.KeeperException; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * @author Cesar Aguilera - */ -public class ZookeeperConfigAutoConfigurationTests { - - @Rule - public ExpectedException expectedException; - - @Before - public void setUp() throws Exception { - expectedException = ExpectedException.none(); - // makes Curator fail faster, otherwise it takes 15 seconds to trigger a retry - System.setProperty("curator-default-connection-timeout", "0"); - } - - @After - public void tearDown() throws Exception { - System.clearProperty("curator-default-connection-timeout"); - } - - @Test(expected = NoSuchBeanDefinitionException.class) - public void testConfigEnabledFalseDoesNotLoadZookeeperConfigAutoConfiguration() { - ConfigurableApplicationContext context = new SpringApplicationBuilder() - .listeners(new ZookeeperTestingServer()) - .sources(Config.class).web(WebApplicationType.NONE) - .run("--spring.application.name=testZookeeperConfigEnabledSetToFalse", - "--spring.config.use-legacy-processing=true", - "--spring.jmx.default-domain=testZookeeperConfigEnabledSetToFalse", - "--spring.cloud.zookeeper.config.connectString=localhost:2188", - "--spring.cloud.zookeeper.baseSleepTimeMs=0", - "--spring.cloud.zookeeper.maxRetries=0", - "--spring.cloud.zookeeper.maxSleepMs=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=0", - "--spring.cloud.zookeeper.config.failFast=false", - "--spring.cloud.zookeeper.config.enabled=false"); - - context.getBean(ZookeeperConfigAutoConfiguration.class); - } - - @Test - public void testConfigEnabledTrueLoadsZookeeperConfigAutoConfiguration() - throws Exception { - expectedException.expectCause(Matchers.isA(KeeperException.class)); - - new SpringApplicationBuilder().sources(Config.class).web(WebApplicationType.NONE) - .listeners(new ZookeeperTestingServer()) - .run("--spring.application.name=testZookeeperConfigEnabledSetToTrue", - "--spring.config.use-legacy-processing=true", - "--spring.jmx.default-domain=testZookeeperConfigEnabledSetToTrue", - "--spring.cloud.zookeeper.config.connectString=localhost:2188", - "--spring.cloud.zookeeper.baseSleepTimeMs=0", - "--spring.cloud.zookeeper.maxRetries=0", - "--spring.cloud.zookeeper.maxSleepMs=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=0", - "--spring.cloud.zookeeper.config.failFast=false", - "--spring.cloud.zookeeper.config.enabled=true"); - } - - @SpringBootConfiguration - @EnableAutoConfiguration - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataCustomizationIntegrationTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataCustomizationIntegrationTests.java deleted file mode 100644 index 7e916eac8..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataCustomizationIntegrationTests.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.UUID; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.imps.CuratorFrameworkImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.boot.BootstrapContext; -import org.springframework.boot.BootstrapRegistry; -import org.springframework.boot.BootstrapRegistryInitializer; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.properties.bind.BindContext; -import org.springframework.boot.context.properties.bind.BindHandler; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.source.ConfigurationPropertyName; -import org.springframework.cloud.zookeeper.CuratorFactory; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.ReflectionUtils; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Spencer Gibb - */ -public class ZookeeperConfigDataCustomizationIntegrationTests { - - private static final Log log = LogFactory - .getLog(ZookeeperConfigDataCustomizationIntegrationTests.class); - - public static final String PREFIX = "test__configdata__"; - - public static final String ROOT = "/" + PREFIX + UUID.randomUUID(); - - private ConfigurableApplicationContext context; - private BindHandlerBootstrapper bindHandlerBootstrapper; - - @Before - public void setup() { - bindHandlerBootstrapper = new BindHandlerBootstrapper(); - this.context = new SpringApplicationBuilder(Config.class) - .listeners(new ZookeeperTestingServer()) - .web(WebApplicationType.NONE) - .addBootstrapRegistryInitializer(bindHandlerBootstrapper) - .addBootstrapRegistryInitializer(ZookeeperBootstrapper.fromBootstrapContext(this::curatorFramework)) - .run("--spring.config.import=zookeeper:", - "--spring.application.name=testZkConfigDataIntegration", - "--logging.level.org.springframework.cloud.zookeeper=DEBUG", - "--spring.cloud.zookeeper.config.root=" + ROOT); - } - - @After - public void after() { - if (context != null) { - this.context.close(); - } - } - - CuratorFramework curatorFramework(BootstrapContext context) { - ZookeeperProperties properties = context.get(ZookeeperProperties.class); - CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() - .retryPolicy(CuratorFactory.retryPolicy(properties)) - .connectString(properties.getConnectString()); - TestCuratorFramework curator = new TestCuratorFramework(builder); - curator.start(); - try { - curator.blockUntilConnected(properties.getBlockUntilConnectedWait(), - properties.getBlockUntilConnectedUnit()); - } - catch (InterruptedException e) { - ReflectionUtils.rethrowRuntimeException(e); - } - return curator; - } - - @Test - public void curatorFrameworkIsCustom() { - CuratorFramework curator = context.getBean(CuratorFramework.class); - assertThat(curator).isNotNull().isInstanceOf(TestCuratorFramework.class); - assertThat(bindHandlerBootstrapper.onSuccessCount).isGreaterThan(0); - } - - static class TestCuratorFramework extends CuratorFrameworkImpl { - TestCuratorFramework(CuratorFrameworkFactory.Builder builder) { - super(builder); - } - } - - @Configuration - @EnableAutoConfiguration - static class Config { - - } - - static class BindHandlerBootstrapper implements BootstrapRegistryInitializer { - - private int onSuccessCount = 0; - - @Override - public void initialize(BootstrapRegistry registry) { - registry.register(BindHandler.class, context -> new BindHandler() { - @Override - public Object onSuccess(ConfigurationPropertyName name, Bindable target, BindContext context, - Object result) { - onSuccessCount++; - return result; - } - }); - } - - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataIntegrationTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataIntegrationTests.java deleted file mode 100644 index c6d3d9a2a..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataIntegrationTests.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryOneTime; -import org.apache.zookeeper.KeeperException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.context.environment.EnvironmentChangeEvent; -import org.springframework.cloud.context.refresh.ConfigDataContextRefresher; -import org.springframework.cloud.context.refresh.ContextRefresher; -import org.springframework.cloud.context.scope.refresh.RefreshScope; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.ApplicationListener; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Spencer Gibb - */ -public class ZookeeperConfigDataIntegrationTests { - - private static final Log log = LogFactory - .getLog(ZookeeperConfigDataIntegrationTests.class); - - public static final String APPLICATION_NAME = "testZkConfigDataIntegration"; - - public static final String PREFIX = "test__configdata__"; - - public static final String ROOT = "/" + PREFIX + UUID.randomUUID(); - - public static final String CONTEXT = ROOT + "/application/"; - - public static final String KEY_BASIC = "testProp"; - - public static final String KEY_BASIC_PATH = CONTEXT + KEY_BASIC; - - public static final String KEY_APP_PATH = ROOT + "/" + APPLICATION_NAME + "/" + KEY_BASIC; - - public static final String VAL_BASIC_DEFAULT = "testPropValDefault"; - - public static final String VAL_BASIC = "testPropVal"; - - public static final String KEY_WITH_DOT = "testProp.dot"; - - public static final String KEY_WITH_DOT_PATH = CONTEXT + KEY_WITH_DOT; - - public static final String VAL_WITH_DOT = "withDotVal"; - - public static final String KEY_NESTED = "testProp.nested"; - - public static final String KEY_NESTED_PATH = CONTEXT + KEY_NESTED.replace('.', '/'); - - public static final String VAL_NESTED = "nestedVal"; - - public static final String KEY_WITHOUT_VALUE = "testProp.novalue"; - - public static final String KEY_WITHOUT_VALUE_PATH = CONTEXT + KEY_WITHOUT_VALUE; - - private ConfigurableEnvironment environment; - - private ConfigurableApplicationContext context; - - private CuratorFramework curator; - private ZookeeperTestingServer testingServer; - - @Before - public void setup() throws Exception { - testingServer = new ZookeeperTestingServer(); - testingServer.start(); - String connectString = "localhost:" + testingServer.getPort(); - this.curator = CuratorFrameworkFactory.builder() - .retryPolicy(new RetryOneTime(500)).connectString(connectString).build(); - this.curator.start(); - - List children = this.curator.getChildren().forPath("/"); - for (String child : children) { - if (child.startsWith(PREFIX) && child.length() > PREFIX.length()) { - delete("/" + child); - } - } - - StringBuilder create = new StringBuilder(1024); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_BASIC_PATH, VAL_BASIC_DEFAULT.getBytes())).append('\n'); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_APP_PATH, VAL_BASIC.getBytes())).append('\n'); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_WITH_DOT_PATH, VAL_WITH_DOT.getBytes())).append('\n'); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_NESTED_PATH, VAL_NESTED.getBytes())).append('\n'); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_WITHOUT_VALUE_PATH, null)).append('\n'); - this.curator.close(); - System.out.println(create); - - this.context = new SpringApplicationBuilder(Config.class) - .web(WebApplicationType.NONE) - .run("--spring.config.import=zookeeper:" + connectString, - "--spring.application.name=" + APPLICATION_NAME, - "--logging.level.org.springframework.cloud.zookeeper=DEBUG", - "--spring.cloud.zookeeper.config.root=" + ROOT); - - this.curator = this.context.getBean(CuratorFramework.class); - this.environment = this.context.getEnvironment(); - } - - public void delete(String path) throws Exception { - try { - this.curator.delete().deletingChildrenIfNeeded().forPath(path); - } - catch (KeeperException e) { - if (e.code() != KeeperException.Code.NONODE) { - throw e; - } - } - } - - @After - public void after() throws Exception { - try { - delete(ROOT); - } - finally { - this.context.close(); - this.testingServer.close(); - } - } - - @Test - public void checkKeyValues() { - String propValue = this.environment.getProperty(KEY_BASIC); - assertThat(propValue).as(KEY_BASIC + " was wrong").isEqualTo(VAL_BASIC); - - propValue = this.environment.getProperty(KEY_NESTED); - assertThat(propValue).as(VAL_NESTED + " was wrong").isEqualTo(VAL_NESTED); - - propValue = this.environment.getProperty(KEY_WITH_DOT); - assertThat(propValue).as(VAL_WITH_DOT + " was wrong").isEqualTo(VAL_WITH_DOT); - - propValue = this.environment.getProperty(KEY_WITHOUT_VALUE); - assertThat(propValue).as(KEY_WITHOUT_VALUE + " was wrong").isEmpty(); - } - - @Test - public void propertyLoadedAndUpdated() throws Exception { - String testProp = this.environment.getProperty(KEY_BASIC); - assertThat(testProp).as("testProp was wrong").isEqualTo(VAL_BASIC); - - this.curator.setData().forPath(KEY_APP_PATH, "testPropValUpdate".getBytes()); - - CountDownLatch latch = this.context.getBean(CountDownLatch.class); - boolean receivedEvent = latch.await(15, TimeUnit.SECONDS); - assertThat(receivedEvent).as("listener didn't receive event").isTrue(); - - testProp = this.environment.getProperty(KEY_BASIC); - assertThat(testProp).as("testProp was wrong after update") - .isEqualTo("testPropValUpdate"); - } - - @Configuration - @EnableAutoConfiguration - static class Config implements ApplicationListener { - - @Bean - public CountDownLatch countDownLatch() { - return new CountDownLatch(1); - } - - @Bean - public ContextRefresher contextRefresher(ConfigurableApplicationContext context, - RefreshScope scope) { - return new ConfigDataContextRefresher(context, scope); - } - - @Override - public void onApplicationEvent(EnvironmentChangeEvent event) { - log.debug("Event keys: " + event.getKeys()); - if (event.getKeys().contains(KEY_BASIC)) { - countDownLatch().countDown(); - } - } - - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLocationResolverTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLocationResolverTests.java deleted file mode 100644 index 17eb05143..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataLocationResolverTests.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import org.apache.commons.logging.LogFactory; -import org.junit.jupiter.api.Test; - -import org.springframework.boot.ConfigurableBootstrapContext; -import org.springframework.boot.context.config.ConfigDataLocation; -import org.springframework.boot.context.config.ConfigDataLocationResolverContext; -import org.springframework.boot.context.config.Profiles; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.web.util.UriComponents; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ZookeeperConfigDataLocationResolverTests { - - @Test - public void testParseLocation() { - ZookeeperConfigDataLocationResolver resolver = new ZookeeperConfigDataLocationResolver(destination -> LogFactory.getLog(ZookeeperConfigDataLocationResolver.class)); - UriComponents uriComponents = resolver.parseLocation( - ConfigDataLocation.of("zookeeper:myhost:2182/mypath1;/mypath2;/mypath3")); - assertThat(uriComponents.toUri()).hasScheme("zookeeper").hasHost("myhost") - .hasPort(2182).hasPath("/mypath1;/mypath2;/mypath3"); - - uriComponents = resolver.parseLocation(ConfigDataLocation.of("zookeeper:myhost:2182")); - assertThat(uriComponents.toUri()).hasScheme("zookeeper").hasHost("myhost") - .hasPort(2182).hasPath(""); - } - - @Test - public void testResolveProfileSpecificWithCustomPaths() { - String location = "zookeeper:myhost:2182/mypath1;/mypath2;/mypath3"; - List locations = testResolveProfileSpecific(location); - assertThat(locations).hasSize(3); - assertThat(toContexts(locations)).containsExactly("/mypath1", "/mypath2", - "/mypath3"); - } - - @Test - public void testResolveProfileSpecificWithAutomaticPaths() { - String location = "zookeeper:myhost:1234"; - List locations = testResolveProfileSpecific(location); - assertThat(locations).hasSize(4); - assertThat(toContexts(locations)).containsExactly("config/application", - "config/application,dev", "config/testapp", "config/testapp,dev"); - } - - private List toContexts(List locations) { - return locations.stream().map(ZookeeperConfigDataResource::getContext) - .collect(Collectors.toList()); - } - - private List testResolveProfileSpecific(String location) { - ZookeeperConfigDataLocationResolver resolver = createResolver(); - - MockEnvironment env = new MockEnvironment(); - env.setProperty("spring.application.name", "testapp"); - - ConfigurableBootstrapContext bootstrapContext = mock(ConfigurableBootstrapContext.class); - - ConfigDataLocationResolverContext context = mock( - ConfigDataLocationResolverContext.class); - - when(context.getBootstrapContext()).thenReturn(bootstrapContext); - when(context.getBinder()).thenReturn(Binder.get(env)); - - Profiles profiles = mock(Profiles.class); - when(profiles.getAccepted()).thenReturn(Collections.singletonList("dev")); - - return resolver.resolveProfileSpecific(context, ConfigDataLocation.of(location), profiles); - } - - private ZookeeperConfigDataLocationResolver createResolver() { - return new ZookeeperConfigDataLocationResolver(destination -> LogFactory.getLog(ZookeeperConfigDataLocationResolver.class)); - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataMissingEnvironmentPostProcessorTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataMissingEnvironmentPostProcessorTests.java deleted file mode 100644 index 148528748..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataMissingEnvironmentPostProcessorTests.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2015-2021 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.junit.jupiter.api.Test; - -import org.springframework.boot.SpringApplication; -import org.springframework.mock.env.MockEnvironment; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; - -/** - * @author Ryan Baxter - */ -class ZookeeperConfigDataMissingEnvironmentPostProcessorTests { - - @Test - void noSpringConfigImport() { - MockEnvironment environment = new MockEnvironment(); - SpringApplication app = mock(SpringApplication.class); - ZookeeperConfigDataMissingEnvironmentPostProcessor processor = new ZookeeperConfigDataMissingEnvironmentPostProcessor(); - assertThatThrownBy(() -> processor.postProcessEnvironment(environment, app)) - .isInstanceOf(ZookeeperConfigDataMissingEnvironmentPostProcessor.ImportException.class); - } - - @Test - void boostrap() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("spring.cloud.bootstrap.enabled", "true"); - SpringApplication app = mock(SpringApplication.class); - ZookeeperConfigDataMissingEnvironmentPostProcessor processor = new ZookeeperConfigDataMissingEnvironmentPostProcessor(); - assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException(); - } - - @Test - void legacy() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("spring.config.use-legacy-processing", "true"); - SpringApplication app = mock(SpringApplication.class); - ZookeeperConfigDataMissingEnvironmentPostProcessor processor = new ZookeeperConfigDataMissingEnvironmentPostProcessor(); - assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException(); - } - - @Test - void configNotEnabled() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("spring.cloud.zookeeper.enabled", "false"); - SpringApplication app = mock(SpringApplication.class); - ZookeeperConfigDataMissingEnvironmentPostProcessor processor = new ZookeeperConfigDataMissingEnvironmentPostProcessor(); - assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException(); - } - - @Test - void importCheckNotEnabled() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("spring.cloud.zookeeper.config.import-check.enabled", "false"); - SpringApplication app = mock(SpringApplication.class); - ZookeeperConfigDataMissingEnvironmentPostProcessor processor = new ZookeeperConfigDataMissingEnvironmentPostProcessor(); - assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException(); - } - - @Test - void importSinglePropertySource() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("spring.config.import", "zookeeper:http://localhost:8888"); - SpringApplication app = mock(SpringApplication.class); - ZookeeperConfigDataMissingEnvironmentPostProcessor processor = new ZookeeperConfigDataMissingEnvironmentPostProcessor(); - assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException(); - } - - @Test - void importMultiplePropertySource() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("spring.config.import", "zookeeper:http://localhost:8888,file:./app.properties"); - SpringApplication app = mock(SpringApplication.class); - ZookeeperConfigDataMissingEnvironmentPostProcessor processor = new ZookeeperConfigDataMissingEnvironmentPostProcessor(); - assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException(); - } - - @Test - void importMultiplePropertySourceAsList() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("spring.config.import[0]", "zookeeper:http://localhost:8888"); - environment.setProperty("spring.config.import[1]", "file:./app.properties"); - SpringApplication app = mock(SpringApplication.class); - ZookeeperConfigDataMissingEnvironmentPostProcessor processor = new ZookeeperConfigDataMissingEnvironmentPostProcessor(); - assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException(); - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataNoImportIntegrationTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataNoImportIntegrationTests.java deleted file mode 100644 index 85a65e13f..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataNoImportIntegrationTests.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.test.system.CapturedOutput; -import org.springframework.boot.test.system.OutputCaptureExtension; -import org.springframework.cloud.commons.ConfigDataMissingEnvironmentPostProcessor; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Configuration; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.cloud.zookeeper.config.ZookeeperConfigDataLocationResolver.PREFIX; - -/** - * @author Spencer Gibb - */ -@ExtendWith(OutputCaptureExtension.class) -public class ZookeeperConfigDataNoImportIntegrationTests { - - private static final String APP_NAME = "testZookeeperConfigDataNoImport"; - - @Test - public void exceptionThrownIfNoImport(CapturedOutput output) { - Assertions.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE) - .run("--spring.application.name=" + APP_NAME)).isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class); - - assertThat(output).contains("No spring.config.import property has been defined") - .contains("Add a spring.config.import=zookeeper: property to your configuration"); - } - - @Test - public void exceptionThrownIfImportMissingZookeeper(CapturedOutput output) { - Assertions.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run( - "--spring.config.import=optional:file:somefile.properties", "--spring.application.name=" + APP_NAME)) - .isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class); - - assertThat(output).contains("spring.config.import property is missing a " + PREFIX) - .contains("Add a spring.config.import=zookeeper: property to your configuration"); - } - - @Test - public void noExceptionThrownIfZookeeperDisabled() { - try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class) - .web(WebApplicationType.NONE) - .run("--spring.cloud.zookeeper.enabled=false", "--spring.application.name=" + APP_NAME)) { - // nothing to do - } - } - - @Test - public void noExceptionThrownIfZookeeperConfigDisabled() { - try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class) - .web(WebApplicationType.NONE) - .run("--spring.cloud.zookeeper.config.enabled=false", "--spring.application.name=" + APP_NAME)) { - // nothing to do - } - } - - @Test - public void noExceptionThrownIfImportCheckDisabled() { - try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class) - .web(WebApplicationType.NONE).run("--spring.cloud.zookeeper.config.import-check.enabled=false", - "--spring.application.name=" + APP_NAME)) { - // nothing to do - } - } - - @Configuration - @EnableAutoConfiguration - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataNotOptionalIntegrationTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataNotOptionalIntegrationTests.java deleted file mode 100644 index 6b2ebaf22..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigDataNotOptionalIntegrationTests.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.config.ConfigDataResourceNotFoundException; -import org.springframework.cloud.context.refresh.ConfigDataContextRefresher; -import org.springframework.cloud.context.refresh.ContextRefresher; -import org.springframework.cloud.context.scope.refresh.RefreshScope; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author Spencer Gibb - */ -public class ZookeeperConfigDataNotOptionalIntegrationTests { - - @Test - public void configDataNotFoundThrowsException() { - Assertions.assertThatThrownBy(() -> { - ConfigurableApplicationContext context = null; - try { - context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run( - "--spring.cloud.zookeeper.connect-string=notexistantdomain:5000", "--debug=true", - "--spring.cloud.zookeeper.max-retries=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=1", - "--spring.cloud.zookeeper.blockUntilConnectedUnit=MILLISECONDS", - "--spring.cloud.zookeeper.connection-timeout=1ms", - "--spring.config.import=zookeeper:", - "--spring.application.name=testZkConfigDataNotOptionalIntegration", - "--logging.level.org.springframework.cloud.zookeeper=DEBUG", - "--spring.cloud.zookeeper.config.root=/shouldfail"); - - } - finally { - if (context != null) { - context.close(); - } - } - }).isInstanceOf(ConfigDataResourceNotFoundException.class); - } - - @Configuration - @EnableAutoConfiguration - static class Config { - - @Bean - public ContextRefresher contextRefresher(ConfigurableApplicationContext context, RefreshScope scope) { - return new ConfigDataContextRefresher(context, scope); - } - - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorFailFastTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorFailFastTests.java deleted file mode 100644 index f7fa13f6b..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorFailFastTests.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -/** - * @author Enrique Recarte Llorens - * @author Olga Maciaszek-Sharma - */ -public class ZookeeperPropertySourceLocatorFailFastTests { - - @Before - public void setUp() { - // This system property makes Curator fail faster, otherwise it takes 15 seconds - // to trigger a retry - System.setProperty("curator-default-connection-timeout", "0"); - } - - @After - public void tearDown() { - System.clearProperty("curator-default-connection-timeout"); - } - - @Test - public void testFailFastFalseLoadsTheApplicationContext() { - assertThatCode(() -> { - new SpringApplicationBuilder().sources(Config.class) - .web(WebApplicationType.NONE) - .run("--spring.application.name=testZookeeperPropertySourceLocatorFailFast", - "--spring.config.use-legacy-processing=true", - "--spring.cloud.zookeeper.config.connectString=localhost:2188", - "--spring.cloud.zookeeper.baseSleepTimeMs=0", - "--spring.cloud.zookeeper.maxRetries=0", - "--spring.cloud.zookeeper.maxSleepMs=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=0", - "--spring.cloud.zookeeper.config.failFast=false"); - }).doesNotThrowAnyException(); - } - - @Test - public void testFailFastTrueDoesNotLoadTheApplicationContext() { - assertThatThrownBy(() -> { - new SpringApplicationBuilder().sources(Config.class) - .web(WebApplicationType.NONE) - .run("--spring.application.name=testZookeeperPropertySourceLocatorFailFast", - "--spring.config.use-legacy-processing=true", - "--spring.cloud.zookeeper.config.connectString=localhost:2188", - "--spring.cloud.zookeeper.baseSleepTimeMs=0", - "--spring.cloud.zookeeper.maxRetries=0", - "--spring.cloud.zookeeper.maxSleepMs=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=0", - "--spring.cloud.zookeeper.config.failFast=true"); - }) - .isNotNull(); - } - - @SpringBootConfiguration - @EnableAutoConfiguration - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorNoApplicationNameTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorNoApplicationNameTests.java deleted file mode 100644 index 2e3bb1086..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorNoApplicationNameTests.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.api.GetChildrenBuilder; -import org.junit.Test; - -import org.springframework.mock.env.MockEnvironment; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author Spencer Gibb - */ -public class ZookeeperPropertySourceLocatorNoApplicationNameTests { - - @Test - public void defaultSpringApplicationNameWorks() { - CuratorFramework curator = mock(CuratorFramework.class); - when(curator.getChildren()).thenReturn(mock(GetChildrenBuilder.class)); - ZookeeperConfigProperties properties = new ZookeeperConfigProperties(); - properties.setName("notempty"); - ZookeeperPropertySourceLocator locator = new ZookeeperPropertySourceLocator( - curator, properties); - locator.locate(new MockEnvironment()); - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorTests.java deleted file mode 100644 index a4f06258e..000000000 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorTests.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.config; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.api.GetChildrenBuilder; -import org.apache.curator.retry.RetryOneTime; -import org.apache.zookeeper.KeeperException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.context.environment.EnvironmentChangeEvent; -import org.springframework.cloud.context.refresh.ContextRefresher; -import org.springframework.cloud.context.refresh.LegacyContextRefresher; -import org.springframework.cloud.context.scope.refresh.RefreshScope; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.ApplicationListener; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.PropertySource; -import org.springframework.mock.env.MockEnvironment; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author Spencer Gibb - */ -public class ZookeeperPropertySourceLocatorTests { - - private static final Log log = LogFactory - .getLog(ZookeeperPropertySourceLocatorTests.class); - - public static final String PREFIX = "test__config__"; - - public static final String ROOT = "/" + PREFIX + UUID.randomUUID(); - - public static final String CONTEXT = ROOT + "/application/"; - - public static final String KEY_BASIC = "testProp"; - - public static final String KEY_BASIC_PATH = CONTEXT + KEY_BASIC; - - public static final String VAL_BASIC = "testPropVal"; - - public static final String KEY_WITH_DOT = "testProp.dot"; - - public static final String KEY_WITH_DOT_PATH = CONTEXT + KEY_WITH_DOT; - - public static final String VAL_WITH_DOT = "withDotVal"; - - public static final String KEY_NESTED = "testProp.nested"; - - public static final String KEY_NESTED_PATH = CONTEXT + KEY_NESTED.replace('.', '/'); - - public static final String VAL_NESTED = "nestedVal"; - - public static final String KEY_WITHOUT_VALUE = "testProp.novalue"; - - public static final String KEY_WITHOUT_VALUE_PATH = CONTEXT + KEY_WITHOUT_VALUE; - - private ConfigurableEnvironment environment; - - private ConfigurableApplicationContext context; - - private ZookeeperTestingServer testingServer; - - private CuratorFramework curator; - - private ZookeeperConfigProperties properties; - - @Before - public void setup() throws Exception { - this.testingServer = new ZookeeperTestingServer(); - testingServer.start(); - String connectString = "localhost:" + testingServer.getPort(); - this.curator = CuratorFrameworkFactory.builder() - .retryPolicy(new RetryOneTime(500)).connectString(connectString).build(); - this.curator.start(); - - List children = this.curator.getChildren().forPath("/"); - for (String child : children) { - if (child.startsWith(PREFIX) && child.length() > PREFIX.length()) { - delete("/" + child); - } - } - - StringBuilder create = new StringBuilder(1024); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_BASIC_PATH, VAL_BASIC.getBytes())).append('\n'); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_WITH_DOT_PATH, VAL_WITH_DOT.getBytes())).append('\n'); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_NESTED_PATH, VAL_NESTED.getBytes())).append('\n'); - create.append(this.curator.create().creatingParentsIfNeeded() - .forPath(KEY_WITHOUT_VALUE_PATH, null)).append('\n'); - this.curator.close(); - System.out.println(create); - - this.context = new SpringApplicationBuilder(Config.class) - .web(WebApplicationType.NONE) - .run("--spring.cloud.zookeeper.connectString=" + connectString, - "--spring.config.use-legacy-processing=true", - "--spring.application.name=testZkPropertySource", - "--logging.level.org.springframework.cloud.zookeeper=DEBUG", - "--spring.cloud.zookeeper.config.root=" + ROOT); - - this.curator = this.context.getBean(CuratorFramework.class); - this.properties = this.context.getBean(ZookeeperConfigProperties.class); - this.environment = this.context.getEnvironment(); - } - - public void delete(String path) throws Exception { - try { - this.curator.delete().deletingChildrenIfNeeded().forPath(path); - } - catch (KeeperException e) { - if (e.code() != KeeperException.Code.NONODE) { - throw e; - } - } - } - - @After - public void after() throws Exception { - try { - delete(this.properties.getRoot()); - } - finally { - this.context.close(); - this.testingServer.close(); - } - } - - @Test - public void checkKeyValues() throws Exception { - String propValue = this.environment.getProperty(KEY_BASIC); - assertThat(propValue).as(KEY_BASIC + " was wrong").isEqualTo(VAL_BASIC); - - propValue = this.environment.getProperty(KEY_NESTED); - assertThat(propValue).as(VAL_NESTED + " was wrong").isEqualTo(VAL_NESTED); - - propValue = this.environment.getProperty(KEY_WITH_DOT); - assertThat(propValue).as(VAL_WITH_DOT + " was wrong").isEqualTo(VAL_WITH_DOT); - - propValue = this.environment.getProperty(KEY_WITHOUT_VALUE); - assertThat(propValue).as(KEY_WITHOUT_VALUE + " was wrong").isEmpty(); - } - - @Test - public void propertyLoadedAndUpdated() throws Exception { - String testProp = this.environment.getProperty(KEY_BASIC); - assertThat(testProp).as("testProp was wrong").isEqualTo(VAL_BASIC); - - this.curator.setData().forPath(KEY_BASIC_PATH, "testPropValUpdate".getBytes()); - - CountDownLatch latch = this.context.getBean(CountDownLatch.class); - boolean receivedEvent = latch.await(15, TimeUnit.SECONDS); - assertThat(receivedEvent).as("listener didn't receive event").isTrue(); - - testProp = this.environment.getProperty(KEY_BASIC); - assertThat(testProp).as("testProp was wrong after update") - .isEqualTo("testPropValUpdate"); - } - - @Test - public void compositePropertySourceHoldsPropertySourcesInCorrectOrder() { - - // given - final String defaultContext = "someDefaultContext"; - final String someName = "someName"; - final String someProfile = "someProfile"; - - final CuratorFramework curator = mock(CuratorFramework.class); - when(curator.getChildren()).thenReturn(mock(GetChildrenBuilder.class)); - - final MockEnvironment mockEnvironment = new MockEnvironment(); - mockEnvironment.setActiveProfiles(someProfile); - - final ZookeeperConfigProperties properties = new ZookeeperConfigProperties(); - properties.setName(someName); - properties.setDefaultContext(defaultContext); - - final ZookeeperPropertySourceLocator locator = new ZookeeperPropertySourceLocator( - curator, properties); - - // when - final PropertySource propertySource = locator.locate(mockEnvironment); - - // then - assertThat(propertySource).isInstanceOf(CompositePropertySource.class); - - // and - final ArrayList> propertySources = new ArrayList<>( - ((CompositePropertySource) propertySource).getPropertySources()); - - assertThat(propertySources.get(0).getName()) - .endsWith(someName + properties.getProfileSeparator() + someProfile); - assertThat(propertySources.get(1).getName()).endsWith(someName); - assertThat(propertySources.get(2).getName()).endsWith( - defaultContext + properties.getProfileSeparator() + someProfile); - assertThat(propertySources.get(3).getName()).endsWith(defaultContext); - } - - @Configuration - @EnableAutoConfiguration - static class Config implements ApplicationListener { - - @Bean - public CountDownLatch countDownLatch() { - return new CountDownLatch(1); - } - - @Bean - public ContextRefresher contextRefresher(ConfigurableApplicationContext context, - RefreshScope scope) { - return new LegacyContextRefresher(context, scope); - } - - @Override - public void onApplicationEvent(EnvironmentChangeEvent event) { - log.debug("Event keys: " + event.getKeys()); - if (event.getKeys().contains(KEY_BASIC)) { - countDownLatch().countDown(); - } - } - - } - -} diff --git a/spring-cloud-zookeeper-config/src/test/resources/application.yml b/spring-cloud-zookeeper-config/src/test/resources/application.yml deleted file mode 100644 index 7a74dfbd3..000000000 --- a/spring-cloud-zookeeper-config/src/test/resources/application.yml +++ /dev/null @@ -1,3 +0,0 @@ -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR \ No newline at end of file diff --git a/spring-cloud-zookeeper-core/.flattened-pom.xml b/spring-cloud-zookeeper-core/.flattened-pom.xml new file mode 100644 index 000000000..14ddbff02 --- /dev/null +++ b/spring-cloud-zookeeper-core/.flattened-pom.xml @@ -0,0 +1,170 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + .. + + org.springframework.cloud + spring-cloud-zookeeper-core + 4.1.0-SNAPSHOT + Spring Cloud Zookeeper Core + Spring Cloud Zookeeper Core + https://spring.io/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-core + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-core + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-core + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-core + + + + org.springframework.boot + spring-boot-configuration-processor + 3.2.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-starter-web + 3.2.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-starter-actuator + 3.2.0-SNAPSHOT + compile + true + + + org.springframework.cloud + spring-cloud-commons + 4.1.0-SNAPSHOT + compile + true + + + org.apache.curator + curator-x-discovery + 5.1.0 + compile + + + log4j + log4j + + + io.netty + netty + + + true + + + org.apache.curator + curator-framework + 5.1.0 + compile + + + log4j + log4j + + + io.netty + netty + + + true + + + org.springframework.boot + spring-boot-autoconfigure-processor + 3.2.0-SNAPSHOT + compile + true + + + diff --git a/spring-cloud-zookeeper-core/pom.xml b/spring-cloud-zookeeper-core/pom.xml deleted file mode 100644 index 67631b390..000000000 --- a/spring-cloud-zookeeper-core/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - 4.0.0 - - spring-cloud-zookeeper-core - jar - Spring Cloud Zookeeper Core - Spring Cloud Zookeeper Core - - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - .. - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-jar-plugin - 3.2.0 - - - - test-jar - - - - - - - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-web - true - - - org.springframework.boot - spring-boot-starter-actuator - true - - - org.springframework.cloud - spring-cloud-commons - true - - - org.apache.curator - curator-x-discovery - true - - - org.apache.curator - curator-framework - true - - - org.springframework.boot - spring-boot-autoconfigure-processor - true - - - org.apache.curator - curator-test - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - test - - - - diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ConditionalOnZookeeperEnabled.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ConditionalOnZookeeperEnabled.java deleted file mode 100644 index 4bf73c44e..000000000 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ConditionalOnZookeeperEnabled.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - -/** - * Wrapper annotation to enable Zookeeper. - * - * @author Marcin Grzejszczak - * @since 1.1.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE, ElementType.METHOD }) -@ConditionalOnProperty(value = "spring.cloud.zookeeper.enabled", matchIfMissing = true) -public @interface ConditionalOnZookeeperEnabled { - -} diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/CuratorFactory.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/CuratorFactory.java deleted file mode 100644 index 41b190643..000000000 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/CuratorFactory.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import java.util.function.Predicate; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.RetryPolicy; -import org.apache.curator.drivers.TracerDriver; -import org.apache.curator.ensemble.EnsembleProvider; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; - -import org.springframework.boot.BootstrapContext; -import org.springframework.boot.BootstrapRegistry; -import org.springframework.boot.context.config.ConfigDataException; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.util.StringUtils; -import org.springframework.web.util.UriComponents; - -public abstract class CuratorFactory { - - private static final Log log = LogFactory.getLog(ZookeeperAutoConfiguration.class); - - public static CuratorFramework curatorFramework(ZookeeperProperties properties, RetryPolicy retryPolicy, - Supplier> optionalCuratorFrameworkCustomizerProvider, - Supplier optionalEnsembleProvider, Supplier optionalTracerDriverProvider) - throws Exception { - CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - - EnsembleProvider ensembleProvider = optionalEnsembleProvider.get(); - if (ensembleProvider != null) { - builder.ensembleProvider(ensembleProvider); - } - else { - builder.connectString(properties.getConnectString()); - } - builder.sessionTimeoutMs((int) properties.getSessionTimeout().toMillis()) - .connectionTimeoutMs((int) properties.getConnectionTimeout().toMillis()).retryPolicy(retryPolicy); - - Stream customizers = optionalCuratorFrameworkCustomizerProvider.get(); - if (customizers != null) { - customizers.forEach(curatorFrameworkCustomizer -> curatorFrameworkCustomizer.customize(builder)); - } - - CuratorFramework curator = builder.build(); - TracerDriver tracerDriver = optionalTracerDriverProvider.get(); - if (tracerDriver != null && curator.getZookeeperClient() != null) { - curator.getZookeeperClient().setTracerDriver(tracerDriver); - } - - curator.start(); - if (log.isTraceEnabled()) { - log.trace("blocking until connected to zookeeper for " + properties.getBlockUntilConnectedWait() - + properties.getBlockUntilConnectedUnit()); - } - curator.blockUntilConnected(properties.getBlockUntilConnectedWait(), properties.getBlockUntilConnectedUnit()); - if (log.isTraceEnabled()) { - log.trace("connected to zookeeper"); - } - return curator; - } - - public static RetryPolicy retryPolicy(ZookeeperProperties properties) { - return new ExponentialBackoffRetry(properties.getBaseSleepTimeMs(), properties.getMaxRetries(), - properties.getMaxSleepMs()); - } - - public static void registerCurator(BootstrapRegistry registery, UriComponents location, boolean optional) { - registerCurator(registery, location, optional, bootstrapContext -> true); - } - - public static void registerCurator(BootstrapRegistry registery, UriComponents location, boolean optional, - Predicate predicate) { - registery.registerIfAbsent(ZookeeperProperties.class, context -> { - if (!predicate.test(context)) { - return null; - } - return loadProperties(context.get(Binder.class), location); - }); - - registery.registerIfAbsent(RetryPolicy.class, context -> { - if (!predicate.test(context)) { - return null; - } - return retryPolicy(context.get(ZookeeperProperties.class)); - }); - - registery.registerIfAbsent(CuratorFramework.class, context -> { - if (!predicate.test(context)) { - return null; - } - return curatorFramework(context, context.get(ZookeeperProperties.class), optional); - }); - - // promote beans to context - registery.addCloseListener(event -> { - BootstrapContext context = event.getBootstrapContext(); - if (predicate.test(context)) { - CuratorFramework curatorFramework = context.get(CuratorFramework.class); - if (!event.getApplicationContext().getBeanFactory().containsBean("configDataCuratorFramework")) { - event.getApplicationContext().getBeanFactory().registerSingleton("configDataCuratorFramework", - curatorFramework); - } - } - }); - - } - - static ZookeeperProperties loadProperties(Binder binder, UriComponents location) { - ZookeeperProperties properties = binder.bind(ZookeeperProperties.PREFIX, Bindable.of(ZookeeperProperties.class)) - .orElse(new ZookeeperProperties()); - - if (location != null && StringUtils.hasText(location.getHost())) { - if (location.getPort() < 0) { - throw new IllegalArgumentException( - "zookeeper port must be greater than or equal to zero: " + location.getPort()); - } - properties.setConnectString(location.getHost() + ":" + location.getPort()); - } - - return properties; - } - - private static CuratorFramework curatorFramework(BootstrapContext context, ZookeeperProperties properties, - boolean optional) { - - Supplier> customizers; - // TODO: use new apis after milestone release - try { - CuratorFrameworkCustomizer customizer = context.get(CuratorFrameworkCustomizer.class); - customizers = () -> Stream.of(customizer); - } - catch (IllegalStateException e) { - customizers = () -> null; - } - try { - return CuratorFactory.curatorFramework(properties, context.get(RetryPolicy.class), customizers, - supplier(context, EnsembleProvider.class), supplier(context, TracerDriver.class)); - } - catch (Exception e) { - if (!optional) { - log.error("Unable to connect to zookeeper", e); - throw new ZookeeperConnectException("Unable to connect to zookeeper", e); - } - if (log.isDebugEnabled()) { - log.debug("Unable to connect to zookeeper", e); - } - } - return null; - } - - private static Supplier supplier(BootstrapContext context, Class type) { - try { - // TODO: use new apis after milestone release - T instance = context.get(type); - return () -> instance; - } - catch (IllegalStateException e) { - return () -> null; - } - } - - private static class ZookeeperConnectException extends ConfigDataException { - - /** - * Create a new {@link ConfigDataException} instance. - * @param message the exception message - * @param cause the exception cause - */ - protected ZookeeperConnectException(String message, Throwable cause) { - super(message, cause); - } - } - -} diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/CuratorFrameworkCustomizer.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/CuratorFrameworkCustomizer.java deleted file mode 100644 index e450a5e54..000000000 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/CuratorFrameworkCustomizer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; - -import org.springframework.beans.factory.ObjectProvider; - -/** - * Beans that implement this interface will be used by the - * {@link ZookeeperAutoConfiguration#curatorFramework(RetryPolicy, ZookeeperProperties, ObjectProvider, ObjectProvider, ObjectProvider) - * ZookeeperAutoConfiguration} ZookeeperAutoConfiguration} to further customize the - * {@link CuratorFramework} that it provides. - * - * @author Bernardo Gomez Palacio. - * @see ZookeeperAutoConfiguration - */ -@FunctionalInterface -public interface CuratorFrameworkCustomizer { - - /** - * Customize the {@link CuratorFrameworkFactory.Builder}. - * @param builder instance of the builder that you can further customize. - */ - void customize(CuratorFrameworkFactory.Builder builder); - -} diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfiguration.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfiguration.java deleted file mode 100644 index 606cd5121..000000000 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfiguration.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.RetryPolicy; -import org.apache.curator.drivers.TracerDriver; -import org.apache.curator.ensemble.EnsembleProvider; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.x.discovery.UriSpec; -import org.apache.zookeeper.ClientCnxnSocketNIO; - -import org.springframework.aot.hint.MemberCategory; -import org.springframework.aot.hint.RuntimeHints; -import org.springframework.aot.hint.RuntimeHintsRegistrar; -import org.springframework.aot.hint.TypeReference; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.ClassUtils; - -/** - * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration - * Auto-configuration} that sets up Zookeeper discovery. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnZookeeperEnabled -@EnableConfigurationProperties -public class ZookeeperAutoConfiguration { - - private static final Log log = LogFactory.getLog(ZookeeperAutoConfiguration.class); - - @Bean - @ConditionalOnMissingBean - public ZookeeperProperties zookeeperProperties() { - return new ZookeeperProperties(); - } - - @Bean(destroyMethod = "close") - @ConditionalOnMissingBean - public CuratorFramework curatorFramework(ZookeeperProperties properties, RetryPolicy retryPolicy, - ObjectProvider optionalCuratorFrameworkCustomizerProvider, - ObjectProvider optionalEnsembleProvider, - ObjectProvider optionalTracerDriverProvider) throws Exception { - return CuratorFactory.curatorFramework(properties, retryPolicy, - optionalCuratorFrameworkCustomizerProvider::orderedStream, optionalEnsembleProvider::getIfAvailable, - optionalTracerDriverProvider::getIfAvailable); - } - - @Bean - @ConditionalOnMissingBean - public RetryPolicy exponentialBackoffRetry(ZookeeperProperties properties) { - return CuratorFactory.retryPolicy(properties); - } - -} - -// TODO: remove after GraalVM metadata PR merged -class ZookeeperCoreHints implements RuntimeHintsRegistrar { - - @Override - public void registerHints(RuntimeHints hints, ClassLoader classLoader) { - if (!ClassUtils.isPresent("org.apache.zookeeper.ZooKeeper", classLoader)) { - return; - } - hints.reflection().registerType(TypeReference.of(ClientCnxnSocketNIO.class), - hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)); - hints.reflection() - .registerType(TypeReference.of("org.apache.curator.x.discovery.details.OldServiceInstance"), - hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS, - MemberCategory.INVOKE_DECLARED_METHODS)); - hints.reflection() - .registerType(TypeReference.of("org.apache.curator.x.discovery.UriSpec"), - hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS, - MemberCategory.INVOKE_DECLARED_METHODS)); - hints.reflection().registerType(TypeReference.of(UriSpec.Part.class), - hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS, - MemberCategory.INVOKE_DECLARED_METHODS)); - hints.reflection() - .registerType(TypeReference.of("org.apache.curator.x.discovery.ServiceInstance"), - hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS, - MemberCategory.INVOKE_DECLARED_METHODS)); - } -} diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfiguration.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfiguration.java deleted file mode 100644 index bdc430b54..000000000 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfiguration.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Auto {@link Configuration} for adding a Zookeeper health endpoint to actuator if - * required. - * - * @author Tom Gianos - * @since 2.0.1 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnZookeeperEnabled -@ConditionalOnClass(Endpoint.class) -@AutoConfigureAfter({ ZookeeperAutoConfiguration.class }) -public class ZookeeperHealthAutoConfiguration { - - /** - * If there is an active curator, if the zookeeper health endpoint is enabled and if a - * health indicator hasn't already been added by a user add one. - * @param curator The curator connection to zookeeper to use - * @return An instance of {@link ZookeeperHealthIndicator} to add to actuator health - * report - */ - @Bean - @ConditionalOnMissingBean(ZookeeperHealthIndicator.class) - @ConditionalOnBean(CuratorFramework.class) - @ConditionalOnEnabledHealthIndicator("zookeeper") - public ZookeeperHealthIndicator zookeeperHealthIndicator(CuratorFramework curator) { - return new ZookeeperHealthIndicator(curator); - } - -} diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthIndicator.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthIndicator.java deleted file mode 100644 index ff0aee227..000000000 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthIndicator.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.imps.CuratorFrameworkState; - -import org.springframework.boot.actuate.health.AbstractHealthIndicator; -import org.springframework.boot.actuate.health.Health; - -/** - * A {@link org.springframework.boot.actuate.health.HealthIndicator} that checks the - * status of the Zookeeper connection. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class ZookeeperHealthIndicator extends AbstractHealthIndicator { - - private final CuratorFramework curator; - - public ZookeeperHealthIndicator(CuratorFramework curator) { - this.curator = curator; - } - - @Override - protected void doHealthCheck(Health.Builder builder) throws Exception { - try { - CuratorFrameworkState state = this.curator.getState(); - if (state != CuratorFrameworkState.STARTED) { - builder.down().withDetail("error", "Client not started"); - } - else if (this.curator.checkExists().forPath("/") == null) { - builder.down().withDetail("error", "Root for namespace does not exist"); - } - else { - builder.up(); - } - builder.withDetail("connectionString", - this.curator.getZookeeperClient().getCurrentConnectionString()) - .withDetail("state", state); - } - catch (Exception e) { - builder.down(e); - } - } - -} diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperProperties.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperProperties.java deleted file mode 100644 index 9c13338cb..000000000 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperProperties.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.concurrent.TimeUnit; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.convert.DurationUnit; -import org.springframework.util.Assert; - -/** - * Properties related to connecting to Zookeeper. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -@ConfigurationProperties(ZookeeperProperties.PREFIX) -public class ZookeeperProperties { - - /** - * Configuration prefix. - */ - public static final String PREFIX = "spring.cloud.zookeeper"; - /** - * Connection string to the Zookeeper cluster. - */ - private String connectString = "localhost:2181"; - - /** - * Is Zookeeper enabled. - */ - private boolean enabled = true; - - /** - * Initial amount of time to wait between retries. - */ - private Integer baseSleepTimeMs = 50; - - /** - * Max number of times to retry. - */ - private Integer maxRetries = 10; - - /** - * Max time in ms to sleep on each retry. - */ - private Integer maxSleepMs = 500; - - /** - * Wait time to block on connection to Zookeeper. - */ - private Integer blockUntilConnectedWait = 10; - - /** - * The unit of time related to blocking on connection to Zookeeper. - */ - private TimeUnit blockUntilConnectedUnit = TimeUnit.SECONDS; - - /** - * The configured/negotiated session timeout in milliseconds. Please refer to - * Curator's Tech - * Note 14 to understand how Curator implements connection sessions. - * - * @see Curator's - * Tech Note 14 - */ - @DurationUnit(ChronoUnit.MILLIS) - private Duration sessionTimeout = Duration.of(60 * 1000, ChronoUnit.MILLIS); - - /** - * The configured connection timeout in milliseconds. - */ - @DurationUnit(ChronoUnit.MILLIS) - private Duration connectionTimeout = Duration.of(15 * 1000, ChronoUnit.MILLIS); - - public String getConnectString() { - return this.connectString; - } - - public boolean isEnabled() { - return this.enabled; - } - - public Integer getBaseSleepTimeMs() { - return this.baseSleepTimeMs; - } - - public Integer getMaxRetries() { - return this.maxRetries; - } - - public Integer getMaxSleepMs() { - return this.maxSleepMs; - } - - public Integer getBlockUntilConnectedWait() { - return this.blockUntilConnectedWait; - } - - public TimeUnit getBlockUntilConnectedUnit() { - return this.blockUntilConnectedUnit; - } - - public void setConnectString(String connectString) { - Assert.hasText(connectString, "spring.cloud.zookeeper.connect-string may not be empty"); - this.connectString = connectString; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public void setBaseSleepTimeMs(Integer baseSleepTimeMs) { - this.baseSleepTimeMs = baseSleepTimeMs; - } - - public void setMaxRetries(Integer maxRetries) { - this.maxRetries = maxRetries; - } - - public void setMaxSleepMs(Integer maxSleepMs) { - this.maxSleepMs = maxSleepMs; - } - - public void setBlockUntilConnectedWait(Integer blockUntilConnectedWait) { - this.blockUntilConnectedWait = blockUntilConnectedWait; - } - - public void setBlockUntilConnectedUnit(TimeUnit blockUntilConnectedUnit) { - this.blockUntilConnectedUnit = blockUntilConnectedUnit; - } - - public Duration getSessionTimeout() { - return sessionTimeout; - } - - public void setSessionTimeout(Duration sessionTimeout) { - this.sessionTimeout = sessionTimeout; - } - - public Duration getConnectionTimeout() { - return connectionTimeout; - } - - public void setConnectionTimeout(Duration connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - -} diff --git a/spring-cloud-zookeeper-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-zookeeper-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json deleted file mode 100644 index 02211578e..000000000 --- a/spring-cloud-zookeeper-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ /dev/null @@ -1,15 +0,0 @@ -{"properties": [ - { - "name": "management.health.zookeeper.enabled", - "type": "java.lang.Boolean", - "description": "Enable the health endpoint for zookeeper.", - "defaultValue": true - }, - { - "name": "endpoints.zookeeper.enabled", - "type": "java.lang.Boolean", - "description": "Enable the /zookeeper endpoint to inspect the state of zookeeper.", - "defaultValue": true - } -]} - diff --git a/spring-cloud-zookeeper-core/src/main/resources/META-INF/spring/aot.factories b/spring-cloud-zookeeper-core/src/main/resources/META-INF/spring/aot.factories deleted file mode 100644 index c2fe4ff25..000000000 --- a/spring-cloud-zookeeper-core/src/main/resources/META-INF/spring/aot.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.aot.hint.RuntimeHintsRegistrar=\ -org.springframework.cloud.zookeeper.ZookeeperCoreHints \ No newline at end of file diff --git a/spring-cloud-zookeeper-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/spring-cloud-zookeeper-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports deleted file mode 100644 index 925e9e0c9..000000000 --- a/spring-cloud-zookeeper-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration -org.springframework.cloud.zookeeper.ZookeeperHealthAutoConfiguration diff --git a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/CuratorFactoryTests.java b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/CuratorFactoryTests.java deleted file mode 100644 index e73059e36..000000000 --- a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/CuratorFactoryTests.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import org.junit.jupiter.api.Test; - -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.web.util.UriComponentsBuilder; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CuratorFactoryTests { - - @Test - public void testLoadProperties() { - ZookeeperProperties properties = CuratorFactory.loadProperties( - Binder.get(new MockEnvironment()), - UriComponentsBuilder.fromUriString("zookeeper://myhost:8502").build()); - assertThat(properties.getConnectString()).isEqualTo("myhost:8502"); - } - -} diff --git a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationTests.java b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationTests.java deleted file mode 100644 index b11de7e07..000000000 --- a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationTests.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.curator.drivers.TracerDriver; -import org.apache.curator.ensemble.EnsembleProvider; -import org.apache.curator.ensemble.fixed.FixedEnsembleProvider; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.test.TestingServer; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Bean; -import org.springframework.core.annotation.Order; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -/** - * @author Marcin Grzejszczak - */ - -@RunWith(Enclosed.class) -public class ZookeeperAutoConfigurationTests { - - @RunWith(SpringRunner.class) - @ContextConfiguration(loader = ZookeeperTestingServer.Loader.class, - classes = { BaseTestConfig.class, ZookeeperAutoConfiguration.class }) - public static class BaseTests { - - @Autowired(required = false) - CuratorFramework curator; - - @Test - public void should_successfully_inject_Curator_as_a_Spring_bean() { - assertThat(this.curator).isNotNull(); - } - - } - - static class BaseTestConfig { - - @Bean - ZookeeperProperties zookeeperProperties(TestingServer testingServer) { - ZookeeperProperties properties = new ZookeeperProperties(); - properties.setConnectString(testingServer.getConnectString()); - return properties; - } - - @Bean(destroyMethod = "close") - TestingServer testingServer() throws Exception { - return new TestingServer(); - } - - } - - @RunWith(SpringRunner.class) - @ContextConfiguration(loader = ZookeeperTestingServer.Loader.class, - classes = { EnsembleTestConfig.class, ZookeeperAutoConfiguration.class }) - public static class EnsembleTests { - - @Autowired(required = false) - CuratorFramework curator; - - @Autowired - TestingServer testingServer; - - @Test - public void should_successfully_inject_Curator_with_ensemble_connection_string() { - assertThat(curator.getZookeeperClient().getCurrentConnectionString()) - .isEqualTo(testingServer.getConnectString()); - assertThat(curator.getZookeeperClient().getCurrentConnectionString()) - .isNotEqualTo(EnsembleTestConfig.DUMMY_CONNECTION_STRING); - } - - } - - static class EnsembleTestConfig { - - static final String DUMMY_CONNECTION_STRING = "dummy-connection-string:2111"; - - @Bean - EnsembleProvider ensembleProvider(TestingServer testingServer) { - return new FixedEnsembleProvider(testingServer.getConnectString()); - } - - @Bean - ZookeeperProperties zookeeperProperties() { - ZookeeperProperties properties = new ZookeeperProperties(); - properties.setConnectString(DUMMY_CONNECTION_STRING); - return properties; - } - - @Bean(destroyMethod = "close") - TestingServer testingServer() throws Exception { - return new TestingServer(); - } - - } - - @RunWith(SpringRunner.class) - @ContextConfiguration(loader = ZookeeperTestingServer.Loader.class, - classes = { BaseTestConfig.class, - ZookeeperAutoConfiguration.class, CuratorFrameworkCustomizerConfig.class }) - @DirtiesContext - public static class CuratorFrameworkCustomizerTest { - - @Autowired - @Qualifier("customizerCallOrder") - List callOrder; - - @Test - public void should_invoke_the_CuratorFrameworkCustomizer_in_order() { - assertThat(callOrder).containsExactly(1, 2); - } - - } - - static class CuratorFrameworkCustomizerConfig { - - @Bean("customizerCallOrder") - public List curatorFrameworkCustomizerCallOrder() { - return new ArrayList<>(2); - } - - @Bean - @Order(1) - public CuratorFrameworkCustomizer customizer1( - @Qualifier("customizerCallOrder") List callOrder) { - return (builder) -> callOrder.add(1); - } - - @Bean - @Order(2) - public CuratorFrameworkCustomizer customizer2( - @Qualifier("customizerCallOrder") List callOrder) { - return (builder) -> callOrder.add(2); - } - - } - - @RunWith(SpringRunner.class) - @ContextConfiguration(loader = ZookeeperTestingServer.Loader.class, - classes = { BaseTestConfig.class, TracerDriverTestConfig.class, - ZookeeperAutoConfiguration.class }) - public static class TracerDriverTests { - - @Autowired(required = false) - TracerDriver tracerDriver; - - @Autowired(required = false) - CuratorFramework curator; - - @Autowired - TestingServer testingServer; - - @Test - public void should_successfully_inject_Curators_TracerDriver() { - assertThat(curator.getZookeeperClient().getTracerDriver()) - .isEqualTo(tracerDriver); - } - - } - - static class TracerDriverTestConfig { - - @Bean - TracerDriver mockedTracerDriver() { - return mock(TracerDriver.class); - } - - } - -} diff --git a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfigurationTests.java b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfigurationTests.java deleted file mode 100644 index 059c1ffb6..000000000 --- a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfigurationTests.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper; - -import org.apache.curator.framework.CuratorFramework; -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Bean; - -/** - * Tests for {@link ZookeeperHealthAutoConfiguration}. - * - * @author Tom Gianos - * @since 2.0.1 - */ -public class ZookeeperHealthAutoConfigurationTests { - - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withInitializer(new ZookeeperTestingServer.Initializer()) - .withConfiguration(AutoConfigurations.of(ZookeeperAutoConfiguration.class, - ZookeeperHealthAutoConfiguration.class)) - .withUserConfiguration(ZookeeperAutoConfigurationTests.BaseTestConfig.class); - - @Test - public void testDefaultPropertiesCreateZookeeperHealthIndicator() { - this.contextRunner.run((context) -> Assertions.assertThat(context) - .hasSingleBean(ZookeeperHealthIndicator.class)); - } - - @Test - public void testZookeeperHealthIndicatorDisabled() { - this.contextRunner.withPropertyValues("management.health.zookeeper.enabled=false") - .run((context) -> Assertions.assertThat(context) - .doesNotHaveBean(ZookeeperHealthIndicator.class)); - } - - @Test - public void testZookeeperHealthIndicatorAlreadyAdded() { - this.contextRunner.withUserConfiguration(HealthIndicatorCustomConfig.class) - .run((context) -> { - Assertions.assertThat(context) - .hasSingleBean(ZookeeperHealthIndicator.class); - Assertions.assertThat(context) - .doesNotHaveBean("zookeeperHealthIndicator"); - Assertions.assertThat(context) - .hasBean("customZookeeperHealthIndicator"); - }); - } - - static class HealthIndicatorCustomConfig { - - @Bean - ZookeeperHealthIndicator customZookeeperHealthIndicator( - CuratorFramework curatorFramework) { - return new ZookeeperHealthIndicator(curatorFramework); - } - - } - -} diff --git a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/test/ZookeeperTestingServer.java b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/test/ZookeeperTestingServer.java deleted file mode 100644 index 7fea6f610..000000000 --- a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/test/ZookeeperTestingServer.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.test; - -import java.io.IOException; -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.test.TestingServer; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.boot.context.event.ApplicationPreparedEvent; -import org.springframework.boot.test.context.SpringBootContextLoader; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.event.ContextClosedEvent; -import org.springframework.context.event.SmartApplicationListener; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.util.Assert; -import org.springframework.util.ReflectionUtils; - -public class ZookeeperTestingServer implements SmartApplicationListener, Ordered { - - private final Log log = LogFactory.getLog(getClass()); - - private AtomicBoolean started = new AtomicBoolean(); - - private TestingServer testingServer; - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } - - public int getPort() { - Assert.notNull(testingServer, "testingServer not started"); - return testingServer.getPort(); - } - - @Override - public boolean supportsEventType(Class eventType) { - return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType) - || ApplicationPreparedEvent.class.isAssignableFrom(eventType); - } - - @Override - public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof ApplicationEnvironmentPreparedEvent) { - envPrepared(((ApplicationEnvironmentPreparedEvent) event).getEnvironment()); - } - else if (event instanceof ApplicationPreparedEvent) { - appPrepared(((ApplicationPreparedEvent) event).getApplicationContext()); - } - } - - public void envPrepared(ConfigurableEnvironment environment) { - MutablePropertySources sources = environment.getPropertySources(); - - start(); - - if (!sources.contains("zookeeperTestingServer")) { - HashMap map = new HashMap<>(); - map.put(ZookeeperProperties.PREFIX + ".connect-string", "localhost:" + testingServer.getPort()); - - sources.addFirst(new MapPropertySource("zookeeperTestingServer", map)); - } - - } - - public void start() { - if (started.compareAndSet(false, true)) { - try { - testingServer = new TestingServer(); - } - catch (Exception e) { - ReflectionUtils.rethrowRuntimeException(e); - } - log.debug("Starting TestingServer on port " + testingServer.getPort()); - } - } - - public void appPrepared(ConfigurableApplicationContext context) { - context.addApplicationListener(new CloseListener(this)); - } - - public void close() { - try { - if (started.compareAndSet(true, false)) { - log.debug("Closing TestingServer on port " + testingServer.getPort()); - testingServer.close(); - } - } - catch (IOException ex) { - ReflectionUtils.rethrowRuntimeException(ex); - } - } - - static class CloseListener implements ApplicationListener, Ordered { - - private final ZookeeperTestingServer testingServer; - - CloseListener(ZookeeperTestingServer testingServer) { - this.testingServer = testingServer; - } - - @Override - public void onApplicationEvent(ContextClosedEvent event) { - testingServer.close(); - } - - @Override - public int getOrder() { - return Ordered.LOWEST_PRECEDENCE; - } - } - - public static class Loader extends SpringBootContextLoader { - - @Override - protected SpringApplication getSpringApplication() { - SpringApplication application = super.getSpringApplication(); - ZookeeperTestingServer testingServer = new ZookeeperTestingServer(); - application.addListeners(testingServer); - application.addListeners(new CloseListener(testingServer)); - return application; - } - - } - - public static class Initializer implements ApplicationContextInitializer { - - @Override - public void initialize(ConfigurableApplicationContext context) { - ZookeeperTestingServer testingServer = new ZookeeperTestingServer(); - testingServer.envPrepared(context.getEnvironment()); - testingServer.appPrepared(context); - } - - } - -} diff --git a/spring-cloud-zookeeper-dependencies/pom.xml b/spring-cloud-zookeeper-dependencies/pom.xml deleted file mode 100644 index 6548de780..000000000 --- a/spring-cloud-zookeeper-dependencies/pom.xml +++ /dev/null @@ -1,198 +0,0 @@ - - - 4.0.0 - - spring-cloud-dependencies-parent - org.springframework.cloud - 4.1.0-SNAPSHOT - - - spring-cloud-zookeeper-dependencies - 4.1.0-SNAPSHOT - pom - spring-cloud-zookeeper-dependencies - Spring Cloud Zookeeper Dependencies - - 5.1.0 - true - true - true - - - - - org.springframework.cloud - spring-cloud-zookeeper-core - ${project.version} - - - org.springframework.cloud - spring-cloud-zookeeper-config - ${project.version} - - - org.springframework.cloud - spring-cloud-zookeeper-discovery - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-zookeeper - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-zookeeper-all - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-zookeeper-config - ${project.version} - - - org.springframework.cloud - spring-cloud-starter-zookeeper-discovery - ${project.version} - - - org.apache.curator - curator-framework - ${curator.version} - - - log4j - log4j - - - io.netty - netty - - - - - org.apache.curator - curator-recipes - ${curator.version} - - - log4j - log4j - - - io.netty - netty - - - - - org.apache.curator - curator-x-discovery - ${curator.version} - - - log4j - log4j - - - io.netty - netty - - - - - org.apache.curator - curator-test - ${curator.version} - test - - - log4j - log4j - - - io.netty - netty - - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - io.spring.javaformat - spring-javaformat-maven-plugin - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - - - - spring - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - false - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - spring-releases - Spring Releases - https://repo.spring.io/release - - false - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - false - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - diff --git a/spring-cloud-zookeeper-discovery/.flattened-pom.xml b/spring-cloud-zookeeper-discovery/.flattened-pom.xml new file mode 100644 index 000000000..5ebc4be68 --- /dev/null +++ b/spring-cloud-zookeeper-discovery/.flattened-pom.xml @@ -0,0 +1,208 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + .. + + org.springframework.cloud + spring-cloud-zookeeper-discovery + 4.1.0-SNAPSHOT + Spring Cloud Zookeeper Discovery + Spring Cloud Zookeeper Discovery + https://spring.io/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-discovery + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-discovery + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-discovery + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-discovery + + + + org.springframework.cloud + spring-cloud-zookeeper-core + 4.1.0-SNAPSHOT + compile + + + org.springframework.cloud + spring-cloud-commons + 4.1.0-SNAPSHOT + compile + true + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + 4.1.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-starter + 3.2.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-configuration-processor + 3.2.0-SNAPSHOT + compile + true + + + org.springframework + spring-web + 6.1.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-starter-actuator + 3.2.0-SNAPSHOT + compile + true + + + org.springframework.boot + spring-boot-starter-webflux + 3.2.0-SNAPSHOT + compile + true + + + org.apache.curator + curator-x-discovery + 5.1.0 + compile + + + log4j + log4j + + + io.netty + netty + + + true + + + org.springframework.cloud + spring-cloud-starter-openfeign + 4.1.0-SNAPSHOT + compile + true + + + io.github.openfeign + feign-core + 12.4 + compile + true + + + org.springframework.boot + spring-boot-autoconfigure-processor + 3.2.0-SNAPSHOT + compile + true + + + org.springframework.cloud + spring-cloud-config-client + 4.1.0-SNAPSHOT + compile + true + + + org.springframework.cloud + spring-cloud-config-server + 4.1.0-SNAPSHOT + compile + true + + + diff --git a/spring-cloud-zookeeper-discovery/pom.xml b/spring-cloud-zookeeper-discovery/pom.xml deleted file mode 100644 index f2c01a53b..000000000 --- a/spring-cloud-zookeeper-discovery/pom.xml +++ /dev/null @@ -1,181 +0,0 @@ - - - 4.0.0 - - spring-cloud-zookeeper-discovery - jar - Spring Cloud Zookeeper Discovery - Spring Cloud Zookeeper Discovery - - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - .. - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - maven-surefire-plugin - - - - - - - org.springframework.cloud - spring-cloud-zookeeper-core - - - org.springframework.cloud - spring-cloud-commons - true - - - org.springframework.cloud - spring-cloud-starter-loadbalancer - true - - - org.springframework.boot - spring-boot-starter - true - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework - spring-web - true - - - org.springframework.boot - spring-boot-starter-actuator - true - - - org.springframework.boot - spring-boot-starter-webflux - true - - - org.apache.curator - curator-x-discovery - true - - - org.springframework.cloud - spring-cloud-starter-openfeign - true - - - io.github.openfeign - feign-core - true - - - org.springframework.boot - spring-boot-autoconfigure-processor - true - - - org.springframework.cloud - spring-cloud-config-client - true - - - org.springframework.cloud - spring-cloud-config-server - true - - - org.springframework.boot - spring-boot-starter-web - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - test - - - org.springframework.cloud - spring-cloud-test-support - test - - - org.springframework.cloud - spring-cloud-zookeeper-core - ${project.version} - test-jar - test - - - org.apache.curator - curator-test - test - - - com.github.tomakehurst - wiremock - test - 2.27.1 - - - org.assertj - assertj-core - test - - - com.jayway.awaitility - awaitility - test - - - com.toomuchcoding.jsonassert - jsonassert - test - - - io.projectreactor - reactor-test - test - - - org.testcontainers - testcontainers - test - - - org.testcontainers - junit-jupiter - test - - - org.testcontainers - mockserver - test - - - org.mock-server - mockserver-client-java - test - - - - diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnLoadBalancerForZookeeperEnabled.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnLoadBalancerForZookeeperEnabled.java deleted file mode 100644 index c9a65ad76..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnLoadBalancerForZookeeperEnabled.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - -/** - * Wrapper annotation to enable Spring Cloud LoadBalancer for Zookeeper. - * - * @author Olga Maciaszek-Sharma - * @since 3.0.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) -@ConditionalOnProperty(value = "spring.cloud.zookeeper.loadbalancer.enabled", matchIfMissing = true) -public @interface ConditionalOnLoadBalancerForZookeeperEnabled { -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnZookeeperDiscoveryEnabled.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnZookeeperDiscoveryEnabled.java deleted file mode 100644 index 0466c678f..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnZookeeperDiscoveryEnabled.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; - -/** - * Wrapper annotation to enable Zookeeper Discovery. - * - * @author Marcin Grzejszczak - * @since 1.1.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE, ElementType.METHOD }) -@ConditionalOnZookeeperEnabled -@ConditionalOnProperty(value = ConditionalOnZookeeperDiscoveryEnabled.PROPERTY, matchIfMissing = true) -public @interface ConditionalOnZookeeperDiscoveryEnabled { - /** - * Property name. - */ - String PROPERTY = "spring.cloud.zookeeper.discovery.enabled"; -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/DependencyPathUtils.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/DependencyPathUtils.java deleted file mode 100644 index 2d2e74df6..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/DependencyPathUtils.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -/** - * Utils for correct dependency path format. - * - * @author Denis Stepanov - * @since 1.0.4 - */ -public final class DependencyPathUtils { - - private DependencyPathUtils() { - } - - /** - * Sanitizes path by ensuring that path starts with a slash and doesn't have one at - * the end. - * @param path file path to sanitize. - * @return sanitized path. - */ - public static String sanitize(String path) { - return withLeadingSlash(withoutSlashAtEnd(path)); - } - - private static String withLeadingSlash(String value) { - return value.startsWith("/") ? value : "/" + value; - } - - private static String withoutSlashAtEnd(String value) { - return value.endsWith("/") ? value.substring(0, value.length() - 1) : value; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/LoadBalancerZookeeperAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/LoadBalancerZookeeperAutoConfiguration.java deleted file mode 100644 index db066349e..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/LoadBalancerZookeeperAutoConfiguration.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer; -import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients; -import org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration; -import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependenciesAutoConfiguration; -import org.springframework.context.annotation.Configuration; - -/** - * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration - * Auto-configuration} that sets up Spring Cloud LoadBalancer for Zookeeper. - * - * @author Olga Maciaszek-Sharma - * @since 3.0.0 - */ -@Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties -@ConditionalOnZookeeperEnabled -@ConditionalOnBean(ReactiveLoadBalancer.Factory.class) -@ConditionalOnLoadBalancerForZookeeperEnabled -@AutoConfigureAfter({LoadBalancerAutoConfiguration.class, ZookeeperDependenciesAutoConfiguration.class}) -@LoadBalancerClients(defaultConfiguration = ZookeeperLoadBalancerConfiguration.class) -public class LoadBalancerZookeeperAutoConfiguration { -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoConfiguration.java deleted file mode 100644 index f59eb5f3a..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoConfiguration.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.x.discovery.ServiceDiscovery; - -import org.springframework.aot.hint.MemberCategory; -import org.springframework.aot.hint.RuntimeHints; -import org.springframework.aot.hint.RuntimeHintsRegistrar; -import org.springframework.aot.hint.TypeReference; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.client.CommonsClientAutoConfiguration; -import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.ClassUtils; - -/** - * @author Spencer Gibb - * @author Tim Ysewyn - * @since 1.1.0 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnDiscoveryEnabled -@ConditionalOnZookeeperDiscoveryEnabled -@AutoConfigureBefore({CommonsClientAutoConfiguration.class}) -public class ZookeeperDiscoveryAutoConfiguration { - - @Autowired - private CuratorFramework curator; - - @Bean - @ConditionalOnMissingBean - public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties( - InetUtils inetUtils) { - return new ZookeeperDiscoveryProperties(inetUtils); - } - - @Bean - public ZookeeperServiceWatch zookeeperServiceWatch( - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - return new ZookeeperServiceWatch(curator, zookeeperDiscoveryProperties); - } - - @Configuration(proxyBeanMethods = false) - @ConditionalOnClass({ Endpoint.class, HealthIndicator.class }) - protected static class ZookeeperDiscoveryHealthConfig { - - @Autowired(required = false) - private ZookeeperDependencies zookeeperDependencies; - - @Bean - @ConditionalOnMissingBean - @ConditionalOnEnabledHealthIndicator("zookeeper") - public ZookeeperDiscoveryHealthIndicator zookeeperDiscoveryHealthIndicator( - CuratorFramework curatorFramework, - ServiceDiscovery serviceDiscovery, - ZookeeperDiscoveryProperties properties) { - return new ZookeeperDiscoveryHealthIndicator(curatorFramework, - serviceDiscovery, zookeeperDependencies, properties); - } - - } - -} - -class ZookeeperDiscoveryHints implements RuntimeHintsRegistrar { - - @Override - public void registerHints(RuntimeHints hints, ClassLoader classLoader) { - if (!ClassUtils.isPresent("org.apache.zookeeper.ZooKeeper", classLoader)) { - return; - } - hints.reflection() - .registerType(TypeReference.of(ZookeeperInstance.class), - hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS, - MemberCategory.INVOKE_DECLARED_METHODS)); - hints.reflection().registerType(TypeReference.of(ZookeeperServiceInstance.class), - hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS, - MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)); - } -} - diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClient.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClient.java deleted file mode 100644 index 9779d26fe..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClient.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.zookeeper.KeeperException; - -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; - -import static org.springframework.util.ReflectionUtils.rethrowRuntimeException; - -/** - * Zookeeper version of {@link DiscoveryClient}. Capable of resolving aliases from - * {@link ZookeeperDependencies} to service names in Zookeeper. - * - * @author Spencer Gibb - * @author Marcin Grzejszczak - * @author Olga Maciaszek-Sharma - * @since 1.0.0 - */ -public class ZookeeperDiscoveryClient implements DiscoveryClient { - - private static final Log log = LogFactory.getLog(ZookeeperDiscoveryClient.class); - - private final ZookeeperDependencies zookeeperDependencies; - - private final ServiceDiscovery serviceDiscovery; - - private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; - - public ZookeeperDiscoveryClient(ServiceDiscovery serviceDiscovery, - ZookeeperDependencies zookeeperDependencies, - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - this.serviceDiscovery = serviceDiscovery; - this.zookeeperDependencies = zookeeperDependencies; - this.zookeeperDiscoveryProperties = zookeeperDiscoveryProperties; - } - - @Override - public String description() { - return "Spring Cloud Zookeeper Discovery Client"; - } - - private static org.springframework.cloud.client.ServiceInstance createServiceInstance( - String serviceId, ServiceInstance serviceInstance) { - return new ZookeeperServiceInstance(serviceId, serviceInstance); - } - - @Override - public List getInstances( - final String serviceId) { - try { - if (getServiceDiscovery() == null) { - return Collections.EMPTY_LIST; - } - String serviceIdToQuery = getServiceIdToQuery(serviceId); - Collection> zkInstances = getServiceDiscovery() - .queryForInstances(serviceIdToQuery); - List instances = new ArrayList<>(); - for (ServiceInstance instance : zkInstances) { - instances.add(createServiceInstance(serviceIdToQuery, instance)); - } - return instances; - } - catch (KeeperException.NoNodeException e) { - if (log.isDebugEnabled()) { - log.debug( - "Error getting instances from zookeeper. Possibly, no service has registered.", - e); - } - // this means that nothing has registered as a service yes - return Collections.emptyList(); - } - catch (Exception exception) { - rethrowRuntimeException(exception); - } - return new ArrayList<>(); - } - - private ServiceDiscovery getServiceDiscovery() { - return this.serviceDiscovery; - } - - private String getServiceIdToQuery(String serviceId) { - if (this.zookeeperDependencies != null - && this.zookeeperDependencies.hasDependencies()) { - String pathForAlias = this.zookeeperDependencies.getPathForAlias(serviceId); - return pathForAlias.isEmpty() ? serviceId : pathForAlias; - } - return serviceId; - } - - @Override - public List getServices() { - List services = null; - if (getServiceDiscovery() == null) { - log.warn( - "Service Discovery is not yet ready - returning empty list of services"); - return Collections.emptyList(); - } - try { - Collection names = getServiceDiscovery().queryForNames(); - if (names == null) { - return Collections.emptyList(); - } - services = new ArrayList<>(names); - } - catch (KeeperException.NoNodeException e) { - if (log.isDebugEnabled()) { - log.debug( - "Error getting services from zookeeper. Possibly, no service has registered.", - e); - } - // this means that nothing has registered as a service yes - return Collections.emptyList(); - } - catch (Exception e) { - rethrowRuntimeException(e); - } - return services; - } - - @Override - public int getOrder() { - return this.zookeeperDiscoveryProperties.getOrder(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientConfiguration.java deleted file mode 100644 index d9b4bf285..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientConfiguration.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import org.apache.curator.x.discovery.ServiceDiscovery; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; -import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * {@link org.springframework.cloud.client.discovery.DiscoveryClient} configuration for - * Zookeeper. - * - * @author Spencer Gibb - * @author Tim Ysewyn - * @since 1.0.0 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnDiscoveryEnabled -@ConditionalOnBlockingDiscoveryEnabled -@ConditionalOnZookeeperDiscoveryEnabled -@AutoConfigureBefore({ ZookeeperDiscoveryAutoConfiguration.class }) -public class ZookeeperDiscoveryClientConfiguration { - - @Autowired(required = false) - private ZookeeperDependencies zookeeperDependencies; - - @Bean - @ConditionalOnMissingBean - // currently means auto-registration is false. That will change when - // ZookeeperServiceDiscovery is gone - public ZookeeperDiscoveryClient zookeeperDiscoveryClient( - ServiceDiscovery serviceDiscovery, - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - return new ZookeeperDiscoveryClient(serviceDiscovery, zookeeperDependencies, - zookeeperDiscoveryProperties); - } - - @Bean - public Marker zookeeperDiscoveryClientMarker() { - return new Marker(); - } - - class Marker { - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicator.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicator.java deleted file mode 100644 index 19a74038a..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicator.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceInstance; - -import org.springframework.boot.actuate.health.Health; -import org.springframework.cloud.client.discovery.health.DiscoveryHealthIndicator; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; - -/** - * {@link org.springframework.boot.actuate.health.HealthIndicator} that presents the - * status of all instances registered in Zookeeper. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class ZookeeperDiscoveryHealthIndicator implements DiscoveryHealthIndicator { - - private static final Log log = LogFactory - .getLog(ZookeeperDiscoveryHealthIndicator.class); - - private CuratorFramework curatorFramework; - - private ServiceDiscovery serviceDiscovery; - - private final ZookeeperDependencies zookeeperDependencies; - - private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; - - public ZookeeperDiscoveryHealthIndicator(CuratorFramework curatorFramework, - ServiceDiscovery serviceDiscovery, - ZookeeperDependencies zookeeperDependencies, - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - this.curatorFramework = curatorFramework; - this.serviceDiscovery = serviceDiscovery; - this.zookeeperDependencies = zookeeperDependencies; - this.zookeeperDiscoveryProperties = zookeeperDiscoveryProperties; - } - - @Override - public String getName() { - return "zookeeper"; - } - - @Override - public Health health() { - Health.Builder builder = Health.unknown(); - try { - Iterable> allInstances = new ZookeeperServiceInstances( - this.curatorFramework, this.serviceDiscovery, - this.zookeeperDependencies, this.zookeeperDiscoveryProperties); - builder.up().withDetail("services", allInstances); - } - catch (Exception e) { - log.error("Error", e); - builder.down(e); - } - - return builder.build(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryProperties.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryProperties.java deleted file mode 100644 index 22cbf614b..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryProperties.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.zookeeper.support.StatusConstants; -import org.springframework.util.StringUtils; - -/** - * Properties related to Zookeeper's Service Discovery. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -@ConfigurationProperties(ZookeeperDiscoveryProperties.PREFIX) -public class ZookeeperDiscoveryProperties { - - /** - * Zookeeper Discovery Properties prefix. - */ - public static final String PREFIX = "spring.cloud.zookeeper.discovery"; - - /** - * Default URI spec. - */ - public static final String DEFAULT_URI_SPEC = "{scheme}://{address}:{port}"; - - private InetUtils.HostInfo hostInfo; - - private boolean enabled = true; - - /** - * Root Zookeeper folder in which all instances are registered. - */ - private String root = "/services"; - - /** - * The URI specification to resolve during service registration in Zookeeper. - */ - private String uriSpec = DEFAULT_URI_SPEC; - - /** Id used to register with zookeeper. Defaults to a random UUID. */ - private String instanceId; - - /** - * Predefined host with which a service can register itself in Zookeeper. Corresponds - * to the {code address} from the URI spec. - */ - private String instanceHost; - - /** - * IP address to use when accessing service (must also set preferIpAddress to use). - */ - private String instanceIpAddress; - - /** - * Use ip address rather than hostname during registration. - */ - private boolean preferIpAddress = false; - - /** Port to register the service under (defaults to listening port). */ - private Integer instancePort; - - /** Ssl port of the registered service. */ - private Integer instanceSslPort; - - /** - * Register as a service in zookeeper. - */ - private boolean register = true; - - /** - * Gets the metadata name/value pairs associated with this instance. This information - * is sent to zookeeper and can be used by other instances. - */ - private Map metadata = new HashMap<>(); - - /** - * The initial status of this instance (defaults to - * {@link StatusConstants#STATUS_UP}). - */ - private String initialStatus = StatusConstants.STATUS_UP; - - /** - * Order of the discovery client used by `CompositeDiscoveryClient` for sorting - * available clients. - */ - private int order = 0; - - // Visible for Testing - protected ZookeeperDiscoveryProperties() { - } - - public ZookeeperDiscoveryProperties(InetUtils inetUtils) { - this.hostInfo = inetUtils.findFirstNonLoopbackHostInfo(); - this.instanceHost = this.hostInfo.getHostname(); - this.instanceIpAddress = this.hostInfo.getIpAddress(); - } - - public boolean isEnabled() { - return this.enabled; - } - - public String getRoot() { - return this.root; - } - - public String getUriSpec() { - return this.uriSpec; - } - - public String getInstanceHost() { - if (this.preferIpAddress && StringUtils.hasText(this.instanceIpAddress)) { - return this.instanceIpAddress; - } - return this.instanceHost; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public void setRoot(String root) { - this.root = DependencyPathUtils.sanitize(root); - } - - public void setUriSpec(String uriSpec) { - this.uriSpec = uriSpec; - } - - public String getInstanceId() { - return this.instanceId; - } - - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - - public void setInstanceHost(String instanceHost) { - this.instanceHost = instanceHost; - this.hostInfo.override = true; - } - - public void setInstanceIpAddress(String instanceIpAddress) { - this.instanceIpAddress = instanceIpAddress; - this.hostInfo.override = true; - } - - public void setPreferIpAddress(boolean preferIpAddress) { - this.preferIpAddress = preferIpAddress; - } - - public Map getMetadata() { - return this.metadata; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - - public boolean isRegister() { - return this.register; - } - - public void setRegister(boolean register) { - this.register = register; - } - - public Integer getInstancePort() { - return this.instancePort; - } - - public void setInstancePort(Integer instancePort) { - this.instancePort = instancePort; - } - - public Integer getInstanceSslPort() { - return this.instanceSslPort; - } - - public void setInstanceSslPort(Integer instanceSslPort) { - this.instanceSslPort = instanceSslPort; - } - - public String getInitialStatus() { - return this.initialStatus; - } - - public void setInitialStatus(String initialStatus) { - this.initialStatus = initialStatus; - } - - public int getOrder() { - return this.order; - } - - public void setOrder(int order) { - this.order = order; - } - - @Override - public String toString() { - return "ZookeeperDiscoveryProperties{" + "enabled=" + this.enabled + ", root='" - + this.root + '\'' + ", uriSpec='" + this.uriSpec + '\'' - + ", instanceId='" + this.instanceId + '\'' + ", instanceHost='" - + this.instanceHost + '\'' + ", instancePort='" + this.instancePort + '\'' - + ", instanceSslPort='" + this.instanceSslPort + '\'' + ", metadata=" - + this.metadata + ", register=" + this.register + ", initialStatus=" - + this.initialStatus + ", order=" + this.order + '}'; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperInstance.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperInstance.java deleted file mode 100644 index 383db8ab2..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperInstance.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.HashMap; -import java.util.Map; - -/** - * Represents the default payload of a registered service in Zookeeper. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class ZookeeperInstance { - - private String id; - - private String name; - - private Map metadata = new HashMap<>(); - - @SuppressWarnings("unused") - private ZookeeperInstance() { - } - - public ZookeeperInstance(String id, String name, Map metadata) { - this.id = id; - this.name = name; - this.metadata = metadata; - } - - public String getId() { - return this.id; - } - - public String getName() { - return this.name; - } - - public void setId(String id) { - this.id = id; - } - - public void setName(String name) { - this.name = name; - } - - public Map getMetadata() { - return this.metadata; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - - @Override - public String toString() { - return "ZookeeperInstance{" + "id='" + this.id + '\'' + ", name='" + this.name - + '\'' + ", metadata=" + this.metadata + '}'; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLoadBalancerConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLoadBalancerConfiguration.java deleted file mode 100644 index 51b0404d9..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLoadBalancerConfiguration.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.loadbalancer.cache.LoadBalancerCacheManager; -import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier; -import org.springframework.cloud.loadbalancer.core.DiscoveryClientServiceInstanceListSupplier; -import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** - * Zookeeper-specific {@link ServiceInstanceListSupplier} that provides a delegate that - * filters available instances based on status retrieved from Zookeeper. - * - * @author Olga Maciaszek-Sharma - * @since 3.0.0 - */ -@Configuration(proxyBeanMethods = false) -public class ZookeeperLoadBalancerConfiguration { - - @Bean - @ConditionalOnBean(DiscoveryClient.class) - @ConditionalOnMissingBean - public ServiceInstanceListSupplier zookeeperDiscoveryClientServiceInstanceListSupplier( - DiscoveryClient discoveryClient, Environment env, - ApplicationContext context, - ZookeeperDependencies zookeeperDependencies) { - DiscoveryClientServiceInstanceListSupplier firstDelegate = new DiscoveryClientServiceInstanceListSupplier( - discoveryClient, env); - ZookeeperServiceInstanceListSupplier secondDelegate = new ZookeeperServiceInstanceListSupplier(firstDelegate, - zookeeperDependencies); - ObjectProvider cacheManagerProvider = context - .getBeanProvider(LoadBalancerCacheManager.class); - if (cacheManagerProvider.getIfAvailable() != null) { - return new CachingServiceInstanceListSupplier(secondDelegate, - cacheManagerProvider.getIfAvailable()); - } - return secondDelegate; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstance.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstance.java deleted file mode 100644 index cdcd3170a..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstance.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.net.URI; -import java.util.HashMap; -import java.util.Map; - -import org.springframework.cloud.client.ServiceInstance; - -/** - * A specific {@link ServiceInstance} describing a zookeeper service instance. - * - * @author Reda Housni-Alaoui - * @author Tim Ysewyn - * @since 1.1.0 - */ -public class ZookeeperServiceInstance implements ServiceInstance { - - private final String serviceId; - - private final String host; - - private final int port; - - private final boolean secure; - - private final URI uri; - - private final Map metadata; - - private final org.apache.curator.x.discovery.ServiceInstance serviceInstance; - - /** - * @param serviceId The service id to be used - * @param serviceInstance The zookeeper service instance described by this service - * instance - */ - public ZookeeperServiceInstance(String serviceId, - org.apache.curator.x.discovery.ServiceInstance serviceInstance) { - this.serviceId = serviceId; - this.serviceInstance = serviceInstance; - this.host = this.serviceInstance.getAddress(); - this.secure = serviceInstance.getSslPort() != null; - Integer port = serviceInstance.getPort(); - if (this.secure) { - port = serviceInstance.getSslPort(); - } - this.port = port; - this.uri = URI.create(serviceInstance.buildUriSpec()); - if (serviceInstance.getPayload() != null) { - this.metadata = serviceInstance.getPayload().getMetadata(); - } - else { - this.metadata = new HashMap<>(); - } - } - - @Override - public String getInstanceId() { - return this.serviceInstance.getId(); - } - - @Override - public String getServiceId() { - return this.serviceId; - } - - @Override - public String getHost() { - return this.host; - } - - @Override - public int getPort() { - return this.port; - } - - @Override - public boolean isSecure() { - return this.secure; - } - - @Override - public URI getUri() { - return this.uri; - } - - @Override - public Map getMetadata() { - return this.metadata; - } - - public org.apache.curator.x.discovery.ServiceInstance getServiceInstance() { - return this.serviceInstance; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstanceListSupplier.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstanceListSupplier.java deleted file mode 100644 index 42c830dc7..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstanceListSupplier.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.ArrayList; -import java.util.List; - -import reactor.core.publisher.Flux; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.util.StringUtils; - -import static org.springframework.cloud.zookeeper.support.StatusConstants.INSTANCE_STATUS_KEY; -import static org.springframework.cloud.zookeeper.support.StatusConstants.STATUS_UP; - -/** - * A {@link ServiceInstanceListSupplier} implementation that filters available instances based on status retrieved from Zookeeper. - * - * @author Olga Maciaszek-Sharma - * @since 3.0.0 - */ -public class ZookeeperServiceInstanceListSupplier implements ServiceInstanceListSupplier { - - private final ServiceInstanceListSupplier delegate; - private final String serviceId; - - public ZookeeperServiceInstanceListSupplier(ServiceInstanceListSupplier delegate, - ZookeeperDependencies zookeeperDependencies) { - this.delegate = delegate; - this.serviceId = getServiceIdFromDepsOrClientName(delegate - .getServiceId(), zookeeperDependencies); - } - - private String getServiceIdFromDepsOrClientName(String delegateServiceId, - ZookeeperDependencies zookeeperDependencies) { - String serviceIdFromDeps = zookeeperDependencies - .getPathForAlias(delegateServiceId); - return StringUtils.hasText(serviceIdFromDeps) ? serviceIdFromDeps - : delegateServiceId; - } - - @Override - public String getServiceId() { - return serviceId; - } - - @Override - public Flux> get() { - return delegate.get().map(this::filteredByZookeeperStatusUp); - } - - private List filteredByZookeeperStatusUp(List serviceInstances) { - ArrayList filteredInstances = new ArrayList<>(); - for (ServiceInstance serviceInstance : serviceInstances) { - if (serviceInstance instanceof ZookeeperServiceInstance) { - org.apache.curator.x.discovery.ServiceInstance zookeeperServiceInstance = ((ZookeeperServiceInstance) serviceInstance) - .getServiceInstance(); - String instanceStatus = null; - if (zookeeperServiceInstance.getPayload() != null - && zookeeperServiceInstance.getPayload().getMetadata() != null) { - instanceStatus = zookeeperServiceInstance.getPayload().getMetadata() - .get(INSTANCE_STATUS_KEY); - } - if (!StringUtils.hasText(instanceStatus) // backwards compatibility - || instanceStatus.equalsIgnoreCase(STATUS_UP)) { - filteredInstances.add(serviceInstance); - } - } - } - return filteredInstances; - } -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstances.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstances.java deleted file mode 100644 index d0c93be8d..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstances.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceInstance; - -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; - -import static org.springframework.cloud.zookeeper.discovery.DependencyPathUtils.sanitize; - -/** - * An {@link Iterable} representing registered Zookeeper instances. If using - * {@link ZookeeperDependencies} it will return a list of registered Zookeeper instances - * corresponding to the ones defined in the dependencies. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -public class ZookeeperServiceInstances - implements Iterable> { - - private static final Log log = LogFactory.getLog(ZookeeperServiceInstances.class); - - private ServiceDiscovery serviceDiscovery; - - private final ZookeeperDependencies zookeeperDependencies; - - private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; - - private final List> allInstances; - - private final CuratorFramework curator; - - public ZookeeperServiceInstances(CuratorFramework curator, - ServiceDiscovery serviceDiscovery, - ZookeeperDependencies zookeeperDependencies, - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - this.curator = curator; - this.serviceDiscovery = serviceDiscovery; - this.zookeeperDependencies = zookeeperDependencies; - this.zookeeperDiscoveryProperties = zookeeperDiscoveryProperties; - this.allInstances = getZookeeperInstances(); - } - - private List> getZookeeperInstances() { - ArrayList> allInstances = new ArrayList<>(); - try { - Collection namesToQuery = getNamesToQuery(); - if (log.isDebugEnabled()) { - log.debug("Querying the following names [" + namesToQuery + "]"); - } - for (String name : namesToQuery) { - allInstances.addAll(nestedInstances(allInstances, name)); - } - return allInstances; - } - catch (Exception e) { - log.debug("Exception occurred while trying to build the list of instances", - e); - return allInstances; - } - } - - private List> nestedInstances( - List> accumulator, String name) - throws Exception { - String parentPath = prepareQueryName(name); - Collection> childrenInstances = tryToGetInstances( - parentPath); - if (childrenInstances != null) { - return convertCollectionToList(childrenInstances); - } - try { - List children = this.curator.getChildren().forPath(parentPath); - return iterateOverChildren(accumulator, parentPath, children); - } - catch (Exception e) { - if (log.isTraceEnabled()) { - log.trace("Exception occurred while trying to retrieve children of [" - + parentPath + "]", e); - } - return injectZookeeperServiceInstances(accumulator, parentPath); - } - } - - private String prepareQueryName(String name) { - String root = this.zookeeperDiscoveryProperties.getRoot(); - return name.startsWith(root) ? name : root + name; - } - - private Collection> tryToGetInstances( - String path) { - try { - return getServiceDiscovery().queryForInstances(getPathWithoutRoot(path)); - } - catch (Exception e) { - log.trace("Exception occurred while trying to retrieve instances of [" + path - + "]", e); - return null; - } - } - - private ServiceDiscovery getServiceDiscovery() { - return this.serviceDiscovery; - } - - private String getPathWithoutRoot(String path) { - return path.substring(this.zookeeperDiscoveryProperties.getRoot().length()); - } - - private List> injectZookeeperServiceInstances( - List> accumulator, String name) - throws Exception { - Collection> instances = getServiceDiscovery() - .queryForInstances(name); - accumulator.addAll(convertCollectionToList(instances)); - return accumulator; - } - - private List> convertCollectionToList( - Collection> instances) { - List> serviceInstances = new ArrayList<>(); - for (ServiceInstance instance : instances) { - serviceInstances.add(instance); - } - return serviceInstances; - } - - private List> iterateOverChildren( - List> accumulator, String parentPath, - List children) throws Exception { - List> lists = new ArrayList<>(); - for (String child : children) { - lists.addAll(nestedInstances(accumulator, parentPath + "/" + child)); - } - return lists; - } - - private Collection getNamesToQuery() throws Exception { - if (this.zookeeperDependencies == null) { - if (log.isDebugEnabled()) { - log.debug("Using direct name resolution instead of dependency based one"); - } - List names = new ArrayList<>(); - for (String name : getServiceDiscovery().queryForNames()) { - names.add(sanitize(name)); - } - return names; - } - if (log.isDebugEnabled()) { - log.debug("Using dependency based names to query"); - } - return this.zookeeperDependencies.getDependencyNames(); - } - - @Override - public Iterator> iterator() { - return this.allInstances.iterator(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceWatch.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceWatch.java deleted file mode 100644 index b7cb45ec0..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceWatch.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.concurrent.atomic.AtomicLong; - -import jakarta.annotation.PreDestroy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.cache.TreeCache; -import org.apache.curator.framework.recipes.cache.TreeCacheEvent; -import org.apache.curator.framework.recipes.cache.TreeCacheListener; - -import org.springframework.cloud.client.discovery.event.HeartbeatEvent; -import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.ApplicationEventPublisherAware; -import org.springframework.context.ApplicationListener; -import org.springframework.util.ReflectionUtils; - -/** - * A {@link TreeCacheListener} that sends {@link HeartbeatEvent} when an entry inside - * Zookeeper has changed. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class ZookeeperServiceWatch - implements ApplicationListener>, TreeCacheListener, - ApplicationEventPublisherAware { - - private final CuratorFramework curator; - - private final ZookeeperDiscoveryProperties properties; - - private final AtomicLong cacheChange = new AtomicLong(0); - - private ApplicationEventPublisher publisher; - - private TreeCache cache; - - public ZookeeperServiceWatch(CuratorFramework curator, - ZookeeperDiscoveryProperties properties) { - this.curator = curator; - this.properties = properties; - } - - @Override - public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { - this.publisher = publisher; - } - - public TreeCache getCache() { - return this.cache; - } - - @Override - public void onApplicationEvent(InstanceRegisteredEvent event) { - this.cache = TreeCache.newBuilder(this.curator, this.properties.getRoot()) - .build(); - this.cache.getListenable().addListener(this); - try { - this.cache.start(); - } - catch (Exception e) { - ReflectionUtils.rethrowRuntimeException(e); - } - } - - @PreDestroy - public void stop() throws Exception { - if (this.cache != null) { - this.cache.close(); - } - } - - @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) - throws Exception { - if (event.getType().equals(TreeCacheEvent.Type.NODE_ADDED) - || event.getType().equals(TreeCacheEvent.Type.NODE_REMOVED) - || event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) { - long newCacheChange = this.cacheChange.incrementAndGet(); - this.publisher.publishEvent(new HeartbeatEvent(this, newCacheChange)); - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfiguration.java deleted file mode 100644 index 73c44a563..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfiguration.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2013-2016 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.configclient; - -import jakarta.annotation.PostConstruct; -import org.apache.curator.framework.CuratorFramework; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.config.server.config.ConfigServerProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; - -/** - * Extra configuration for config server if it happens to be registered with Zookeeper. - * - * @author Dave Syer - */ -@Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties -@ConditionalOnClass({ ZookeeperDiscoveryProperties.class, CuratorFramework.class, - ConfigServerProperties.class }) -public class ZookeeperConfigServerAutoConfiguration { - - @Autowired(required = false) - private ZookeeperDiscoveryProperties properties; - - @Autowired(required = false) - private ConfigServerProperties server; - - @PostConstruct - public void init() { - if (this.properties == null || this.server == null) { - return; - } - String prefix = this.server.getPrefix(); - if (StringUtils.hasText(prefix)) { - this.properties.getMetadata().put("configPath", prefix); - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapper.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapper.java deleted file mode 100644 index 5bdd11f4b..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapper.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.configclient; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Stream; - -import org.apache.commons.logging.Log; -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; -import org.apache.curator.x.discovery.details.InstanceSerializer; -import org.apache.curator.x.discovery.details.JsonInstanceSerializer; - -import org.springframework.boot.BootstrapContext; -import org.springframework.boot.BootstrapRegistry; -import org.springframework.boot.BootstrapRegistryInitializer; -import org.springframework.boot.context.properties.bind.BindHandler; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.cloud.config.client.ConfigClientProperties; -import org.springframework.cloud.config.client.ConfigServerInstanceProvider; -import org.springframework.cloud.zookeeper.CuratorFactory; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.cloud.zookeeper.discovery.ConditionalOnZookeeperDiscoveryEnabled; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryClient; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.cloud.zookeeper.support.DefaultServiceDiscoveryCustomizer; -import org.springframework.cloud.zookeeper.support.ServiceDiscoveryCustomizer; -import org.springframework.util.ClassUtils; - -public class ZookeeperConfigServerBootstrapper implements BootstrapRegistryInitializer { - - private static boolean isEnabled(Binder binder) { - return binder.bind(ConfigClientProperties.CONFIG_DISCOVERY_ENABLED, Boolean.class).orElse(false) && - binder.bind(ConditionalOnZookeeperDiscoveryEnabled.PROPERTY, Boolean.class).orElse(true) && - binder.bind("spring.cloud.discovery.enabled", Boolean.class).orElse(true); - } - - @Override - @SuppressWarnings("unchecked") - public void initialize(BootstrapRegistry registry) { - if (!ClassUtils.isPresent("org.springframework.cloud.config.client.ConfigServerInstanceProvider", null) || - // don't run if bootstrap enabled, how to check the property? - ClassUtils.isPresent("org.springframework.cloud.bootstrap.marker.Marker", null)) { - return; - } - // create curator - CuratorFactory.registerCurator(registry, null, true, bootstrapContext -> isEnabled(bootstrapContext.get(Binder.class))); - - // create discovery - registry.registerIfAbsent(ZookeeperDiscoveryProperties.class, context -> { - Binder binder = context.get(Binder.class); - if (!isEnabled(binder)) { - return null; - } - return binder.bind(ZookeeperDiscoveryProperties.PREFIX, Bindable - .of(ZookeeperDiscoveryProperties.class), getBindHandler(context)) - .orElseGet(() -> new ZookeeperDiscoveryProperties(new InetUtils(new InetUtilsProperties()))); - }); - registry.registerIfAbsent(InstanceSerializer.class, context -> { - if (!isEnabled(context.get(Binder.class))) { - return null; - } - return new JsonInstanceSerializer<>(ZookeeperInstance.class); - }); - registry.registerIfAbsent(ServiceDiscoveryCustomizer.class, context -> { - if (!isEnabled(context.get(Binder.class))) { - return null; - } - CuratorFramework curator = context.get(CuratorFramework.class); - ZookeeperDiscoveryProperties properties = context.get(ZookeeperDiscoveryProperties.class); - InstanceSerializer serializer = context.get(InstanceSerializer.class); - return new DefaultServiceDiscoveryCustomizer(curator, properties, serializer); - }); - registry.registerIfAbsent(ServiceDiscovery.class, context -> { - if (!isEnabled(context.get(Binder.class))) { - return null; - } - ServiceDiscoveryCustomizer customizer = context.get(ServiceDiscoveryCustomizer.class); - return customizer.customize(ServiceDiscoveryBuilder.builder(ZookeeperInstance.class)); - }); - registry.registerIfAbsent(ZookeeperDiscoveryClient.class, context -> { - Binder binder = context.get(Binder.class); - if (!isEnabled(binder)) { - return null; - } - ServiceDiscovery serviceDiscovery = context.get(ServiceDiscovery.class); - ZookeeperDependencies dependencies = binder.bind(ZookeeperDependencies.PREFIX, Bindable - .of(ZookeeperDependencies.class), getBindHandler(context)) - .orElseGet(ZookeeperDependencies::new); - ZookeeperDiscoveryProperties discoveryProperties = context.get(ZookeeperDiscoveryProperties.class); - - return new ZookeeperDiscoveryClient(serviceDiscovery, dependencies, discoveryProperties); - }); - - // create instance provider - // We need to pass the lambda here so we do not create a new instance of ConfigServerInstanceProvider.Function - // which would result in a ClassNotFoundException when Spring Cloud Config is not on the classpath - registry.registerIfAbsent(ConfigServerInstanceProvider.Function.class, ZookeeperFunction::create); - - // promote beans to context - registry.addCloseListener(event -> { - ZookeeperDiscoveryClient discoveryClient = event.getBootstrapContext().get(ZookeeperDiscoveryClient.class); - if (discoveryClient != null) { - event.getApplicationContext().getBeanFactory().registerSingleton("zookeeperServiceDiscovery", - discoveryClient); - } - }); - } - - private BindHandler getBindHandler(org.springframework.boot.BootstrapContext context) { - return context.getOrElse(BindHandler.class, null); - } - - /* - * This Function is executed when loading config data. Because of this we cannot rely on the - * BootstrapContext because Boot has not finished loading all the configuration data so if we - * ask the BootstrapContext for configuration data it will not have it. The apply method in this function - * is passed the Binder and BindHandler from the config data context which has the configuration properties that - * have been loaded so far in the config data process. - * - * We will create many of the same beans in this function as we do above in the initializer above. We do both - * to maintain compatibility since we are promoting those beans to the main application context. - */ - static final class ZookeeperFunction implements ConfigServerInstanceProvider.Function { - - private final BootstrapContext context; - - private ZookeeperFunction(BootstrapContext context) { - this.context = context; - } - - static ZookeeperFunction create(BootstrapContext context) { - return new ZookeeperFunction(context); - } - - @Override - public List apply(String serviceId) { - return apply(serviceId, null, null, null); - } - - @Override - public List apply(String serviceId, Binder binder, BindHandler bindHandler, Log log) { - if (binder == null || !isEnabled(binder)) { - return Collections.emptyList(); - } - - ZookeeperProperties properties = binder.bind(ZookeeperProperties.PREFIX, Bindable.of(ZookeeperProperties.class)) - .orElse(new ZookeeperProperties()); - RetryPolicy retryPolicy = new ExponentialBackoffRetry(properties.getBaseSleepTimeMs(), properties.getMaxRetries(), - properties.getMaxSleepMs()); - try { - CuratorFramework curatorFramework = CuratorFactory.curatorFramework(properties, retryPolicy, Stream::of, - () -> null, () -> null); - InstanceSerializer serializer = new JsonInstanceSerializer<>(ZookeeperInstance.class); - ZookeeperDiscoveryProperties discoveryProperties = binder.bind(ZookeeperDiscoveryProperties.PREFIX, Bindable - .of(ZookeeperDiscoveryProperties.class), bindHandler) - .orElseGet(() -> new ZookeeperDiscoveryProperties(new InetUtils(new InetUtilsProperties()))); - DefaultServiceDiscoveryCustomizer customizer = new DefaultServiceDiscoveryCustomizer(curatorFramework, discoveryProperties, serializer); - ServiceDiscovery serviceDiscovery = customizer.customize(ServiceDiscoveryBuilder.builder(ZookeeperInstance.class)); - ZookeeperDependencies dependencies = binder.bind(ZookeeperDependencies.PREFIX, Bindable - .of(ZookeeperDependencies.class), bindHandler) - .orElseGet(ZookeeperDependencies::new); - return new ZookeeperDiscoveryClient(serviceDiscovery, dependencies, discoveryProperties).getInstances(serviceId); - } - catch (Exception e) { - log.warn("Error fetching config server instance from Zookeeper", e); - return Collections.emptyList(); - } - - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration.java deleted file mode 100644 index c0962a07a..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.configclient; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.discovery.health.DiscoveryClientHealthIndicatorProperties; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.config.client.ConfigServicePropertySourceLocator; -import org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryClientConfiguration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.support.CuratorServiceDiscoveryAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.annotation.Order; - -/** - * Helper for config client that wants to lookup the config server via discovery. - * - * @author Spencer Gibb - * @author Tim Ysewyn - */ -@ConditionalOnClass(ConfigServicePropertySourceLocator.class) -@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false) -@Configuration(proxyBeanMethods = false) -@Import({ ZookeeperAutoConfiguration.class, ZookeeperDiscoveryClientConfiguration.class, - CuratorServiceDiscoveryAutoConfiguration.class, - ZookeeperDiscoveryAutoConfiguration.class }) -@EnableConfigurationProperties({DiscoveryClientHealthIndicatorProperties.class}) -@Order(0) -public class ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration { - - @Bean - public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties( - InetUtils inetUtils) { - ZookeeperDiscoveryProperties properties = new ZookeeperDiscoveryProperties( - inetUtils); - // for bootstrap, registration is not needed, just discovery client - properties.setRegister(false); - return properties; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesNotPassed.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesNotPassed.java deleted file mode 100644 index 174d73058..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesNotPassed.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.context.annotation.Conditional; - -/** - * Annotation to turn off a feature if Zookeeper dependencies have NOT been passed. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -@Target({ ElementType.TYPE, ElementType.METHOD }) -@Retention(RetentionPolicy.RUNTIME) -@Conditional(DependenciesNotPassedCondition.class) -public @interface ConditionalOnDependenciesNotPassed { - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesPassed.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesPassed.java deleted file mode 100644 index a3ce862f7..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesPassed.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.context.annotation.Conditional; - -/** - * Annotation to turn on a feature if Zookeeper dependencies have been passed. Also checks - * if switch for zookeeper dependencies is turned on. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -@Target({ ElementType.TYPE, ElementType.METHOD }) -@Retention(RetentionPolicy.RUNTIME) -@Conditional(DependenciesPassedCondition.class) -public @interface ConditionalOnDependenciesPassed { - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesNotPassedCondition.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesNotPassedCondition.java deleted file mode 100644 index 2bc270cc3..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesNotPassedCondition.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import org.springframework.boot.autoconfigure.condition.ConditionOutcome; -import org.springframework.context.annotation.ConditionContext; -import org.springframework.core.type.AnnotatedTypeMetadata; - -/** - * Inverse of the {@link ConditionalOnDependenciesPassed} condition. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -public class DependenciesNotPassedCondition extends DependenciesPassedCondition { - - @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionOutcome propertiesSet = super.getMatchOutcome(context, metadata); - return ConditionOutcome.inverse(propertiesSet); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesPassedCondition.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesPassedCondition.java deleted file mode 100644 index 271efaeb0..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesPassedCondition.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.Collections; -import java.util.Map; - -import org.springframework.boot.autoconfigure.condition.ConditionOutcome; -import org.springframework.boot.autoconfigure.condition.SpringBootCondition; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.context.annotation.ConditionContext; -import org.springframework.core.type.AnnotatedTypeMetadata; - -/** - * Condition that verifies if the Dependencies have been passed in an appropriate place in - * the application properties. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -public class DependenciesPassedCondition extends SpringBootCondition { - - private static final Bindable> STRING_STRING_MAP = Bindable - .mapOf(String.class, String.class); - - private static final String ZOOKEEPER_DEPENDENCIES_PROP = "spring.cloud.zookeeper.dependencies"; - - @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - Map subProperties = Binder.get(context.getEnvironment()) - .bind(ZOOKEEPER_DEPENDENCIES_PROP, STRING_STRING_MAP) - .orElseGet(Collections::emptyMap); - if (!subProperties.isEmpty()) { - return ConditionOutcome.match("Dependencies are defined in configuration"); - } - Boolean dependenciesEnabled = context.getEnvironment().getProperty( - "spring.cloud.zookeeper.dependency.enabled", Boolean.class, false); - if (dependenciesEnabled) { - return ConditionOutcome.match( - "Dependencies are not defined in configuration, but switch is turned on"); - } - return ConditionOutcome - .noMatch("No dependencies have been passed for the service"); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyEnvironmentPostProcessor.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyEnvironmentPostProcessor.java deleted file mode 100644 index 92a664ddc..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyEnvironmentPostProcessor.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.Collections; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.env.EnvironmentPostProcessor; -import org.springframework.cloud.bootstrap.BootstrapConfigFileApplicationListener; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MapPropertySource; -import org.springframework.util.StringUtils; - -/** - * EnvironmentPostProcessor that sets spring.application.name. Specifically, if - * spring.application.name doesn't contain a / and spring.cloud.zookeeper.prefix has text, - * it sets spring.application.name to - * /${spring.cloud.zookeeper.prefix}/${spring.application.name} - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class DependencyEnvironmentPostProcessor - implements EnvironmentPostProcessor, Ordered { - - // after ConfigFileEnvironmentPostProcessorr - private int order = BootstrapConfigFileApplicationListener.DEFAULT_ORDER + 1; - - @Override - public int getOrder() { - return this.order; - } - - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { - String appName = environment.getProperty("spring.application.name"); - if (StringUtils.hasText(appName) && !appName.contains("/")) { - String prefix = environment.getProperty("spring.cloud.zookeeper.prefix"); - if (StringUtils.hasText(prefix)) { - StringBuilder prefixedName = new StringBuilder(); - if (!prefix.startsWith("/")) { - prefixedName.append("/"); - } - prefixedName.append(prefix); - if (!prefix.endsWith("/")) { - prefixedName.append("/"); - } - prefixedName.append(appName); - MapPropertySource propertySource = new MapPropertySource( - "zookeeperDependencyEnvironment", - Collections.singletonMap("spring.application.name", - (Object) prefixedName.toString())); - environment.getPropertySources().addFirst(propertySource); - } - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyFeignClientAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyFeignClientAutoConfiguration.java deleted file mode 100644 index d47ffc5a4..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyFeignClientAutoConfiguration.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.io.IOException; -import java.net.URI; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import feign.Client; -import feign.Request; -import feign.Response; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties; -import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; -import org.springframework.cloud.loadbalancer.config.BlockingLoadBalancerClientAutoConfiguration; -import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; -import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient; -import org.springframework.cloud.openfeign.loadbalancer.FeignLoadBalancerAutoConfiguration; -import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; - -/** - * Configuration for ensuring that headers are set for a given dependency when Feign is - * used. - * - * @author Marcin Grzejszczak - * @author Olga Maciaszek-Sharma - * @since 1.0.0 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnDependenciesPassed -@ConditionalOnZookeeperEnabled -@ConditionalOnProperty(value = "spring.cloud.zookeeper.dependency.headers.enabled", matchIfMissing = true) -@ConditionalOnClass({Client.class, FeignBlockingLoadBalancerClient.class}) -@ConditionalOnBean(BlockingLoadBalancerClient.class) -@AutoConfigureAfter({FeignLoadBalancerAutoConfiguration.class, BlockingLoadBalancerClientAutoConfiguration.class}) -public class DependencyFeignClientAutoConfiguration { - - private final FeignBlockingLoadBalancerClient feignLoadBalancerClient; - - private final ZookeeperDependencies zookeeperDependencies; - - private final BlockingLoadBalancerClient loadBalancerClient; - - private final LoadBalancerProperties loadBalancerProperties; - - private final LoadBalancerClientFactory loadBalancerClientFactory; - - public DependencyFeignClientAutoConfiguration(@Autowired(required = false) FeignBlockingLoadBalancerClient feignLoadBalancerClient, - ZookeeperDependencies zookeeperDependencies, BlockingLoadBalancerClient loadBalancerClient, LoadBalancerProperties loadBalancerProperties, LoadBalancerClientFactory loadBalancerClientFactory) { - this.feignLoadBalancerClient = feignLoadBalancerClient; - this.zookeeperDependencies = zookeeperDependencies; - this.loadBalancerClient = loadBalancerClient; - this.loadBalancerProperties = loadBalancerProperties; - this.loadBalancerClientFactory = loadBalancerClientFactory; - } - - @Bean - @Primary - Client dependencyBasedFeignClient() { - return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), - loadBalancerClient, loadBalancerProperties, loadBalancerClientFactory) { - - @Override - public Response execute(Request request, Request.Options options) - throws IOException { - URI asUri = URI.create(request.url()); - String clientName = asUri.getHost(); - ZookeeperDependency dependencyForAlias = DependencyFeignClientAutoConfiguration.this.zookeeperDependencies - .getDependencyForAlias(clientName); - Map> headers = getUpdatedHeadersIfPossible( - request, dependencyForAlias); - if (DependencyFeignClientAutoConfiguration.this.feignLoadBalancerClient != null) { - return DependencyFeignClientAutoConfiguration.this.feignLoadBalancerClient - .execute(request(request, headers), options); - } - return super.execute(request(request, headers), options); - } - - private Request request(Request request, - Map> headers) { - return Request.create(request.httpMethod(), request.url(), headers, - request.body(), request.charset(), request.requestTemplate()); - } - - private Map> getUpdatedHeadersIfPossible( - Request request, ZookeeperDependency dependencyForAlias) { - if (dependencyForAlias != null) { - return Collections.unmodifiableMap(new HashMap<>( - dependencyForAlias.getUpdatedHeaders(request.headers()))); - } - return request.headers(); - } - - }; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRestTemplateAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRestTemplateAutoConfiguration.java deleted file mode 100644 index 6a13ecf87..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRestTemplateAutoConfiguration.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import jakarta.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; -import org.springframework.cloud.zookeeper.discovery.ConditionalOnLoadBalancerForZookeeperEnabled; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.web.client.RestTemplate; - -/** - * Customizes RestTemplate to support passing of params from dependency. - * - * @author Marcin Grzejszczak - * @author Olga Maciaszek-Sharma - * @since 1.0.0 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnZookeeperEnabled -@ConditionalOnLoadBalancerForZookeeperEnabled -@ConditionalOnDependenciesPassed -@ConditionalOnProperty(value = "spring.cloud.zookeeper.dependency.resttemplate.enabled", matchIfMissing = true) -@ConditionalOnBean(RestTemplate.class) -public class DependencyRestTemplateAutoConfiguration { - - @Autowired - @LoadBalanced - RestTemplate restTemplate; - - @Autowired - ZookeeperDependencies zookeeperDependencies; - - @PostConstruct - void customizeRestTemplate() { - this.restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() { - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { - String clientName = request.getURI().getHost(); - ZookeeperDependency dependencyForAlias = DependencyRestTemplateAutoConfiguration.this.zookeeperDependencies - .getDependencyForAlias(clientName); - HttpHeaders headers = getUpdatedHeadersIfPossible(request, - dependencyForAlias); - request.getHeaders().putAll(headers); - return execution.execute(request, body); - } - - private HttpHeaders getUpdatedHeadersIfPossible(HttpRequest request, - ZookeeperDependency dependencyForAlias) { - HttpHeaders httpHeaders = new HttpHeaders(); - if (dependencyForAlias != null) { - Map> updatedHeaders = dependencyForAlias - .getUpdatedHeaders(convertHeadersFromListToCollection( - request.getHeaders())); - httpHeaders - .putAll(convertHeadersFromCollectionToList(updatedHeaders)); - return httpHeaders; - } - httpHeaders.putAll(request.getHeaders()); - return httpHeaders; - } - - private Map> convertHeadersFromListToCollection( - HttpHeaders headers) { - Map> transformedHeaders = new HashMap<>(); - for (Map.Entry> entry : headers.entrySet()) { - transformedHeaders.put(entry.getKey(), entry.getValue()); - } - return transformedHeaders; - } - - private Map> convertHeadersFromCollectionToList( - Map> headers) { - Map> transformedHeaders = new HashMap<>(); - for (Map.Entry> entry : headers.entrySet()) { - transformedHeaders.put(entry.getKey(), - new ArrayList<>(entry.getValue())); - } - return transformedHeaders; - } - }); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfiguration.java deleted file mode 100644 index 2313f07a4..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfiguration.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.Arrays; -import java.util.LinkedList; - -import org.springframework.util.StringUtils; - -/** - * Representation of a stubs location. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -public class StubsConfiguration { - - private static final String DEFAULT_STUBS_CLASSIFIER = "stubs"; - - private static final String STUB_COLON_DELIMITER = ":"; - - private static final String PATH_SLASH_DELIMITER = "/"; - - private final String stubsGroupId; - - private final String stubsArtifactId; - - private final String stubsClassifier; - - public StubsConfiguration(String stubsGroupId, String stubsArtifactId, - String stubsClassifier) { - this.stubsGroupId = stubsGroupId; - this.stubsArtifactId = stubsArtifactId; - this.stubsClassifier = StringUtils.hasText(stubsClassifier) ? stubsClassifier - : DEFAULT_STUBS_CLASSIFIER; - } - - public StubsConfiguration(String stubPath) { - String[] parsedPath = parsedStubPathEmptyByDefault(stubPath, - STUB_COLON_DELIMITER); - this.stubsGroupId = parsedPath[0]; - this.stubsArtifactId = parsedPath[1]; - this.stubsClassifier = parsedPath[2]; - } - - public StubsConfiguration(DependencyPath path) { - String[] parsedPath = parsedDependencyPathEmptyByDefault(path.getPath(), - PATH_SLASH_DELIMITER); - this.stubsGroupId = parsedPath[0]; - this.stubsArtifactId = parsedPath[1]; - this.stubsClassifier = parsedPath[2]; - } - - private String[] parsedStubPathEmptyByDefault(String path, String delimiter) { - String[] splitPath = path.split(delimiter); - String stubsGroupId = ""; - String stubsArtifactId = ""; - String stubsClassifier = ""; - if (splitPath.length >= 2) { - stubsGroupId = splitPath[0]; - stubsArtifactId = splitPath[1]; - stubsClassifier = splitPath.length == 3 ? splitPath[2] - : DEFAULT_STUBS_CLASSIFIER; - } - return new String[] { stubsGroupId, stubsArtifactId, stubsClassifier }; - } - - private String[] parsedDependencyPathEmptyByDefault(String path, String delimiter) { - String trimmedPath = path.startsWith(delimiter) ? path.substring(1) : path; - String[] splitPath = trimmedPath.split(delimiter); - String stubsGroupId = ""; - String stubsArtifactId = ""; - String stubsClassifier = ""; - if (splitPath.length >= 2) { - LinkedList list = new LinkedList<>(Arrays.asList(splitPath)); - String lastElement = list.removeLast(); - stubsGroupId = StringUtils.collectionToDelimitedString(list, "."); - stubsArtifactId = lastElement; - stubsClassifier = DEFAULT_STUBS_CLASSIFIER; - } - return new String[] { stubsGroupId, stubsArtifactId, stubsClassifier }; - } - - private boolean isDefined() { - return StringUtils.hasText(this.stubsGroupId) - && StringUtils.hasText(this.stubsArtifactId); - } - - public String toColonSeparatedDependencyNotation() { - if (!isDefined()) { - return ""; - } - return StringUtils.collectionToDelimitedString(Arrays.asList(getStubsGroupId(), - getStubsArtifactId(), getStubsClassifier()), STUB_COLON_DELIMITER); - } - - public String getStubsGroupId() { - return this.stubsGroupId; - } - - public String getStubsArtifactId() { - return this.stubsArtifactId; - } - - public String getStubsClassifier() { - return this.stubsClassifier; - } - - /** - * Marker class to discern between the stubs location and dependency registration path. - */ - public static class DependencyPath { - - private final String path; - - public DependencyPath(String path) { - this.path = path; - } - - public String getPath() { - return this.path; - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependencies.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependencies.java deleted file mode 100644 index 2b6b4bc24..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependencies.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import jakarta.annotation.PostConstruct; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cloud.zookeeper.discovery.dependency.StubsConfiguration.DependencyPath; -import org.springframework.util.StringUtils; - -import static org.springframework.cloud.zookeeper.discovery.DependencyPathUtils.sanitize; - -/** - * Representation of this service's dependencies in Zookeeper. - * - * @author Marcin Grzejszczak - * @author Olga Maciaszek-Sharma - * @since 1.0.0 - */ -@ConfigurationProperties(ZookeeperDependencies.PREFIX) -public class ZookeeperDependencies { - - /** - * Zookeeper Dependencies prefix. - */ - public static final String PREFIX = "spring.cloud.zookeeper"; - - /** - * Common prefix that will be applied to all Zookeeper dependencies' paths. - */ - private String prefix = ""; - - /** - * Mapping of alias to ZookeeperDependency. From LoadBalancer perspective the alias is - * actually serviceID since SC LoadBalancer can't accept nested structures in serviceID. - */ - private Map dependencies = new LinkedHashMap<>(); - - @PostConstruct - public void init() { - if (StringUtils.hasText(this.prefix)) { - this.prefix = sanitize(this.prefix); - } - for (Map.Entry entry : this.dependencies - .entrySet()) { - ZookeeperDependency value = entry.getValue(); - - if (!StringUtils.hasText(value.getPath())) { - value.setPath(entry.getKey()); - } - - value.setPath(sanitize(value.getPath())); - - if (StringUtils.hasText(this.prefix)) { - value.setPath(this.prefix + value.getPath()); - } - - setStubDefinition(value); - } - } - - private void setStubDefinition(ZookeeperDependency value) { - if (!StringUtils.hasText(value.getStubs())) { - value.setStubsConfiguration( - new StubsConfiguration(new DependencyPath(value.getPath()))); - } - else { - value.setStubsConfiguration(new StubsConfiguration(value.getStubs())); - } - } - - public Collection getDependencyConfigurations() { - return this.dependencies.values(); - } - - public boolean hasDependencies() { - return !this.dependencies.isEmpty(); - } - - public ZookeeperDependency getDependencyForPath(final String path) { - for (Map.Entry zookeeperDependencyEntry : this.dependencies - .entrySet()) { - if (zookeeperDependencyEntry.getValue().getPath().equals(path)) { - return zookeeperDependencyEntry.getValue(); - } - } - return null; - } - - public ZookeeperDependency getDependencyForAlias(final String alias) { - for (Map.Entry zookeeperDependencyEntry : this.dependencies - .entrySet()) { - if (zookeeperDependencyEntry.getKey().equals(alias)) { - return zookeeperDependencyEntry.getValue(); - } - } - return null; - } - - public String getPathForAlias(final String alias) { - ZookeeperDependency dependency = getDependencyForAlias(alias); - if (dependency != null) { - return dependency.getPath(); - } - return ""; - } - - public String getAliasForPath(final String path) { - for (Map.Entry zookeeperDependencyEntry : this.dependencies - .entrySet()) { - if (zookeeperDependencyEntry.getValue().getPath().equals(path)) { - return zookeeperDependencyEntry.getKey(); - } - } - return ""; - } - - public Collection getDependencyNames() { - List names = new ArrayList<>(); - for (Map.Entry zookeeperDependencyEntry : this.dependencies - .entrySet()) { - names.add(zookeeperDependencyEntry.getValue().getPath()); - } - return names; - } - - public String getPrefix() { - return this.prefix; - } - - public Map getDependencies() { - return this.dependencies; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public void setDependencies(Map dependencies) { - this.dependencies = dependencies; - } - - @Override - public String toString() { - final StringBuffer sb = new StringBuffer("ZookeeperDependencies{"); - sb.append("prefix='").append(this.prefix).append('\''); - sb.append(", dependencies=").append(this.dependencies); - sb.append('}'); - return sb.toString(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesAutoConfiguration.java deleted file mode 100644 index 30c3eb57d..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesAutoConfiguration.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; -import org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Provides AutoConfiguration for Zookeeper dependency set up in properties. - * - * @author Marcin Grzejszczak - * @author Olga Maciaszek-Sharma - * @since 1.0.0 - */ -@Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties -@ConditionalOnZookeeperEnabled -@AutoConfigureAfter(ZookeeperAutoConfiguration.class) -public class ZookeeperDependenciesAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - public ZookeeperDependencies zookeeperDependencies() { - return new ZookeeperDependencies(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependency.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependency.java deleted file mode 100644 index d2a06be5a..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependency.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.springframework.util.StringUtils; - -import static java.util.Collections.singletonList; - -/** - * Represents a particular dependency of Zookeeper instance. - * - * @author Marcin Grzejszczak - * @author Spencer Gibb - * @author Olga Maciaszek-Sharma - * @since 1.0.0 - */ -public class ZookeeperDependency { - - private static final String VERSION_PLACEHOLDER_REGEX = "\\$version"; - - private static final String CONTENT_TYPE_HEADER = "Content-Type"; - - /** - * Path under which the dependency is registered in Zookeeper. The common prefix - * {@link ZookeeperDependencies#prefix} will be applied to this path. - */ - private String path; - - /** - * Content type template with {@code $version} placeholder which will be filled by the - * {@link ZookeeperDependency#version} variable. - *

- * e.g. {@code 'application/vnd.some-service.$version+json'} - */ - private String contentTypeTemplate = ""; - - /** - * Provide the current version number of the dependency. This version will be placed - * under the {@code $version} placeholder in - * {@link ZookeeperDependency#contentTypeTemplate}. - */ - private String version = ""; - - /** - * You can provide a map of default headers that should be attached when sending a - * message to the dependency. - */ - private Map> headers = new HashMap<>(); - - /** - * If set to true - if the dependency is not present on startup then the application - * will not boot successfully. - *

- * {@link org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier} - * {@link org.springframework.cloud.zookeeper.discovery.watcher.DefaultDependencyWatcher} - */ - private boolean required; - - /** - * Colon separated notation of the stubs. E.g. - * {@code org.springframework:zookeeper-sample:stubs}. If not provided the - * {@code path} will be parsed to try to split it into groupId and artifactId. If not - * provided the classifier will by default equal {@code stubs} - */ - private String stubs; - - public ZookeeperDependency() { - } - - public ZookeeperDependency(String path, String contentTypeTemplate, String version, - Map> headers, boolean required, String stubs) { - this.path = path; - this.contentTypeTemplate = contentTypeTemplate; - this.version = version; - this.headers = headers; - this.required = required; - this.stubs = stubs; - } - - /** - * Parsed stubs path. - */ - private StubsConfiguration stubsConfiguration; - - public ZookeeperDependency(String path) { - if (StringUtils.hasText(path)) { - this.path = path; - } - } - - /** - * Function that will replace the placeholder - * {@link ZookeeperDependency#VERSION_PLACEHOLDER_REGEX} from the - * {@link ZookeeperDependency#contentTypeTemplate} with value from - * {@link ZookeeperDependency#version}. - *

- *

- * e.g. having: - *

  • contentTypeTemplate: {@code 'application/vnd.some-service.$version+json'}
  • - *
  • version: {@code 'v1'}
  • - *

    - *

    - * the result of the function will be {@code 'application/vnd.some-service.v1+json'} - * @return content type template with version - */ - public String getContentTypeWithVersion() { - if (!StringUtils.hasText(this.contentTypeTemplate) - || !StringUtils.hasText(this.version)) { - return ""; - } - return this.contentTypeTemplate.replaceAll(VERSION_PLACEHOLDER_REGEX, - this.version); - } - - public Map> getUpdatedHeaders( - Map> headers) { - Map> newHeaders = new HashMap<>(headers); - if (hasContentTypeTemplate()) { - setContentTypeFromTemplate(newHeaders); - } - if (hasHeadersSet()) { - addPredefinedHeaders(newHeaders); - } - return newHeaders; - } - - private void setContentTypeFromTemplate(Map> headers) { - Collection contentTypes = headers.get(CONTENT_TYPE_HEADER); - if (contentTypes == null || contentTypes.isEmpty()) { - headers.put(CONTENT_TYPE_HEADER, singletonList(getContentTypeWithVersion())); - } - else { - contentTypes.add(getContentTypeWithVersion()); - } - } - - private void addPredefinedHeaders(Map> newHeaders) { - for (Map.Entry> entry : this.headers.entrySet()) { - Collection value = newHeaders.get(entry.getKey()); - if (value == null || value.isEmpty()) { - newHeaders.put(entry.getKey(), entry.getValue()); - } - else { - value.addAll(entry.getValue()); - } - } - } - - private boolean hasContentTypeTemplate() { - return StringUtils.hasText(this.contentTypeTemplate); - } - - private boolean hasHeadersSet() { - return !this.headers.isEmpty(); - } - - public String getPath() { - return this.path; - } - - public String getContentTypeTemplate() { - return this.contentTypeTemplate; - } - - public String getVersion() { - return this.version; - } - - public Map> getHeaders() { - return this.headers; - } - - public boolean isRequired() { - return this.required; - } - - public String getStubs() { - return this.stubs; - } - - public StubsConfiguration getStubsConfiguration() { - return this.stubsConfiguration; - } - - public void setPath(String path) { - this.path = path; - } - - public void setContentTypeTemplate(String contentTypeTemplate) { - this.contentTypeTemplate = contentTypeTemplate; - } - - public void setVersion(String version) { - this.version = version; - } - - public void setHeaders(Map> headers) { - this.headers = headers; - } - - public void setRequired(boolean required) { - this.required = required; - } - - public void setStubs(String stubs) { - this.stubs = stubs; - } - - public void setStubsConfiguration(StubsConfiguration stubsConfiguration) { - this.stubsConfiguration = stubsConfiguration; - } - - @Override - public String toString() { - final StringBuffer sb = new StringBuffer("ZookeeperDependency{"); - sb.append("path='").append(this.path).append('\''); - sb.append(", contentTypeTemplate='").append(this.contentTypeTemplate) - .append('\''); - sb.append(", version='").append(this.version).append('\''); - sb.append(", headers=").append(this.headers); - sb.append(", required=").append(this.required); - sb.append(", stubs='").append(this.stubs).append('\''); - sb.append(", stubsConfiguration=").append(this.stubsConfiguration); - sb.append('}'); - return sb.toString(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClient.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClient.java deleted file mode 100644 index 1f7881b83..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClient.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2019-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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.reactive; - -import java.util.function.Function; -import java.util.function.Supplier; - -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.reactivestreams.Publisher; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.discovery.ZookeeperServiceInstance; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; - -/** - * Zookeeper version of {@link ReactiveDiscoveryClient}. Capable of resolving aliases from - * {@link org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies} to service names in Zookeeper. - * - * @author Tim Ysewyn - * @since 2.2.0 - */ -public class ZookeeperReactiveDiscoveryClient implements ReactiveDiscoveryClient { - - private static final Logger logger = LoggerFactory.getLogger(ZookeeperReactiveDiscoveryClient.class); - - private final ServiceDiscovery serviceDiscovery; - - private final ZookeeperDependencies zookeeperDependencies; - - private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; - - public ZookeeperReactiveDiscoveryClient(ServiceDiscovery serviceDiscovery, - ZookeeperDependencies zookeeperDependencies, ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - this.serviceDiscovery = serviceDiscovery; - this.zookeeperDependencies = zookeeperDependencies; - this.zookeeperDiscoveryProperties = zookeeperDiscoveryProperties; - } - - @Override - public String description() { - return "Spring Cloud Zookeeper Reactive Discovery Client"; - } - - @Override - public Flux getInstances(String serviceId) { - String serviceIdToQuery = serviceIdToQuery(serviceId); - return Mono.justOrEmpty(serviceIdToQuery) - .flatMapMany(getInstancesFromZookeeper()) - .subscribeOn(Schedulers.boundedElastic()) - .map(zkInstance -> toZookeeperServiceInstance(serviceIdToQuery, zkInstance)); - } - - private Function>> getInstancesFromZookeeper() { - return service -> { - try { - return Flux.fromIterable(serviceDiscovery.queryForInstances(service)); - } - catch (Exception e) { - logger.error("Error getting instances from zookeeper. Possibly, no service has registered.", e); - return Flux.empty(); - } - }; - } - - private ZookeeperServiceInstance toZookeeperServiceInstance(String serviceId, - org.apache.curator.x.discovery.ServiceInstance zkInstanceServiceInstance) { - return new ZookeeperServiceInstance(serviceId, zkInstanceServiceInstance); - } - - @Override - public Flux getServices() { - return Flux.defer(getServicesFromZookeeper()) - .subscribeOn(Schedulers.boundedElastic()); - } - - private Supplier> getServicesFromZookeeper() { - return () -> { - try { - return Flux.fromIterable(serviceDiscovery.queryForNames()); - } - catch (Exception e) { - logger.error("Error getting services from zookeeper. Possibly, no service has registered.", e); - return Flux.empty(); - } - }; - } - - private String serviceIdToQuery(String serviceId) { - if (zookeeperDependencies != null - && zookeeperDependencies.hasDependencies()) { - String pathForAlias = zookeeperDependencies.getPathForAlias(serviceId); - return pathForAlias.isEmpty() ? serviceId : pathForAlias; - } - return serviceId; - } - - @Override - public int getOrder() { - return zookeeperDiscoveryProperties.getOrder(); - } -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientConfiguration.java deleted file mode 100644 index cf506faf3..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientConfiguration.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2019-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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.reactive; - -import org.apache.curator.x.discovery.ServiceDiscovery; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; -import org.springframework.cloud.client.ConditionalOnDiscoveryHealthIndicatorEnabled; -import org.springframework.cloud.client.ConditionalOnReactiveDiscoveryEnabled; -import org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration; -import org.springframework.cloud.client.discovery.composite.reactive.ReactiveCompositeDiscoveryClientAutoConfiguration; -import org.springframework.cloud.client.discovery.health.DiscoveryClientHealthIndicatorProperties; -import org.springframework.cloud.client.discovery.health.reactive.ReactiveDiscoveryClientHealthIndicator; -import org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.ConditionalOnZookeeperDiscoveryEnabled; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * {@link org.springframework.cloud.client.discovery.ReactiveDiscoveryClient} configuration for - * Zookeeper. - * - * @author Tim Ysewyn - * @since 2.2.0 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnDiscoveryEnabled -@ConditionalOnReactiveDiscoveryEnabled -@ConditionalOnZookeeperDiscoveryEnabled -@AutoConfigureAfter({ ReactiveCompositeDiscoveryClientAutoConfiguration.class, ZookeeperAutoConfiguration.class}) -@AutoConfigureBefore(ReactiveCommonsClientAutoConfiguration.class) -public class ZookeeperReactiveDiscoveryClientConfiguration { - - @Autowired(required = false) - private ZookeeperDependencies zookeeperDependencies; - - @Bean - @ConditionalOnMissingBean - public ZookeeperReactiveDiscoveryClient zookeeperReactiveDiscoveryClient(ServiceDiscovery serviceDiscovery, - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - return new ZookeeperReactiveDiscoveryClient(serviceDiscovery, zookeeperDependencies, zookeeperDiscoveryProperties); - } - - @Bean - @ConditionalOnClass(name = "org.springframework.boot.actuate.health.ReactiveHealthIndicator") - @ConditionalOnDiscoveryHealthIndicatorEnabled - public ReactiveDiscoveryClientHealthIndicator zookeeperReactiveDiscoveryClientHealthIndicator( - ZookeeperReactiveDiscoveryClient client, - DiscoveryClientHealthIndicatorProperties properties) { - return new ReactiveDiscoveryClientHealthIndicator(client, properties); - } -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcher.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcher.java deleted file mode 100755 index 597aaab2c..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcher.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.curator.x.discovery.ServiceCache; -import org.apache.curator.x.discovery.ServiceDiscovery; - -import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependency; -import org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier; -import org.springframework.context.ApplicationListener; -import org.springframework.util.ReflectionUtils; - -/** - * This Dependency Watcher will verify the presence of dependencies upon startup and - * registers listeners to changing of state of dependencies during the application's - * lifecycle. - * - * @author Marcin Grzejszczak - * @author Michal Chmielarz, 4financeIT - * @since 1.0.0 - * @see DependencyPresenceOnStartupVerifier - * @see DependencyWatcherListener - */ -public class DefaultDependencyWatcher implements DependencyRegistrationHookProvider, - ApplicationListener> { - - private final Map> dependencyRegistry = new ConcurrentHashMap<>(); - - private final List listeners; - - private ServiceDiscovery serviceDiscovery; - - private final DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier; - - private final ZookeeperDependencies zookeeperDependencies; - - public DefaultDependencyWatcher(ServiceDiscovery serviceDiscovery, - DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier, - List dependencyWatcherListeners, - ZookeeperDependencies zookeeperDependencies) { - this.serviceDiscovery = serviceDiscovery; - this.dependencyPresenceOnStartupVerifier = dependencyPresenceOnStartupVerifier; - this.listeners = dependencyWatcherListeners; - this.zookeeperDependencies = zookeeperDependencies; - } - - @Override - public void onApplicationEvent(InstanceRegisteredEvent event) { - registerDependencyRegistrationHooks(); - } - - @Override - public void registerDependencyRegistrationHooks() { - for (ZookeeperDependency zookeeperDependency : this.zookeeperDependencies - .getDependencyConfigurations()) { - String dependencyPath = zookeeperDependency.getPath(); - ServiceCache serviceCache = getServiceDiscovery().serviceCacheBuilder() - .name(dependencyPath).build(); - try { - serviceCache.start(); - } - catch (Exception e) { - ReflectionUtils.rethrowRuntimeException(e); - } - this.dependencyPresenceOnStartupVerifier.verifyDependencyPresence( - dependencyPath, serviceCache, zookeeperDependency.isRequired()); - this.dependencyRegistry.put(dependencyPath, serviceCache); - serviceCache.addListener(new DependencyStateChangeListenerRegistry( - this.listeners, dependencyPath, serviceCache)); - } - } - - private ServiceDiscovery getServiceDiscovery() { - return this.serviceDiscovery; - } - - @Override - public void clearDependencyRegistrationHooks() throws IOException { - for (ServiceCache cache : this.dependencyRegistry.values()) { - cache.close(); - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyRegistrationHookProvider.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyRegistrationHookProvider.java deleted file mode 100644 index 6280d1423..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyRegistrationHookProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher; - -import java.io.IOException; - -/** - * Implementations of this interface are required to register dependency registration - * hooks on startup and their cleaning upon application context shutdown. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -public interface DependencyRegistrationHookProvider { - - /** - * Register hooks upon dependencies registration. - * @throws Exception if registration fails. - */ - void registerDependencyRegistrationHooks() throws Exception; - - /** - * Unregister hooks upon dependencies registration. - * @throws IOException if clearing fails. - */ - void clearDependencyRegistrationHooks() throws IOException; - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyState.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyState.java deleted file mode 100755 index 6999025c5..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyState.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher; - -/** - * Represents a dependency's Zookeeper connection state. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -public enum DependencyState { - - /** - * valid states. - */ - CONNECTED, DISCONNECTED - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyStateChangeListenerRegistry.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyStateChangeListenerRegistry.java deleted file mode 100755 index 2e4e498e8..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyStateChangeListenerRegistry.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.x.discovery.ServiceCache; -import org.apache.curator.x.discovery.details.ServiceCacheListener; - -/** - * Informs all the DependencyWatcherListeners that a dependency's state has changed. - * - * @author Marcin Grzejszczak - * @author Tomasz Nurkiewicz, 4financeIT - * @since 1.0.0 - */ -public class DependencyStateChangeListenerRegistry implements ServiceCacheListener { - - private static final Log log = LogFactory - .getLog(DependencyStateChangeListenerRegistry.class); - - private final List listeners; - - private final String dependencyName; - - private final ServiceCache serviceCache; - - public DependencyStateChangeListenerRegistry( - List listeners, String dependencyName, - ServiceCache serviceCache) { - this.listeners = listeners; - this.dependencyName = dependencyName; - this.serviceCache = serviceCache; - } - - @Override - public void cacheChanged() { - DependencyState state = this.serviceCache.getInstances().isEmpty() - ? DependencyState.DISCONNECTED : DependencyState.CONNECTED; - logCurrentState(state); - informListeners(state); - } - - private void logCurrentState(DependencyState dependencyState) { - log.info("Service cache state change for '" + this.dependencyName - + "' instances, current service state: " + dependencyState); - } - - private void informListeners(DependencyState state) { - for (DependencyWatcherListener listener : this.listeners) { - listener.stateChanged(this.dependencyName, state); - } - } - - @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) { - // TODO do something or ignore for what is worth - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherAutoConfiguration.java deleted file mode 100644 index e3dbd6614..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherAutoConfiguration.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.curator.x.discovery.ServiceDiscovery; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.discovery.dependency.ConditionalOnDependenciesPassed; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependenciesAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.watcher.presence.DefaultDependencyPresenceOnStartupVerifier; -import org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Provides hooks for observing dependency lifecycle in Zookeeper. Needs custom - * dependencies to be set in order to work. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - * @see ZookeeperDependencies - */ -@Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties -@ConditionalOnZookeeperEnabled -@ConditionalOnDependenciesPassed -@AutoConfigureAfter(ZookeeperDependenciesAutoConfiguration.class) -public class DependencyWatcherAutoConfiguration { - - @Autowired(required = false) - private List dependencyWatcherListeners = new ArrayList<>(); - - @Bean - @ConditionalOnMissingBean - public DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier() { - return new DefaultDependencyPresenceOnStartupVerifier(); - } - - @Bean(destroyMethod = "clearDependencyRegistrationHooks") - @ConditionalOnMissingBean - public DependencyRegistrationHookProvider dependencyWatcher( - ServiceDiscovery serviceDiscovery, - DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier, - ZookeeperDependencies zookeeperDependencies) { - return new DefaultDependencyWatcher(serviceDiscovery, - dependencyPresenceOnStartupVerifier, this.dependencyWatcherListeners, - zookeeperDependencies); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherListener.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherListener.java deleted file mode 100755 index 81cc09faf..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherListener.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher; - -/** - * Performs logic upon change of state of a dependency {@link DependencyState} in the - * service discovery system. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - * @see org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies - */ -public interface DependencyWatcherListener { - - /** - * Method executed upon state change of a dependency. - * @param dependencyName - alias from microservice configuration - * @param newState - new state of the dependency - */ - void stateChanged(String dependencyName, DependencyState newState); - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifier.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifier.java deleted file mode 100644 index 851efeea5..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifier.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher.presence; - -/** - * By default passes logging dependency checker in order not to shutdown the application - * if dependency is missing. - * - * @author Marcin Grzejszczak - * @see LogMissingDependencyChecker - * @version 1.0.0 - */ -public class DefaultDependencyPresenceOnStartupVerifier - extends DependencyPresenceOnStartupVerifier { - - public DefaultDependencyPresenceOnStartupVerifier() { - super(new LogMissingDependencyChecker()); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifier.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifier.java deleted file mode 100644 index aaa3cc3a2..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifier.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher.presence; - -import org.apache.curator.x.discovery.ServiceCache; - -/** - * Verifier that checks for presence of mandatory dependencies and delegates to an - * optional presence checker verification of presence of optional dependencies. - * - * The default implementation of required dependencies will result in shutting down of the - * application if the dependency is missing. - * - * @author Marcin Grzejszczak - * @author Tomasz Szymanski, 4financeIT - * @see FailOnMissingDependencyChecker - * @version 1.0.0 - */ -public abstract class DependencyPresenceOnStartupVerifier { - - private static final PresenceChecker MANDATORY_DEPENDENCY_CHECKER = new FailOnMissingDependencyChecker(); - - private final PresenceChecker optionalDependencyChecker; - - public DependencyPresenceOnStartupVerifier( - PresenceChecker optionalDependencyChecker) { - this.optionalDependencyChecker = optionalDependencyChecker; - } - - @SuppressWarnings("unchecked") - public void verifyDependencyPresence(String dependencyName, - @SuppressWarnings("rawtypes") ServiceCache serviceCache, boolean required) { - if (required) { - MANDATORY_DEPENDENCY_CHECKER.checkPresence(dependencyName, - serviceCache.getInstances()); - } - else { - this.optionalDependencyChecker.checkPresence(dependencyName, - serviceCache.getInstances()); - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/FailOnMissingDependencyChecker.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/FailOnMissingDependencyChecker.java deleted file mode 100755 index 04ee125b1..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/FailOnMissingDependencyChecker.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher.presence; - -import java.util.List; - -import org.apache.curator.x.discovery.ServiceInstance; - -/** - * Will result in throwing an exception if there are no running instances of the - * dependency. - * - * @author Marcin Grzejszczak - * @author Adam Chudzik, 4financeIT - * @since 1.0.0 - */ -public class FailOnMissingDependencyChecker implements PresenceChecker { - - @Override - public void checkPresence(String dependencyName, - List> serviceInstances) { - if (serviceInstances.isEmpty()) { - throw new NoInstancesRunningException(dependencyName); - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/LogMissingDependencyChecker.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/LogMissingDependencyChecker.java deleted file mode 100755 index a35c0e4af..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/LogMissingDependencyChecker.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher.presence; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.x.discovery.ServiceInstance; - -/** - * Will log the missing microservice dependency. - * - * @author Marcin Grzejszczak - * @author Tomasz Dziurko, 4financeIT - * @since 1.0.0 - */ -public class LogMissingDependencyChecker implements PresenceChecker { - - private static final Log log = LogFactory.getLog(LogMissingDependencyChecker.class); - - @Override - public void checkPresence(String dependencyName, - List> serviceInstances) { - if (serviceInstances.isEmpty()) { - log.warn("Microservice dependency with name [" + dependencyName - + "] is missing."); - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/NoInstancesRunningException.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/NoInstancesRunningException.java deleted file mode 100755 index 9a5429c63..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/NoInstancesRunningException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher.presence; - -/** - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -public class NoInstancesRunningException extends RuntimeException { - - public NoInstancesRunningException(String dependencyName) { - super("Required microservice dependency with name [" + dependencyName - + "] is missing"); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/PresenceChecker.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/PresenceChecker.java deleted file mode 100755 index 30e84ca50..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/PresenceChecker.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher.presence; - -import java.util.List; - -import org.apache.curator.x.discovery.ServiceInstance; - -/** - * The implementation of this interface will be called upon checking if a dependency with - * a given name is present upon startup within the provided service instances. - * - * @author Marcin Grzejszczak - * @since 1.0.0 - */ -public interface PresenceChecker { - - /** - * Checks if a given dependency is present. - * @param dependencyName Name of the dependency. - * @param serviceInstances - instances to check the dependency for. - */ - void checkPresence(String dependencyName, List> serviceInstances); - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java deleted file mode 100644 index 5a54c0435..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.serviceregistry; - -import java.net.URI; -import java.util.Collections; -import java.util.Map; - -import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.curator.x.discovery.ServiceInstanceBuilder; -import org.apache.curator.x.discovery.ServiceType; -import org.apache.curator.x.discovery.UriSpec; - -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; - -import static org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties.DEFAULT_URI_SPEC; - -/** - * {@link org.springframework.cloud.client.serviceregistry.Registration} that lazily - * builds a {@link ServiceInstance} so the port can by dynamically set (for instance, when - * the user wants a dynamic port for spring boot. - * - * @author Spencer Gibb - */ -public class ServiceInstanceRegistration implements ZookeeperRegistration { - - public static RegistrationBuilder builder() { - try { - return new RegistrationBuilder(ServiceInstance.builder()); - } - catch (Exception e) { - throw new RuntimeException("Error creating ServiceInstanceBuilder", e); - } - } - - public static RegistrationBuilder builder( - ServiceInstanceBuilder builder) { - return new RegistrationBuilder(builder); - } - - protected ServiceInstance serviceInstance; - - protected ServiceInstanceBuilder builder; - - public ServiceInstanceRegistration( - ServiceInstanceBuilder builder) { - this.builder = builder; - } - - public ServiceInstance getServiceInstance() { - if (this.serviceInstance == null) { - build(); - } - return this.serviceInstance; - } - - protected void build() { - this.serviceInstance = this.builder.build(); - } - - @Override - public String getServiceId() { - if (this.serviceInstance == null) { - return null; - } - return this.serviceInstance.getName(); - } - - public int getPort() { - if (this.serviceInstance == null) { - return 0; - } - return this.serviceInstance.getPort(); - } - - public void setPort(int port) { - this.builder.port(port); - this.build(); - } - - @Override - public String getHost() { - if (this.serviceInstance == null) { - return null; - } - return this.serviceInstance.getAddress(); - } - - @Override - public boolean isSecure() { - if (this.serviceInstance == null) { - return false; - } - return this.serviceInstance.getSslPort() != null; - } - - @Override - public URI getUri() { - if (this.serviceInstance == null) { - return null; - } - return URI.create(this.serviceInstance.buildUriSpec()); - } - - @Override - public Map getMetadata() { - if (this.serviceInstance == null || this.serviceInstance.getPayload() == null) { - return Collections.emptyMap(); - } - return this.serviceInstance.getPayload().getMetadata(); - } - - /** - * A builder for ServiceInstanceRegistration. - */ - public static class RegistrationBuilder { - - protected ServiceInstanceBuilder builder; - - public RegistrationBuilder(ServiceInstanceBuilder builder) { - this.builder = builder; - } - - public ServiceInstanceRegistration build() { - return new ServiceInstanceRegistration(this.builder); - } - - public RegistrationBuilder name(String name) { - this.builder.name(name); - return this; - } - - public RegistrationBuilder address(String address) { - this.builder.address(address); - return this; - } - - public RegistrationBuilder id(String id) { - this.builder.id(id); - return this; - } - - public RegistrationBuilder port(int port) { - this.builder.port(port); - return this; - } - - public RegistrationBuilder sslPort(int port) { - this.builder.sslPort(port); - return this; - } - - public RegistrationBuilder payload(ZookeeperInstance payload) { - this.builder.payload(payload); - return this; - } - - public RegistrationBuilder serviceType(ServiceType serviceType) { - this.builder.serviceType(serviceType); - return this; - } - - public RegistrationBuilder registrationTimeUTC(long registrationTimeUTC) { - this.builder.registrationTimeUTC(registrationTimeUTC); - return this; - } - - public RegistrationBuilder uriSpec(UriSpec uriSpec) { - this.builder.uriSpec(uriSpec); - return this; - } - - public RegistrationBuilder uriSpec(String uriSpec) { - this.builder.uriSpec(new UriSpec(uriSpec)); - return this; - } - - public RegistrationBuilder defaultUriSpec() { - this.builder.uriSpec(new UriSpec(DEFAULT_URI_SPEC)); - return this; - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistration.java deleted file mode 100644 index 33f67ea93..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistration.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.serviceregistry; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; - -/** - * Zookeeper {@link AbstractAutoServiceRegistration} that uses - * {@link ZookeeperServiceRegistry} to register and de-register instances. - * - * @author Spencer Gibb - * @since 1.0.0 - */ -public class ZookeeperAutoServiceRegistration - extends AbstractAutoServiceRegistration { - - private static final Log log = LogFactory - .getLog(ZookeeperAutoServiceRegistration.class); - - private ZookeeperRegistration registration; - - private ZookeeperDiscoveryProperties properties; - - public ZookeeperAutoServiceRegistration(ZookeeperServiceRegistry registry, - ZookeeperRegistration registration, ZookeeperDiscoveryProperties properties) { - this(registry, registration, properties, null); - } - - public ZookeeperAutoServiceRegistration(ZookeeperServiceRegistry registry, - ZookeeperRegistration registration, ZookeeperDiscoveryProperties properties, - AutoServiceRegistrationProperties arProperties) { - super(registry, arProperties); - this.registration = registration; - this.properties = properties; - if (this.properties.getInstancePort() != null) { - this.registration.setPort(this.properties.getInstancePort()); - } - } - - @Override - protected ZookeeperRegistration getRegistration() { - return this.registration; - } - - @Override - protected ZookeeperRegistration getManagementRegistration() { - return null; - } - - @Override - protected void register() { - if (!this.properties.isRegister()) { - log.debug("Registration disabled."); - return; - } - if (this.registration.getPort() == 0) { - this.registration.setPort(getPort().get()); - } - super.register(); - } - - @Override - protected void deregister() { - if (!this.properties.isRegister()) { - return; - } - super.deregister(); - } - - @Override - protected boolean isEnabled() { - return this.properties.isEnabled(); - } - - @Override - protected Object getConfiguration() { - return this.properties; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationAutoConfiguration.java deleted file mode 100644 index 4723ede9b..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationAutoConfiguration.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.serviceregistry; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.ConditionalOnZookeeperDiscoveryEnabled; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.serviceregistry.ServiceInstanceRegistration.RegistrationBuilder; -import org.springframework.cloud.zookeeper.support.StatusConstants; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; - -/** - * @author Spencer Gibb - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnMissingBean(type = "org.springframework.cloud.zookeeper.discovery.ZookeeperLifecycle") -@ConditionalOnZookeeperDiscoveryEnabled -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) -@AutoConfigureAfter({ ZookeeperServiceRegistryAutoConfiguration.class }) -@AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class, - ZookeeperDiscoveryAutoConfiguration.class }) -public class ZookeeperAutoServiceRegistrationAutoConfiguration { - - @Bean - public ZookeeperAutoServiceRegistration zookeeperAutoServiceRegistration( - ZookeeperServiceRegistry registry, ZookeeperRegistration registration, - ZookeeperDiscoveryProperties properties) { - return new ZookeeperAutoServiceRegistration(registry, registration, properties); - } - - @Bean - @ConditionalOnMissingBean(ZookeeperRegistration.class) - public ServiceInstanceRegistration serviceInstanceRegistration( - ApplicationContext context, ZookeeperDiscoveryProperties properties) { - String appName = context.getEnvironment().getProperty("spring.application.name", - "application"); - String host = properties.getInstanceHost(); - if (!StringUtils.hasText(host)) { - throw new IllegalStateException("instanceHost must not be empty"); - } - - properties.getMetadata().put(StatusConstants.INSTANCE_STATUS_KEY, properties.getInitialStatus()); - - ZookeeperInstance zookeeperInstance = new ZookeeperInstance(context.getId(), - appName, properties.getMetadata()); - RegistrationBuilder builder = ServiceInstanceRegistration.builder().address(host) - .name(appName).payload(zookeeperInstance) - .uriSpec(properties.getUriSpec()); - - if (properties.getInstanceSslPort() != null) { - builder.sslPort(properties.getInstanceSslPort()); - } - if (properties.getInstanceId() != null) { - builder.id(properties.getInstanceId()); - } - - // TODO add customizer? - - return builder.build(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperRegistration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperRegistration.java deleted file mode 100644 index ee5c06fc5..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperRegistration.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.serviceregistry; - -import org.apache.curator.x.discovery.ServiceInstance; - -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; - -/** - * @author Spencer Gibb - */ -public interface ZookeeperRegistration extends Registration { - - ServiceInstance getServiceInstance(); - - void setPort(int port); - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistry.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistry.java deleted file mode 100644 index e6cc36200..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistry.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.serviceregistry; - -import java.io.Closeable; -import java.io.IOException; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceInstance; - -import org.springframework.beans.factory.SmartInitializingSingleton; -import org.springframework.cloud.client.serviceregistry.ServiceRegistry; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; - -import static org.springframework.cloud.zookeeper.support.StatusConstants.INSTANCE_STATUS_KEY; -import static org.springframework.cloud.zookeeper.support.StatusConstants.STATUS_UP; -import static org.springframework.util.ReflectionUtils.rethrowRuntimeException; - -/** - * @author Spencer Gibb - */ -public class ZookeeperServiceRegistry implements ServiceRegistry, - SmartInitializingSingleton, Closeable { - - // private AtomicBoolean started = new AtomicBoolean(); - - protected CuratorFramework curator; - - protected ZookeeperDiscoveryProperties properties; - - // protected InstanceSerializer instanceSerializer; - private ServiceDiscovery serviceDiscovery; - - public ZookeeperServiceRegistry( - ServiceDiscovery serviceDiscovery) { - this.serviceDiscovery = serviceDiscovery; - } - - /** - * TODO: add when ZookeeperServiceDiscovery is removed One can override this method to - * provide custom way of registering {@link ServiceDiscovery} - */ - /* - * private void configureServiceDiscovery() { - * this.zookeeperServiceDiscovery.configureServiceDiscovery(this. - * zookeeperServiceDiscovery.getServiceDiscoveryRef(), this.curator, this.properties, - * this.instanceSerializer, this.zookeeperServiceDiscovery.getServiceInstanceRef()); } - */ - - @Override - public void register(ZookeeperRegistration registration) { - try { - getServiceDiscovery().registerService(registration.getServiceInstance()); - } - catch (Exception e) { - rethrowRuntimeException(e); - } - } - - private ServiceDiscovery getServiceDiscovery() { - return this.serviceDiscovery; - } - - @Override - public void deregister(ZookeeperRegistration registration) { - try { - getServiceDiscovery().unregisterService(registration.getServiceInstance()); - } - catch (Exception e) { - rethrowRuntimeException(e); - } - } - - @Override - public void afterSingletonsInstantiated() { - try { - getServiceDiscovery().start(); - } - catch (Exception e) { - rethrowRuntimeException(e); - } - } - - @Override - public void close() { - try { - getServiceDiscovery().close(); - } - catch (IOException e) { - rethrowRuntimeException(e); - } - } - - @Override - public void setStatus(ZookeeperRegistration registration, String status) { - ServiceInstance serviceInstance = registration - .getServiceInstance(); - ZookeeperInstance instance = serviceInstance.getPayload(); - instance.getMetadata().put(INSTANCE_STATUS_KEY, status); - try { - getServiceDiscovery().updateService(serviceInstance); - } - catch (Exception e) { - ReflectionUtils.rethrowRuntimeException(e); - } - } - - @Override - public Object getStatus(ZookeeperRegistration registration) { - ZookeeperInstance instance = registration.getServiceInstance().getPayload(); - String instanceStatus = instance.getMetadata().get(INSTANCE_STATUS_KEY); - - if (!StringUtils.hasText(instanceStatus)) { - instanceStatus = STATUS_UP; - } - return instanceStatus; - } - - @Deprecated - protected CuratorFramework getCurator() { - return this.curator; - } - - /* - * protected AtomicReference> - * getServiceDiscoveryRef() { return - * this.zookeeperServiceDiscovery.getServiceDiscoveryRef(); } - */ - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistryAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistryAutoConfiguration.java deleted file mode 100644 index d07216ca5..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistryAutoConfiguration.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.serviceregistry; - -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.details.InstanceSerializer; -import org.apache.curator.x.discovery.details.JsonInstanceSerializer; - -import org.springframework.beans.BeansException; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.zookeeper.discovery.ConditionalOnZookeeperDiscoveryEnabled; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author Spencer Gibb - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnZookeeperDiscoveryEnabled -@ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", matchIfMissing = true) -@AutoConfigureBefore(ServiceRegistryAutoConfiguration.class) -public class ZookeeperServiceRegistryAutoConfiguration - implements ApplicationContextAware { - - private ApplicationContext context; - - @Override - public void setApplicationContext(ApplicationContext context) throws BeansException { - this.context = context; - } - - @Bean - @ConditionalOnBean(ServiceDiscovery.class) - @SuppressWarnings("unchecked") - public ZookeeperServiceRegistry zookeeperServiceRegistry() { - return new ZookeeperServiceRegistry(this.context.getBean(ServiceDiscovery.class)); - } - - @Bean - @ConditionalOnMissingBean - public InstanceSerializer instanceSerializer() { - return new JsonInstanceSerializer<>(ZookeeperInstance.class); - } - - @Bean - @ConditionalOnMissingBean - public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties( - InetUtils inetUtils) { - return new ZookeeperDiscoveryProperties(inetUtils); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/CuratorServiceDiscoveryAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/CuratorServiceDiscoveryAutoConfiguration.java deleted file mode 100644 index c3bd12e30..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/CuratorServiceDiscoveryAutoConfiguration.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.support; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; -import org.apache.curator.x.discovery.details.InstanceSerializer; -import org.apache.curator.x.discovery.details.JsonInstanceSerializer; - -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; -import org.springframework.cloud.zookeeper.discovery.ConditionalOnZookeeperDiscoveryEnabled; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistryAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author Spencer Gibb - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnDiscoveryEnabled -@ConditionalOnZookeeperDiscoveryEnabled -@AutoConfigureBefore({ ZookeeperDiscoveryAutoConfiguration.class, - ZookeeperServiceRegistryAutoConfiguration.class }) -public class CuratorServiceDiscoveryAutoConfiguration { - - @Bean - @ConditionalOnMissingBean(ServiceDiscoveryCustomizer.class) - public DefaultServiceDiscoveryCustomizer defaultServiceDiscoveryCustomizer( - CuratorFramework curator, ZookeeperDiscoveryProperties properties, - InstanceSerializer serializer) { - return new DefaultServiceDiscoveryCustomizer(curator, properties, serializer); - } - - @Bean - @ConditionalOnMissingBean - public InstanceSerializer deprecatedInstanceSerializer() { - return new JsonInstanceSerializer<>(ZookeeperInstance.class); - } - - @Bean - @ConditionalOnMissingBean - public ServiceDiscovery curatorServiceDiscovery( - ServiceDiscoveryCustomizer customizer) { - return customizer - .customize(ServiceDiscoveryBuilder.builder(ZookeeperInstance.class)); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/DefaultServiceDiscoveryCustomizer.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/DefaultServiceDiscoveryCustomizer.java deleted file mode 100644 index cbaf3af9e..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/DefaultServiceDiscoveryCustomizer.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.support; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; -import org.apache.curator.x.discovery.details.InstanceSerializer; - -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; - -/** - * @author Spencer Gibb - */ -public class DefaultServiceDiscoveryCustomizer implements ServiceDiscoveryCustomizer { - - protected CuratorFramework curator; - - protected ZookeeperDiscoveryProperties properties; - - protected InstanceSerializer instanceSerializer; - - public DefaultServiceDiscoveryCustomizer(CuratorFramework curator, - ZookeeperDiscoveryProperties properties, - InstanceSerializer instanceSerializer) { - this.curator = curator; - this.properties = properties; - this.instanceSerializer = instanceSerializer; - } - - @Override - public ServiceDiscovery customize( - ServiceDiscoveryBuilder builder) { - // @formatter:off - return builder - .client(this.curator) - .basePath(this.properties.getRoot()) - .serializer(this.instanceSerializer) - .build(); - // @formatter:on - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/ServiceDiscoveryCustomizer.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/ServiceDiscoveryCustomizer.java deleted file mode 100644 index cabe4d70c..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/ServiceDiscoveryCustomizer.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.support; - -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; - -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; - -/** - * @author Spencer Gibb - */ -public interface ServiceDiscoveryCustomizer { - - ServiceDiscovery customize( - ServiceDiscoveryBuilder builder); - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/StatusConstants.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/StatusConstants.java deleted file mode 100644 index 5e29a15ec..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/StatusConstants.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.support; - -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; - -/** - * @author Spencer Gibb - */ -public final class StatusConstants { - - private StatusConstants() { - } - - /** - * Key to the - * {@link ZookeeperInstance#getMetadata()} - * map. - */ - public static final String INSTANCE_STATUS_KEY = "instance_status"; - - /** - * UP value for {@link StatusConstants#INSTANCE_STATUS_KEY} key. - */ - public static final String STATUS_UP = "UP"; - - /** - * OUT_OF_SERVICE value for {@link StatusConstants#INSTANCE_STATUS_KEY} key. - */ - public static final String STATUS_OUT_OF_SERVICE = "OUT_OF_SERVICE"; - -} diff --git a/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring.factories b/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring.factories deleted file mode 100644 index bc1944e85..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,9 +0,0 @@ -# Environment Post Processors -org.springframework.boot.env.EnvironmentPostProcessor=\ -org.springframework.cloud.zookeeper.discovery.dependency.DependencyEnvironmentPostProcessor - -org.springframework.cloud.bootstrap.BootstrapConfiguration=\ -org.springframework.cloud.zookeeper.discovery.configclient.ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration - -org.springframework.boot.BootstrapRegistryInitializer=\ -org.springframework.cloud.zookeeper.discovery.configclient.ZookeeperConfigServerBootstrapper \ No newline at end of file diff --git a/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring/aot.factories b/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring/aot.factories deleted file mode 100644 index cd162f1ba..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring/aot.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.aot.hint.RuntimeHintsRegistrar=\ -org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryHints \ No newline at end of file diff --git a/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports deleted file mode 100644 index 260956de6..000000000 --- a/spring-cloud-zookeeper-discovery/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ /dev/null @@ -1,11 +0,0 @@ -org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryAutoConfiguration -org.springframework.cloud.zookeeper.discovery.dependency.DependencyFeignClientAutoConfiguration -org.springframework.cloud.zookeeper.discovery.dependency.DependencyRestTemplateAutoConfiguration -org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependenciesAutoConfiguration -org.springframework.cloud.zookeeper.discovery.watcher.DependencyWatcherAutoConfiguration -org.springframework.cloud.zookeeper.serviceregistry.ZookeeperAutoServiceRegistrationAutoConfiguration -org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistryAutoConfiguration -org.springframework.cloud.zookeeper.support.CuratorServiceDiscoveryAutoConfiguration -org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryClientConfiguration -org.springframework.cloud.zookeeper.discovery.LoadBalancerZookeeperAutoConfiguration -org.springframework.cloud.zookeeper.discovery.reactive.ZookeeperReactiveDiscoveryClientConfiguration \ No newline at end of file diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/TestServiceRegistrar.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/TestServiceRegistrar.java deleted file mode 100644 index e20866b1b..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/TestServiceRegistrar.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.io.IOException; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; -import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.curator.x.discovery.UriSpec; - -public class TestServiceRegistrar { - - private final int serverPort; - - private final CuratorFramework curatorFramework; - - private final ServiceDiscovery serviceDiscovery; - - public TestServiceRegistrar(int serverPort, CuratorFramework curatorFramework) { - this.serverPort = serverPort; - this.curatorFramework = curatorFramework; - this.serviceDiscovery = serviceDiscovery(); - } - - public void start() { - try { - this.serviceDiscovery.start(); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - - public ServiceInstance serviceInstance() { - try { - return ServiceInstance.builder() - .uriSpec(new UriSpec("{scheme}://{address}:{port}/")) - .address("localhost").port(this.serverPort).name("testInstance") - .build(); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - - public ServiceDiscovery serviceDiscovery() { - return ServiceDiscoveryBuilder.builder(Void.class).basePath("/services") - .client(this.curatorFramework).thisInstance(serviceInstance()).build(); - } - - public void stop() { - try { - this.serviceDiscovery.close(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoRegistrationFalseTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoRegistrationFalseTests.java deleted file mode 100644 index fce391371..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoRegistrationFalseTests.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Spencer Gibb - * @author Olga Maciaszek-Sharma - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoveryAutoRegistrationFalseTests.Config.class, properties = { - "spring.application.name=testzkautoregfalse", - "debug=true" }, webEnvironment = RANDOM_PORT) -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -@DirtiesContext -public class ZookeeperDiscoveryAutoRegistrationFalseTests { - - @Autowired - DiscoveryClient discoveryClient; - - @Value("${spring.application.name}") - String springAppName; - - @Test - public void discovery_client_is_zookeeper() { - // given: this.discoveryClient - // expect: - then(discoveryClient).isInstanceOf(CompositeDiscoveryClient.class); - CompositeDiscoveryClient composite = (CompositeDiscoveryClient) discoveryClient; - List discoveryClients = composite.getDiscoveryClients(); - DiscoveryClient first = discoveryClients.get(0); - then(first).isInstanceOf(ZookeeperDiscoveryClient.class); - } - - @Test - public void application_should_not_have_been_registered() { - // given: - List instances = this.discoveryClient - .getInstances(springAppName); - // expect: - then(instances).isEmpty(); - } - - @Configuration - @EnableAutoConfiguration - @Import(CommonTestConfig.class) - @EnableDiscoveryClient(autoRegister = false) - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientTests.java deleted file mode 100644 index 40f61ad40..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientTests.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.List; - -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.zookeeper.KeeperException.NoNodeException; -import org.junit.Test; - -import org.springframework.cloud.client.ServiceInstance; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author Marcin Grzejszczak - */ -public class ZookeeperDiscoveryClientTests { - - @Test - public void should_return_an_empty_list_of_services_if_service_discovery_is_null() { - // given: - ServiceDiscovery serviceDiscovery = mock( - ServiceDiscovery.class); - ZookeeperDiscoveryClient zookeeperDiscoveryClient = new ZookeeperDiscoveryClient( - serviceDiscovery, null, new ZookeeperDiscoveryProperties()); - // when: - List services = zookeeperDiscoveryClient.getServices(); - // then: - then(services).isEmpty(); - } - - @Test - public void getServicesShouldReturnEmptyWhenNoNodeException() throws Exception { - // given: - ServiceDiscovery serviceDiscovery = mock( - ServiceDiscovery.class); - when(serviceDiscovery.queryForNames()).thenThrow(new NoNodeException()); - ZookeeperDiscoveryClient discoveryClient = new ZookeeperDiscoveryClient( - serviceDiscovery, null, new ZookeeperDiscoveryProperties()); - // when: - List services = discoveryClient.getServices(); - // then: - then(services).isEmpty(); - } - - @Test - public void getInstancesshouldReturnEmptyWhenNoNodeException() throws Exception { - // given: - ServiceDiscovery serviceDiscovery = mock( - ServiceDiscovery.class); - when(serviceDiscovery.queryForInstances("myservice")) - .thenThrow(new NoNodeException()); - ZookeeperDiscoveryClient discoveryClient = new ZookeeperDiscoveryClient( - serviceDiscovery, null, new ZookeeperDiscoveryProperties()); - // when: - List instances = discoveryClient.getInstances("myservice"); - // then: - then(instances).isEmpty(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryDisabledTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryDisabledTests.java deleted file mode 100644 index 07c0487fa..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryDisabledTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import org.apache.curator.framework.CuratorFramework; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * @author Marcin Grzejszczak - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoveryDisabledTests.SomeApp.class, - webEnvironment = WebEnvironment.RANDOM_PORT, properties = { - "spring.cloud.zookeeper.discovery.enabled=false", "debug=true" }) -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperDiscoveryDisabledTests { - - @Test - public void should_start_the_context_with_discovery_disabled() { - } - - @Configuration - @EnableAutoConfiguration - @Import(CommonTestConfig.class) - static class SomeApp { - - @Bean - CuratorFramework curator() { - return null; - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorDisabledTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorDisabledTests.java deleted file mode 100644 index 800d65166..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorDisabledTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, properties = { "management.health.zookeeper.enabled=false", - "spring.cloud.service-registry.auto-registration.enabled=false" }) -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperDiscoveryHealthIndicatorDisabledTests { - - @Autowired(required = false) - private ZookeeperDiscoveryHealthIndicator healthIndicator; - - // Issue: #101 - ZookeeperDiscoveryHealthIndicator should be able to be disabled with - // a property - @Test - public void healthIndicatorDisabled() { - // when: - // then: - then(this.healthIndicator).isNull(); - } - - @SpringBootConfiguration - @EnableAutoConfiguration - @Import(CommonTestConfig.class) - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.java deleted file mode 100644 index 71b8dc39a..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.lang.invoke.MethodHandles; - -import jakarta.annotation.PostConstruct; -import jakarta.annotation.PreDestroy; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.framework.CuratorFramework; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.discovery.test.TestLoadBalancedClient; -import org.springframework.cloud.zookeeper.serviceregistry.ServiceInstanceRegistration; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistry; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Profile; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import static org.springframework.cloud.zookeeper.discovery.test.TestLoadBalancedClient.BASE_PATH; - -/** - * @author Marcin Grzejszczak - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.Config.class, - properties = "management.endpoints.web.exposure.include=*", webEnvironment = RANDOM_PORT) -@ActiveProfiles("nestedstructure") -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests { - - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); - - @Autowired - TestLoadBalancedClient testLoadBalancedClient; - - @Autowired - CuratorFramework curatorFramework; - - // Issue: #54 - ZookeeperDiscoveryHealthIndicator fails on nested structure - @Test - public void should_return_a_response_that_app_is_in_a_healthy_state_when_nested_folders_in_zookeeper_are_present() - throws Exception { - // when: - String response = this.testLoadBalancedClient.callService("me", BASE_PATH + "/health"); - // then: - log.info("Received response [" + response + "]"); - then(this.curatorFramework.getChildren().forPath("/services/me")).isNotEmpty(); - then(this.curatorFramework.getChildren().forPath("/services/a/b/c/d/anotherservice")).isNotEmpty(); - } - - @Configuration - @EnableAutoConfiguration - @Import(CommonTestConfig.class) - @Profile("nestedstructure") - static class Config { - - @Autowired - ZookeeperServiceRegistry serviceRegistry; - - private ZookeeperRegistration registration; - - @PostConstruct - void registerNestedDependency() { - try { - this.registration = ServiceInstanceRegistration.builder().defaultUriSpec().address("anyUrl").port(10) - .name("/a/b/c/d/anotherservice").build(); - this.serviceRegistry.register(registration); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - - @PreDestroy - void unregisterServiceDiscovery() { - this.serviceRegistry.deregister(this.registration); - } - - @Bean - TestLoadBalancedClient testLoadBalancedClient(@LoadBalanced RestTemplate restTemplate, - @Value("${spring.application.name}") String springAppName) { - return new TestLoadBalancedClient(restTemplate, springAppName); - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesIntegrationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesIntegrationTests.java deleted file mode 100644 index 7c51a3ccc..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesIntegrationTests.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - - -import org.junit.jupiter.api.Test; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ContextConfiguration; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author wmz7year - */ -@SpringBootTest(properties = { "spring.application.name=testZookeeperDiscovery", - "spring.cloud.service-registry.auto-registration.enabled=false", - "spring.cloud.zookeeper.discovery.instance-id=zkpropstestid-123", - "spring.cloud.zookeeper.discovery.preferIpAddress=true", - "spring.cloud.zookeeper.discovery.instanceIpAddress=1.1.1.1" }, - classes = ZookeeperDiscoveryPropertiesIntegrationTests.Config.class, - webEnvironment = WebEnvironment.RANDOM_PORT) -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperDiscoveryPropertiesIntegrationTests { - - @Autowired - private ZookeeperDiscoveryProperties discoveryProperties; - - @Test - public void testPreferIpAddress() { - assertThat(this.discoveryProperties.getInstanceId()) - .isEqualTo("zkpropstestid-123"); - assertThat(this.discoveryProperties.getInstanceHost()).isEqualTo("1.1.1.1"); - } - - @Configuration - @EnableAutoConfiguration - @Import(CommonTestConfig.class) - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTests.java deleted file mode 100644 index f45be911c..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTests.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.Arrays; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; - -import static org.assertj.core.api.BDDAssertions.then; - -@RunWith(Parameterized.class) -public class ZookeeperDiscoveryPropertiesTests { - - private String root; - - public ZookeeperDiscoveryPropertiesTests(String root) { - this.root = root; - } - - @Parameterized.Parameters(name = "With root {0}") - public static Iterable rootVariations() { - return Arrays.asList("es", "es/", "/es"); - } - - @Test - public void should_escape_root() { - // given: - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties = new ZookeeperDiscoveryProperties( - new InetUtils(new InetUtilsProperties())); - // when: - zookeeperDiscoveryProperties.setRoot(root); - // then: - then(zookeeperDiscoveryProperties.getRoot()).isEqualTo("/es"); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoverySecurePortTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoverySecurePortTests.java deleted file mode 100644 index 90d0c97de..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoverySecurePortTests.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Profile; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Marcin Grzejszczak - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoverySecurePortTests.Config.class, properties = { - "feign.hystrix.enabled=false", - "spring.cloud.zookeeper.discovery.uriSpec={scheme}://{address}:{port}/contextPath", - "spring.cloud.zookeeper.discovery.instance-ssl-port=8443" }, webEnvironment = RANDOM_PORT) -@ActiveProfiles("loadbalancer") -@DirtiesContext -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperDiscoverySecurePortTests { - - @Autowired - private LoadBalancerClient loadBalancerClient; - - @Autowired - private ZookeeperRegistration zookeeperRegistration; - - @Value("${spring.application.name}") - private String springAppName; - - @Test - public void isSecureIsTrue() { - ServiceInstance instance = this.loadBalancerClient.choose(this.springAppName); - then(instance.isSecure()).isTrue(); - } - - @Test - public void shouldSetServiceInstanceSslPort() { - then(this.zookeeperRegistration.getServiceInstance().getSslPort()) - .isEqualTo(8443); - } - - @Configuration - @EnableAutoConfiguration - @Import(CommonTestConfig.class) - @Profile("loadbalancer") - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryTests.java deleted file mode 100644 index d9b778844..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryTests.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.List; - -import com.jayway.awaitility.Awaitility; -import com.toomuchcoding.jsonassert.JsonPath; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.discovery.test.TestLoadBalancedClient; -import org.springframework.cloud.zookeeper.serviceregistry.ServiceInstanceRegistration; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Controller; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import static org.springframework.cloud.zookeeper.discovery.test.TestLoadBalancedClient.BASE_PATH; - -/** - * @author Marcin Grzejszczak - * @author Tim Ysewyn - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoveryTests.Config.class, properties = { - "spring.cloud.zookeeper.discovery.uri-spec={scheme}://{address}:{port}/contextPath", - "management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT) -@ActiveProfiles("loadbalancer") -@DirtiesContext -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperDiscoveryTests { - - @Autowired - TestLoadBalancedClient testLoadBalancedClient; - - @Autowired - DiscoveryClient discoveryClient; - - @Autowired - ServiceInstanceRegistration serviceDiscovery; - - @Value("${spring.application.name}") - String springAppName; - - @Autowired - IdUsingFeignClient idUsingFeignClient; - - @Autowired - Registration registration; - - @Test - public void should_find_the_app_by_its_name_via_LoadBalancer() { - // expect: - then(registeredServiceStatusViaServiceName()).isEqualTo("UP"); - } - - @Test - public void should_find_a_collaborator_via_discovery_client() { - // given: - List instances = this.discoveryClient - .getInstances(this.springAppName); - ServiceInstance instance = instances.get(0); - // expect: - then(registeredServiceStatus(instance)).isEqualTo("UP"); - then(instance.getInstanceId()).isEqualTo("loadbalancer-instance-id-123"); - then(instance.getMetadata().get("testMetadataKey")) - .isEqualTo("testMetadataValue"); - then(instance).isInstanceOf(ZookeeperServiceInstance.class); - ZookeeperServiceInstance zkInstance = (ZookeeperServiceInstance) instance; - then(zkInstance.getServiceInstance().getId()).isEqualTo("loadbalancer-instance-id-123"); - } - - @Test - public void should_present_application_name_as_id_of_the_service_instance() { - // given: - // expect: - then(this.springAppName).isEqualTo(this.registration.getServiceId()); - } - - @Test - public void should_service_instance_uri_match_uriSpec() { - // given: - // expect: - then(this.registration.getUri()).hasPath("/contextPath"); - } - - @Test - public void should_find_an_instance_using_feign_via_service_id() { - final IdUsingFeignClient idUsingFeignClient = this.idUsingFeignClient; - // expect: - Awaitility.await().until(() -> { - then(idUsingFeignClient.hi()).isNotEmpty(); - return true; - }); - } - - private String registeredServiceStatusViaServiceName() { - return JsonPath.builder(this.testLoadBalancedClient.thisHealthCheck()).field("status") - .read(String.class); - } - - private String registeredServiceStatus(ServiceInstance instance) { - return JsonPath.builder(this.testLoadBalancedClient.callOnUrl( - instance.getHost() + ":" + instance.getPort(), BASE_PATH + "/health")) - .field("status").read(String.class); - } - - @Test - public void should_properly_find_local_instance() { - // expect: - then(this.serviceDiscovery.getServiceInstance().getAddress()) - .isEqualTo(this.registration.getHost()); - } - - @FeignClient("loadBalancerApp") - public interface IdUsingFeignClient { - - @RequestMapping(method = RequestMethod.GET, value = "/hi") - String hi(); - - } - - @Configuration - @EnableAutoConfiguration - @Import(CommonTestConfig.class) - @EnableFeignClients(clients = { IdUsingFeignClient.class }) - @Profile("loadbalancer") - @RestController - static class Config { - - @Bean - TestLoadBalancedClient testLoadBalancedClient(@LoadBalanced RestTemplate restTemplate, - @Value("${spring.application.name}") String springAppName) { - return new TestLoadBalancedClient(restTemplate, springAppName); - } - - @RequestMapping("/hi") - public String hi() { - return "hi"; - } - - } - - @Controller - @Profile("loadbalancer") - class PingController { - - @RequestMapping("/ping") - String ping() { - return "pong"; - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLifecycleRegistrationDisabledTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLifecycleRegistrationDisabledTests.java deleted file mode 100644 index ec89e9719..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLifecycleRegistrationDisabledTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperLifecycleRegistrationDisabledTests.TestPropsConfig.class, properties = { - "spring.application.name=myTestNotRegisteredService", - "spring.cloud.zookeeper.discovery.register=false", - "spring.cloud.zookeeper.dependency.enabled=false" }, webEnvironment = RANDOM_PORT) -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperLifecycleRegistrationDisabledTests { - - @Autowired - private ZookeeperDiscoveryClient client; - - @Test - public void contextLoads() { - List instances = this.client - .getInstances("myTestNotRegisteredService"); - assertThat(instances.isEmpty()).as("service was registered").isTrue(); - } - - @Configuration - @EnableAutoConfiguration - @Import({ CommonTestConfig.class }) - static class TestPropsConfig { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeprDiscoveryNonWebAppTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeprDiscoveryNonWebAppTests.java deleted file mode 100644 index fd1b2f990..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeprDiscoveryNonWebAppTests.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery; - -import com.jayway.awaitility.Awaitility; -import org.apache.curator.test.TestingServer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.test.TestSocketUtils; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.BDDAssertions.then; - -/** - * Test for gh-91, using s-c-zookeeper in a non-web app. - * - * @author Marcin Grzejszczak - */ -public class ZookeeprDiscoveryNonWebAppTests { - - TestingServer server; - - String connectionString; - - @Before - public void setup() throws Exception { - this.server = new TestingServer(TestSocketUtils.findAvailableTcpPort()); - this.connectionString = "--spring.cloud.zookeeper.connectString=" - + this.server.getConnectString(); - } - - @After - public void cleanup() throws Exception { - this.server.close(); - } - - @Test - public void should_work_when_using_web_client_without_the_web_environment() { - SpringApplication producerApp = new SpringApplicationBuilder(HelloProducer.class) - .web(WebApplicationType.SERVLET).build(); - SpringApplication clientApplication = new SpringApplicationBuilder( - HelloClient.class).web(WebApplicationType.NONE).build(); - - try (ConfigurableApplicationContext producerContext = producerApp.run( - this.connectionString, "--server.port=0", - "--spring.application.name=hello-world", "--debug")) { - try (ConfigurableApplicationContext context = clientApplication.run( - this.connectionString, - "--spring.cloud.zookeeper.discovery.register=false")) { - Awaitility.await().until(new Runnable() { - @Override - public void run() { - try { - HelloClient bean = context.getBean(HelloClient.class); - then(bean.discoveryClient.getServices()).isNotEmpty(); - then(bean.discoveryClient.getInstances("hello-world")) - .isNotEmpty(); - String string = bean.restTemplate - .getForObject("http://hello-world/", String.class); - then(string).isEqualTo("foo"); - } - catch (IllegalStateException e) { - throw new AssertionError(e); - } - } - }); - } - } - } - - @EnableAutoConfiguration(exclude = { JmxAutoConfiguration.class }) - @Configuration - static class HelloClient { - - @LoadBalanced - @Bean - RestTemplate restTemplate() { - this.restTemplate = new RestTemplateBuilder().build(); - return this.restTemplate; - } - - @Autowired - DiscoveryClient discoveryClient; - - RestTemplate restTemplate; - - } - - @EnableAutoConfiguration(exclude = { JmxAutoConfiguration.class }) - @RestController - static class HelloProducer { - - @RequestMapping("/") - public String foo() { - return "foo"; - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java deleted file mode 100644 index 660fbd26f..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.configclient; - -import java.util.Arrays; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.cloud.client.DefaultServiceInstance; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.config.client.ConfigClientProperties; -import org.springframework.cloud.config.client.DiscoveryClientConfigServiceBootstrapConfiguration; -import org.springframework.cloud.test.ClassPathExclusions; -import org.springframework.cloud.test.ModifiedClassPathRunner; -import org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryClient; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryClientConfiguration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -/** - * @author Dave Syer - */ -@RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({ "spring-retry-*.jar", "spring-boot-starter-aop-*.jar" }) -public class DiscoveryClientConfigServiceAutoConfigurationTests { - - private AnnotationConfigApplicationContext context; - - @After - public void close() { - if (this.context != null) { - if (this.context.getParent() != null) { - ((AnnotationConfigApplicationContext) this.context.getParent()).close(); - } - this.context.close(); - } - } - - @Test - public void onWhenRequested() { - setup("server.port=7000", "spring.cloud.config.discovery.enabled=true", - "spring.cloud.zookeeper.discovery.instance-port:7001", - "spring.cloud.zookeeper.discovery.instance-host:foo", - "spring.cloud.config.discovery.service-id:configserver"); - assertThat(this.context.getBeanNamesForType(ZookeeperConfigServerAutoConfiguration.class).length).isEqualTo(1); - ZookeeperDiscoveryClient client = this.context.getParent().getBean(ZookeeperDiscoveryClient.class); - verify(client, atLeast(2)).getInstances("configserver"); - ConfigClientProperties locator = this.context.getBean(ConfigClientProperties.class); - assertThat(locator.getUri()[0]).isEqualTo("http://foo:7001/"); - } - - private void setup(String... env) { - ZookeeperTestingServer testingServer = new ZookeeperTestingServer(); - testingServer.start(); - AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); - TestPropertyValues.of(env).applyTo(parent); - TestPropertyValues.of(ZookeeperProperties.PREFIX + ".connect-string=localhost:" + testingServer.getPort()) - .applyTo(parent); - parent.register(UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - EnvironmentKnobbler.class, ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration.class, - DiscoveryClientConfigServiceBootstrapConfiguration.class, ConfigClientProperties.class); - testingServer.appPrepared(parent); - parent.refresh(); - this.context = new AnnotationConfigApplicationContext(); - this.context.setParent(parent); - this.context.register(PropertyPlaceholderAutoConfiguration.class, ZookeeperConfigServerAutoConfiguration.class, - ZookeeperAutoConfiguration.class, ZookeeperDiscoveryClientConfiguration.class); - this.context.refresh(); - } - - @Configuration - protected static class EnvironmentKnobbler { - - @Bean - public ZookeeperDiscoveryClient zookeeperDiscoveryClient(ZookeeperDiscoveryProperties properties) { - ZookeeperDiscoveryClient client = mock(ZookeeperDiscoveryClient.class); - ServiceInstance instance = new DefaultServiceInstance("configserver1", "configserver", - properties.getInstanceHost(), properties.getInstancePort(), false); - given(client.getInstances("configserver")).willReturn(Arrays.asList(instance)); - return client; - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfigurationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfigurationTests.java deleted file mode 100644 index fa48ccbd3..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfigurationTests.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.configclient; - -import org.junit.After; -import org.junit.Test; - -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.config.server.config.ConfigServerProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Dave Syer - */ -public class ZookeeperConfigServerAutoConfigurationTests { - - private ConfigurableApplicationContext context; - - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } - - @Test - public void offByDefault() { - this.context = new AnnotationConfigApplicationContext( - ZookeeperConfigServerAutoConfiguration.class); - assertThat(this.context - .getBeanNamesForType(ZookeeperDiscoveryProperties.class).length) - .isEqualTo(0); - } - - @Test - public void onWhenRequested() { - setup("spring.cloud.config.server.prefix=/config"); - assertThat(this.context - .getBeanNamesForType(ZookeeperDiscoveryProperties.class).length) - .isEqualTo(1); - ZookeeperDiscoveryProperties properties = this.context - .getBean(ZookeeperDiscoveryProperties.class); - assertThat(properties.getMetadata()).containsEntry("configPath", "/config"); - } - - private void setup(String... env) { - this.context = new SpringApplicationBuilder( - PropertyPlaceholderAutoConfiguration.class, - ZookeeperConfigServerAutoConfiguration.class, - ConfigServerProperties.class, ZookeeperDiscoveryProperties.class) - .listeners(new ZookeeperTestingServer()) - .web(WebApplicationType.NONE).properties(env).run(); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperNoConfigClientTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperNoConfigClientTests.java deleted file mode 100644 index 112854e42..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperNoConfigClientTests.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.configclient; - -import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; -import org.apache.curator.test.TestingServer; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.test.ClassPathExclusions; -import org.springframework.cloud.test.ModifiedClassPathRunner; -import org.springframework.cloud.test.TestSocketUtils; -import org.springframework.context.ConfigurableApplicationContext; - -@RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({ "spring-cloud-config-client-*.jar", "spring-cloud-config-server-*.jar" }) -public class ZookeeperConfigServerBootstrapperNoConfigClientTests { - - @Test - public void contextLoads() throws Exception { - TestingServer testingServer = null; - ConfigurableApplicationContext context = null; - try { - TomcatURLStreamHandlerFactory.disable(); - int port = TestSocketUtils.findAvailableTcpPort(); - testingServer = new TestingServer(port); - context = new SpringApplicationBuilder(TestConfig.class).properties("--server.port=0", - "spring.cloud.config.discovery.enabled=true", "spring.cloud.zookeeper.connect-string=localhost:" + port, - "spring.cloud.service-registry.auto-registration.enabled=false") - .run(); - } - finally { - if (context != null) { - context.close(); - } - if (testingServer != null) { - testingServer.close(); - } - } - } - - @SpringBootConfiguration - @EnableAutoConfiguration - static class TestConfig { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperTests.java deleted file mode 100644 index d1dd19ba8..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperTests.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2015-2020 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.configclient; - -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.commons.logging.Log; -import org.apache.curator.framework.CuratorFramework; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.boot.BootstrapRegistry; -import org.springframework.boot.BootstrapRegistryInitializer; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.properties.bind.BindContext; -import org.springframework.boot.context.properties.bind.BindHandler; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.context.properties.source.ConfigurationPropertyName; -import org.springframework.cloud.config.client.ConfigServerInstanceProvider; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryClient; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.ConfigurableApplicationContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; - -public class ZookeeperConfigServerBootstrapperTests { - - private ConfigurableApplicationContext context; - - @AfterEach - public void after() { - if (context != null) { - context.close(); - } - } - - @Test - public void notEnabledReturnsEmptyList() { - ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class) - .listeners(new ZookeeperTestingServer()) - .properties("--server.port=0", "spring.cloud.service-registry.auto-registration.enabled=false") - .addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> { - ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext() - .get(ConfigServerInstanceProvider.Function.class); - Log log = mock(Log.class); - assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class), event.getBootstrapContext().get(BindHandler.class), log)).as("ConfigServerInstanceProvider.Function should return empty list") - .isEmpty(); - })).run(); - CuratorFramework curatorFramework = context.getBean("curatorFramework", CuratorFramework.class); - assertThat(curatorFramework).isNotNull(); - assertThatThrownBy(() -> - context.getBean("configDataCuratorFramework", CuratorFramework.class)).isInstanceOf(NoSuchBeanDefinitionException.class); - context.close(); - } - - @Test - public void zookeeperDiscoveryClientDisabledReturnsEmptyList() { - ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class) - .listeners(new ZookeeperTestingServer()) - .properties("--server.port=0", "spring.cloud.config.discovery.enabled=true", - "spring.cloud.zookeeper.discovery.enabled=false", - "spring.cloud.zookeeper.discovery.metadata[mymetadataprop]=mymetadataval", - "spring.cloud.service-registry.auto-registration.enabled=false") - .addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> { - ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext() - .get(ConfigServerInstanceProvider.Function.class); - Log log = mock(Log.class); - assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class), event.getBootstrapContext().get(BindHandler.class), log)).as("ConfigServerInstanceProvider.Function should return empty list") - .isEmpty(); - })).run(); - CuratorFramework curatorFramework = context.getBean("curatorFramework", CuratorFramework.class); - assertThat(curatorFramework).isNotNull(); - assertThatThrownBy(() -> - context.getBean("configDataCuratorFramework", CuratorFramework.class)).isInstanceOf(NoSuchBeanDefinitionException.class); - context.close(); - } - - @Test - public void discoveryClientDisabledReturnsEmptyList() { - ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class) - .listeners(new ZookeeperTestingServer()) - .properties("--server.port=0", "spring.cloud.config.discovery.enabled=true", - "spring.cloud.discovery.enabled=false", - "spring.cloud.zookeeper.discovery.metadata[mymetadataprop]=mymetadataval", - "spring.cloud.service-registry.auto-registration.enabled=false") - .addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> { - ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext() - .get(ConfigServerInstanceProvider.Function.class); - assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class), event.getBootstrapContext().get(BindHandler.class), mock(Log.class))).as("ConfigServerInstanceProvider.Function should return empty list") - .isEmpty(); - })).run(); - CuratorFramework curatorFramework = context.getBean("curatorFramework", CuratorFramework.class); - assertThat(curatorFramework).isNotNull(); - assertThatThrownBy(() -> - context.getBean("configDataCuratorFramework", CuratorFramework.class)).isInstanceOf(NoSuchBeanDefinitionException.class); - context.close(); - } - - @Test - public void enabledAddsInstanceProviderFn() { - AtomicReference bootstrapDiscoveryClient = new AtomicReference<>(); - BindHandlerBootstrapper bindHandlerBootstrapper = new BindHandlerBootstrapper(); - context = new SpringApplicationBuilder(TestConfig.class) - .listeners(new ZookeeperTestingServer()) - .properties("--server.port=0", "spring.cloud.config.discovery.enabled=true", - "spring.cloud.zookeeper.discovery.metadata[mymetadataprop]=mymetadataval", - "spring.cloud.service-registry.auto-registration.enabled=false") - .addBootstrapRegistryInitializer(bindHandlerBootstrapper) - .addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> { - ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext() - .get(ConfigServerInstanceProvider.Function.class); - assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class), event.getBootstrapContext().get(BindHandler.class), mock(Log.class))).as("Should return empty list.") - .isNotNull(); - bootstrapDiscoveryClient.set(event.getBootstrapContext().get(ZookeeperDiscoveryClient.class)); - })).run(); - - ZookeeperDiscoveryClient discoveryClient = context.getBean(ZookeeperDiscoveryClient.class); - assertThat(discoveryClient == bootstrapDiscoveryClient.get()).isTrue(); - assertThat(bindHandlerBootstrapper.onSuccessCount).isGreaterThan(0); - } - - @SpringBootConfiguration - @EnableAutoConfiguration - static class TestConfig { - - } - static class BindHandlerBootstrapper implements BootstrapRegistryInitializer { - - private int onSuccessCount = 0; - - @Override - public void initialize(BootstrapRegistry registry) { - registry.register(BindHandler.class, context -> new BindHandler() { - @Override - public Object onSuccess(ConfigurationPropertyName name, Bindable target, BindContext context, - Object result) { - onSuccessCount++; - return result; - } - }); - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperTestsIT.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperTestsIT.java deleted file mode 100644 index 2bd6ed462..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerBootstrapperTestsIT.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2015-2022 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.configclient; - -import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockserver.client.MockServerClient; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.MockServerContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.utility.DockerImageName; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.config.environment.Environment; -import org.springframework.cloud.config.environment.PropertySource; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.serviceregistry.ServiceInstanceRegistration; -import org.springframework.context.ConfigurableApplicationContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockserver.model.HttpRequest.request; -import static org.mockserver.model.HttpResponse.response; - -/** - * @author Ryan Baxter - */ -@Testcontainers -class ZookeeperConfigServerBootstrapperTestsIT { - private static final int ZOOKEEPER_PORT = 2181; - - public static final DockerImageName MOCKSERVER_IMAGE = DockerImageName.parse("mockserver/mockserver") - .withTag("mockserver-" + MockServerClient.class.getPackage().getImplementationVersion()); - - @Container - private static final GenericContainer zookeeper = new GenericContainer<>("zookeeper:3.8.0") - .withExposedPorts(ZOOKEEPER_PORT); - - @Container - static MockServerContainer mockServer = new MockServerContainer(MOCKSERVER_IMAGE); - - private ConfigurableApplicationContext context; - - private ServiceDiscovery serviceDiscovery; - - private CuratorFramework curatorFramework; - - @BeforeEach - void before() { - curatorFramework = CuratorFrameworkFactory.builder().connectString(zookeeper.getHost() + ":" + zookeeper.getMappedPort(ZOOKEEPER_PORT)) - .retryPolicy(new RetryOneTime(100)).build(); - - try { - curatorFramework.start(); - serviceDiscovery = ServiceDiscoveryBuilder.builder(ZookeeperInstance.class).client(curatorFramework).basePath("/services") - .build(); - serviceDiscovery.start(); - serviceDiscovery.registerService(ServiceInstanceRegistration.builder().id("zookeeper-configserver").name("zookeeper-configserver") - .address(mockServer.getHost()).port(mockServer.getServerPort()).uriSpec(ZookeeperDiscoveryProperties.DEFAULT_URI_SPEC).build().getServiceInstance()); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - - @AfterEach - void after() throws IOException { - this.context.close(); - this.serviceDiscovery.close(); - this.curatorFramework.close(); - } - - @Test - public void contextLoads() throws JsonProcessingException { - Environment environment = new Environment("test", "default"); - Map properties = new HashMap<>(); - properties.put("hello", "world"); - PropertySource p = new PropertySource("p1", properties); - environment.add(p); - ObjectMapper objectMapper = new ObjectMapper(); - try (MockServerClient mockServerClient = new MockServerClient(mockServer.getHost(), - mockServer.getMappedPort(MockServerContainer.PORT))) { - mockServerClient.when(request().withPath("/application/default")) - .respond(response().withBody(objectMapper.writeValueAsString(environment)) - .withHeader("content-type", "application/json")); - this.context = setup().run(); - assertThat(this.context.getEnvironment().getProperty("hello")).isEqualTo("world"); - } - - } - - SpringApplicationBuilder setup(String... env) { - return new SpringApplicationBuilder(TestConfig.class) - .properties(addDefaultEnv(env)); - } - - private String[] addDefaultEnv(String[] env) { - Set set = new LinkedHashSet<>(); - if (env != null && env.length > 0) { - set.addAll(Arrays.asList(env)); - } - set.add("spring.config.import=classpath:bootstrapper.yaml"); - set.add("spring.cloud.config.enabled=true"); - set.add("spring.cloud.service-registry.auto-registration.enabled=false"); - set.add(ZookeeperProperties.PREFIX + ".connectString=" + zookeeper.getHost() + ":" + zookeeper.getMappedPort(ZOOKEEPER_PORT)); - return set.toArray(new String[0]); - } - - @SpringBootConfiguration - @EnableAutoConfiguration - static class TestConfig { - - } -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyConfig.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyConfig.java deleted file mode 100644 index 8e4d2910f..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyConfig.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.Collection; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.context.WebServerInitializedEvent; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.discovery.test.TestLoadBalancedClient; -import org.springframework.context.ApplicationListener; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -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.RestController; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.BDDAssertions.then; - -@Configuration -@EnableAutoConfiguration -@Import(CommonTestConfig.class) -@EnableFeignClients(basePackageClasses = { AliasUsingFeignClient.class, - IdUsingFeignClient.class }) -public class DependencyConfig { - - @Bean - TestLoadBalancedClient testLoadBalancedClient(@LoadBalanced RestTemplate restTemplate) { - return new TestLoadBalancedClient(restTemplate); - } - - @Bean - PingController pingController() { - return new PingController(portListener()); - } - - @Bean - PortListener portListener() { - return new PortListener(); - } - -} - -class PortListener implements ApplicationListener { - - private int port; - - @Override - public void onApplicationEvent(WebServerInitializedEvent event) { - this.port = event.getWebServer().getPort(); - } - - public int getPort() { - return this.port; - } - -} - -@FeignClient("someAlias") -interface AliasUsingFeignClient { - - @RequestMapping(method = RequestMethod.GET, value = "/application/beans") - String getBeans(); - - @RequestMapping(method = RequestMethod.GET, value = "/checkHeaders") - String checkHeaders(); - -} - -@FeignClient("nameWithoutAlias") -interface IdUsingFeignClient { - - @RequestMapping(method = RequestMethod.GET, value = "/application/beans") - String getBeans(); - -} - -@RestController -class PingController { - - private final PortListener portListener; - - PingController(PortListener portListener) { - this.portListener = portListener; - } - - @RequestMapping("/ping") - String ping() { - return "pong"; - } - - @RequestMapping("/port") - Integer port() { - return this.portListener.getPort(); - } - - @RequestMapping("/checkHeaders") - String checkHeaders(@RequestHeader("Content-Type") String contentType, - @RequestHeader("header1") Collection header1, - @RequestHeader("header2") Collection header2) { - then(contentType).isEqualTo("application/vnd.newsletter.v1+json"); - then(header1).containsExactly("value1"); - then(header2).containsExactly("value2"); - return "ok"; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfigurationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfigurationTests.java deleted file mode 100644 index 6135fcf5b..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfigurationTests.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import org.junit.Test; - -import static org.assertj.core.api.BDDAssertions.then; - -/** - * @author Marcin Grzejszczak - */ -public class StubsConfigurationTests { - - @Test - public void should_return_empty_colon_separated_dependency_notation_if_empty_path_has_been_provided() { - // given: - String path = ""; - // when: - StubsConfiguration stubsConfiguration = new StubsConfiguration(path); - // then: - then(stubsConfiguration.toColonSeparatedDependencyNotation()).isEqualTo(""); - } - - @Test - public void should_return_empty_colon_separated_dependency_notation_if_invalid_path_has_been_provided() { - // given: - String path = "pl/"; - // when: - StubsConfiguration stubsConfiguration = new StubsConfiguration(path); - // then: - then(stubsConfiguration.toColonSeparatedDependencyNotation()).isEqualTo(""); - } - - @Test - public void should_properly_parse_invalid_colon_separated_path_into_empty_notation() { - // given: - String path = "pl/a"; - // when: - StubsConfiguration stubsConfiguration = new StubsConfiguration(path); - // then: - then(stubsConfiguration.toColonSeparatedDependencyNotation()).isEqualTo(""); - then(stubsConfiguration.getStubsGroupId()).isEqualTo(""); - then(stubsConfiguration.getStubsArtifactId()).isEqualTo(""); - then(stubsConfiguration.getStubsClassifier()).isEqualTo(""); - } - - @Test - public void should_parse_the_path_into_group_artifact_and_classifier() { - // given: - String path = "pl/a"; - // when: - StubsConfiguration stubsConfiguration = new StubsConfiguration( - new StubsConfiguration.DependencyPath(path)); - // then: - then(stubsConfiguration.toColonSeparatedDependencyNotation()) - .isEqualTo("pl:a:stubs"); - then(stubsConfiguration.getStubsGroupId()).isEqualTo("pl"); - then(stubsConfiguration.getStubsArtifactId()).isEqualTo("a"); - then(stubsConfiguration.getStubsClassifier()).isEqualTo("stubs"); - } - - @Test - public void should_properly_set_group_artifact_and_classifier() { - // when: - StubsConfiguration stubsConfiguration = new StubsConfiguration("pl", "a", - "superstubs"); - // then: - then(stubsConfiguration.toColonSeparatedDependencyNotation()) - .isEqualTo("pl:a:superstubs"); - then(stubsConfiguration.getStubsGroupId()).isEqualTo("pl"); - then(stubsConfiguration.getStubsArtifactId()).isEqualTo("a"); - then(stubsConfiguration.getStubsClassifier()).isEqualTo("superstubs"); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTest.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTest.java deleted file mode 100644 index 538e500a7..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.LinkedHashMap; -import java.util.Map; - -import org.junit.Test; - -import static org.assertj.core.api.BDDAssertions.then; - -public class ZookeeperDependenciesTest { - - @Test - public void should_properly_sanitize_dependency_path() { - // given: - Map dependencies = new LinkedHashMap<>(); - ZookeeperDependency cat = new ZookeeperDependency(); - cat.setPath("/cats/cat"); - dependencies.put("cat", cat); - ZookeeperDependency dog = new ZookeeperDependency(); - dog.setPath("dogs/dog"); - dependencies.put("dog", dog); - ZookeeperDependencies zookeeperDependencies = new ZookeeperDependencies(); - zookeeperDependencies.setDependencies(dependencies); - // when: - zookeeperDependencies.init(); - // then: - then(zookeeperDependencies.getDependencies().get("cat").getPath()) - .isEqualTo("/cats/cat"); - then(zookeeperDependencies.getDependencies().get("dog").getPath()) - .isEqualTo("/dogs/dog"); - } - - @Test - public void should_properly_sanitize_dependency_path_with_prefix() { - // given: - Map dependencies = new LinkedHashMap<>(); - ZookeeperDependency cat = new ZookeeperDependency(); - cat.setPath("/cats/cat"); - dependencies.put("cat", cat); - ZookeeperDependency dog = new ZookeeperDependency(); - dog.setPath("dogs/dog"); - dependencies.put("dog", dog); - ZookeeperDependencies zookeeperDependencies = new ZookeeperDependencies(); - zookeeperDependencies.setPrefix("animals/"); - zookeeperDependencies.setDependencies(dependencies); - // when: - zookeeperDependencies.init(); - // then: - then(zookeeperDependencies.getDependencies().get("cat").getPath()) - .isEqualTo("/animals/cats/cat"); - then(zookeeperDependencies.getDependencies().get("dog").getPath()) - .isEqualTo("/animals/dogs/dog"); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTests.java deleted file mode 100644 index 5a0563d88..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTests.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import static org.assertj.core.api.BDDAssertions.then; - -/** - * @author Marcin Grzejszczak - */ -public class ZookeeperDependenciesTests { - - private static final ZookeeperDependency EXPECTED_DEPENDENCY = new ZookeeperDependency( - "path", "contentTypeTemplate", "version", - defaultHeader(), false, ""); - - private static final Map DEPENDENCIES = defaultDependencies(); - - private static Map> defaultHeader() { - return Collections.singletonMap("header", - Collections.singletonList("value")); - } - - private static Map defaultDependencies() { - Map map = new HashMap<>(); - map.put("alias", EXPECTED_DEPENDENCY); - return map; - } - - ZookeeperDependencies zookeeperDependencies = new ZookeeperDependencies(); - - @Before - public void setup() { - this.zookeeperDependencies.setDependencies(DEPENDENCIES); - } - - @Test - public void should_retrieve_dependency_dependency_for_good_path() { - // expect: - then(this.zookeeperDependencies.getDependencyForPath("path")) - .isEqualTo(EXPECTED_DEPENDENCY); - } - - @Test - public void should_retrieve_null_dependency_dependency_for_bad_path() { - // expect: - then(this.zookeeperDependencies.getDependencyForPath("unknownPath")).isNull(); - } - - @Test - public void should_retrieve_dependency_for_good_alias() { - // expect: - then(this.zookeeperDependencies.getDependencyForAlias("alias")) - .isEqualTo(EXPECTED_DEPENDENCY); - } - - @Test - public void should_retrieve_null_dependency_for_bad_alias() { - // expect: - then(this.zookeeperDependencies.getDependencyForAlias("unknownAlias")).isNull(); - } - - @Test - public void should_retrieve_alias_for_good_path() { - // expect: - then(this.zookeeperDependencies.getAliasForPath("path")).isEqualTo("alias"); - } - - @Test - public void should_retrieve_empty_alias_for_bad_path() { - // expect: - then(this.zookeeperDependencies.getAliasForPath("unkownPath")).isEmpty(); - } - - @Test - public void should_retrieve_path_for_good_alias() { - // expect: - then(this.zookeeperDependencies.getPathForAlias("alias")).isEqualTo("path"); - } - - @Test - public void should_retrieve_empty_path_for_bad_alias() { - // expect: - then(this.zookeeperDependencies.getPathForAlias("unknownAlias")).isEmpty(); - } - - @Test - public void should_successfully_replace_version_in_content_type_template() { - // given: - ZookeeperDependency zookeeperDependency = new ZookeeperDependency(); - zookeeperDependency - .setContentTypeTemplate("application/vnd.some-service.$version+json"); - zookeeperDependency.setVersion("v1"); - // expect: - then(zookeeperDependency.getContentTypeWithVersion()) - .isEqualTo("application/vnd.some-service.v1+json"); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDependenciesIntegrationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDependenciesIntegrationTests.java deleted file mode 100644 index 97aaf40a2..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDependenciesIntegrationTests.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.util.List; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.zookeeper.discovery.test.TestLoadBalancedClient; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Profile; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static com.jayway.awaitility.Awaitility.await; -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.cloud.zookeeper.discovery.test.TestLoadBalancedClient.BASE_PATH; - -/** - * @author Marcin Grzejszczak - * @author Olga Maciaszek-Sharma - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoveryWithDependenciesIntegrationTests.Config.class, properties = { - "debug=true", - "management.endpoints.web.exposure.include=*"}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("dependencies") -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperDiscoveryWithDependenciesIntegrationTests { - - @Autowired - TestLoadBalancedClient testLoadBalancedClient; - - @Autowired - DiscoveryClient discoveryClient; - - @Autowired - AliasUsingFeignClient aliasUsingFeignClient; - - @Autowired - IdUsingFeignClient idUsingFeignClient; - - @Autowired - ZookeeperDependencies zookeeperDependencies; - - @Test - public void should_find_an_instance_via_path_when_alias_is_not_found() { - // given: - final DiscoveryClient discoveryClient = this.discoveryClient; - // expect: - await().until(() -> !discoveryClient.getInstances("nameWithoutAlias").isEmpty()); - } - - @Test - public void should_fill_out_properly_the_stub_section_of_a_dependency() { - // given: - StubsConfiguration stubsConfiguration = this.zookeeperDependencies - .getDependencies().get("someAlias").getStubsConfiguration(); - // expect: - then(stubsConfiguration.getStubsGroupId()).isEqualTo("org.springframework"); - then(stubsConfiguration.getStubsArtifactId()).isEqualTo("foo"); - then(stubsConfiguration.getStubsClassifier()).isEqualTo("stubs"); - } - - @Ignore // FIXME 2.0.0 - @Test - public void should_find_an_instance_using_feign_via_serviceID_when_alias_is_not_found() { - // given: - final IdUsingFeignClient idUsingFeignClient = this.idUsingFeignClient; - // expect: - await().until(() -> { - then(idUsingFeignClient.getBeans()).isNotEmpty(); - return true; - }); - } - - @Ignore // FIXME 2.0.0 - @Test - public void should_find_a_collaborator_via_load_balanced_rest_template_by_using_its_alias_from_dependencies() { - // expect: - await().until(() -> callingServiceAtBeansEndpointIsNotEmpty()); - } - - @Ignore // FIXME 2.0.0 - @Test - public void should_find_a_collaborator_using_feign_by_using_its_alias_from_dependencies() { - // given: - final AliasUsingFeignClient aliasUsingFeignClient = this.aliasUsingFeignClient; - // expect: - await().until(() -> { - then(aliasUsingFeignClient.getBeans()).isNotEmpty(); - return true; - }); - } - - @Test - public void should_have_headers_from_dependencies_attached_to_the_request_via_load_balanced_rest_template() { - // expect: - await().until(() -> { - callingServiceToCheckIfHeadersArePassed(); - return true; - }); - } - - @Ignore // FIXME 2.0.0 - @Test - public void should_have_headers_from_dependencies_attached_to_the_request_via_feign() { - // given: - final AliasUsingFeignClient aliasUsingFeignClient = this.aliasUsingFeignClient; - // expect: - await().until(() -> { - aliasUsingFeignClient.checkHeaders(); - return true; - }); - } - - @Test - public void should_find_a_collaborator_via_discovery_client() { - // // given: - final DiscoveryClient discoveryClient = this.discoveryClient; - List instances = discoveryClient.getInstances("someAlias"); - final ServiceInstance instance = instances.get(0); - // expect: - await().until(() -> callingServiceViaUrlOnBeansEndpointIsNotEmpty(instance)); - } - - @Test - public void should_have_path_equal_to_prefixed_alias() { - // given: - ZookeeperDependency dependency = this.zookeeperDependencies - .getDependencyForAlias("aliasIsPath"); - // expect: - then(dependency.getPath()).isEqualTo("/aliasIsPath"); - } - - @Test - public void should_have_prefixed_alias_equal_to_path() { - // given: - ZookeeperDependency dependency = this.zookeeperDependencies - .getDependencyForPath("/aliasIsPath"); - // expect: - then(dependency.getPath()).isEqualTo("/aliasIsPath"); - } - - @Test - public void should_have_path_set_via_string_constructor() { - // given: - ZookeeperDependency dependency = this.zookeeperDependencies - .getDependencyForAlias("anotherAlias"); - // expect: - then(dependency.getPath()).isEqualTo("/myPath"); - } - - // #138 - @Test - public void should_parse_dependency_with_path() { - // given: - StubsConfiguration someServiceStub = this.zookeeperDependencies - .getDependencyForAlias("some-service").getStubsConfiguration(); - // expect: - then(someServiceStub.getStubsGroupId()).isEqualTo("io.company.department"); - then(someServiceStub.getStubsArtifactId()).isEqualTo("some-service"); - then(someServiceStub.getStubsClassifier()).isEqualTo("stubs"); - } - - private boolean callingServiceAtBeansEndpointIsNotEmpty() { - return !this.testLoadBalancedClient.callService("someAlias", BASE_PATH + "/beans") - .isEmpty(); - } - - private boolean callingServiceViaUrlOnBeansEndpointIsNotEmpty( - ServiceInstance instance) { - return !this.testLoadBalancedClient - .callOnUrl(instance.getHost() + ":" + instance.getPort(), - BASE_PATH + "/beans") - .isEmpty(); - } - - private void callingServiceToCheckIfHeadersArePassed() { - this.testLoadBalancedClient.callService("someAlias", "checkHeaders"); - } - - @Configuration - @EnableAutoConfiguration - @Import(DependencyConfig.class) - @Profile("dependencies") - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDyingDependenciesTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDyingDependenciesTests.java deleted file mode 100644 index aa2b92baa..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDyingDependenciesTests.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.dependency; - -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.curator.test.TestingServer; -import org.assertj.core.api.BDDAssertions; -import org.junit.Ignore; -import org.junit.Test; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.test.TestSocketUtils; -import org.springframework.cloud.zookeeper.discovery.test.TestLoadBalancedClient; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -import static com.jayway.awaitility.Awaitility.await; - -/** - * @author Marcin Grzejszczak - */ -@Ignore -public class ZookeeperDiscoveryWithDyingDependenciesTests { - - private static final Log log = LogFactory - .getLog(ZookeeperDiscoveryWithDyingDependenciesTests.class); - - // Issue: #45 - @Test - public void should_refresh_a_dependency_in_LoadBalancer_when_the_dependency_has_deregistered_and_registered_in_Zookeeper() - throws Exception { - ConfigurableApplicationContext serverContext = null; - ConfigurableApplicationContext clientContext = null; - TestingServer testingServer = null; - try { - // given: - int zookeeperPort = TestSocketUtils.findAvailableTcpPort(); - testingServer = new TestingServer(zookeeperPort); - System.setProperty("spring.jmx.enabled", "false"); - System.setProperty("spring.cloud.zookeeper.connectString", - "127.0.0.1:" + zookeeperPort); - // and: - serverContext = contextWithProfile("server"); - clientContext = contextWithProfile("client"); - // and: - Integer serverPortBeforeDying = callServiceAtPortEndpoint(clientContext); - // and: - serverContext = restartContext(serverContext, "server"); - // expect: - await().atMost(5, TimeUnit.SECONDS).until(applicationHasStartedOnANewPort( - clientContext, serverPortBeforeDying)); - } - finally { - // cleanup: - close(serverContext); - close(clientContext); - close(testingServer); - } - } - - private Callable applicationHasStartedOnANewPort( - final ConfigurableApplicationContext clientContext, - final Integer serverPortBeforeDying) { - return new Callable() { - @Override - public Boolean call() throws Exception { - try { - BDDAssertions.then(callServiceAtPortEndpoint(clientContext)) - .isNotEqualTo(serverPortBeforeDying); - } - catch (Exception e) { - log.error("Exception occurred while trying to call the server", e); - return false; - } - return true; - } - }; - } - - private void close(Closeable closeable) throws IOException { - if (closeable != null) { - closeable.close(); - } - } - - private ConfigurableApplicationContext contextWithProfile(String profile) { - return new SpringApplicationBuilder(Config.class).profiles(profile).build().run(); - } - - private ConfigurableApplicationContext restartContext( - ConfigurableApplicationContext configurableApplicationContext, String profile) - throws IOException { - close(configurableApplicationContext); - return contextWithProfile(profile); - } - - private Integer callServiceAtPortEndpoint(ApplicationContext applicationContext) { - return applicationContext.getBean(TestLoadBalancedClient.class) - .callService("testInstance", "port", Integer.class); - } - - @Configuration - @EnableAutoConfiguration - @Import(DependencyConfig.class) - static class Config { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientConfigurationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientConfigurationTests.java deleted file mode 100644 index 39eb07090..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientConfigurationTests.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2019-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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.reactive; - -import org.apache.curator.framework.CuratorFramework; -import org.junit.jupiter.api.Test; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.FilteredClassLoader; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration; -import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; -import org.springframework.cloud.client.discovery.health.reactive.ReactiveDiscoveryClientHealthIndicator; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryAutoConfiguration; -import org.springframework.cloud.zookeeper.support.CuratorServiceDiscoveryAutoConfiguration; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Bean; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -/** - * @author Tim Ysewyn - */ -class ZookeeperReactiveDiscoveryClientConfigurationTests { - - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withInitializer(new ZookeeperTestingServer.Initializer()) - .withConfiguration( - AutoConfigurations.of(UtilAutoConfiguration.class, - ReactiveCommonsClientAutoConfiguration.class, - CuratorServiceDiscoveryAutoConfiguration.class, - ZookeeperDiscoveryAutoConfiguration.class, - ZookeeperReactiveDiscoveryClientConfiguration.class)) - .withUserConfiguration(MockedZookeeperConfiguration.class); - - @Test - public void shouldWorkWithDefaults() { - contextRunner.run(context -> { - assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); - assertThat(context).hasSingleBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); - } - - @Test - public void shouldNotHaveDiscoveryClientWhenDiscoveryDisabled() { - contextRunner.withPropertyValues("spring.cloud.discovery.enabled=false") - .run(context -> { - assertThat(context).doesNotHaveBean("zookeeperReactiveDiscoveryClient"); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); - } - - @Test - public void shouldNotHaveDiscoveryClientWhenReactiveDiscoveryDisabled() { - contextRunner.withPropertyValues("spring.cloud.discovery.reactive.enabled=false") - .run(context -> { - assertThat(context).doesNotHaveBean("zookeeperReactiveDiscoveryClient"); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); - } - - @Test - public void shouldNotHaveDiscoveryClientWhenCloudFoundryDiscoveryDisabled() { - contextRunner - .withPropertyValues("spring.cloud.zookeeper.discovery.enabled=false") - .run(context -> { - assertThat(context).doesNotHaveBean("zookeeperReactiveDiscoveryClient"); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); - } - - @Test - public void worksWithoutWebflux() { - contextRunner - .withClassLoader( - new FilteredClassLoader("org.springframework.web.reactive")) - .run(context -> { - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); - } - - @Test - public void worksWithoutActuator() { - contextRunner - .withClassLoader( - new FilteredClassLoader("org.springframework.boot.actuate")) - .run(context -> { - assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); - } - - @TestConfiguration - static class MockedZookeeperConfiguration { - - @Bean - CuratorFramework curator() { - return mock(CuratorFramework.class); - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientTests.java deleted file mode 100644 index 013942528..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/reactive/ZookeeperReactiveDiscoveryClientTests.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2019-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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.reactive; - -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import reactor.core.publisher.Flux; -import reactor.test.StepVerifier; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; - -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -/** - * @author Tim Ysewyn - */ -@ExtendWith(MockitoExtension.class) -class ZookeeperReactiveDiscoveryClientTests { - - @Mock - private ServiceDiscovery zkClient; - - @Mock - private ZookeeperDependencies zookeeperDependencies; - - @Mock - private ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; - - @Mock - private org.apache.curator.x.discovery.ServiceInstance serviceInstance; - - @InjectMocks - private ZookeeperReactiveDiscoveryClient client; - - @Test - public void verifyDefaults() { - when(zookeeperDiscoveryProperties.getOrder()).thenReturn(1); - assertThat(client.description()).isEqualTo("Spring Cloud Zookeeper Reactive Discovery Client"); - assertThat(client.getOrder()).isEqualTo(1); - } - - @Test - public void shouldReturnFluxOfServices() throws Exception { - when(zkClient.queryForNames()).thenReturn(singletonList("my-service")); - Flux services = this.client.getServices(); - StepVerifier.create(services).expectNext("my-service").expectComplete().verify(); - } - - @Test - public void shouldReturnEmptyFluxOfServicesWhenZookeeperFails() throws Exception { - when(zkClient.queryForNames()).thenThrow(new RuntimeException()); - Flux services = this.client.getServices(); - StepVerifier.create(services).expectNextCount(0).expectComplete().verify(); - } - - @Test - public void shouldReturnEmptyFluxForNonExistingService() { - Flux services = this.client.getInstances("nonexistent-service"); - StepVerifier.create(services).expectNextCount(0).expectComplete().verify(); - } - - @Test - public void shouldReturnEmptyFluxWhenZookeeperFails() throws Exception { - when(zkClient.queryForInstances("existing-service")).thenThrow(new RuntimeException()); - Flux services = this.client.getInstances("existing-service"); - StepVerifier.create(services).expectNextCount(0).expectComplete().verify(); - } - - @Test - public void shouldReturnFluxOfServiceInstances() throws Exception { - configureServiceInstance(); - when(zookeeperDependencies.hasDependencies()).thenReturn(false); - when(zkClient.queryForInstances("existing-service")).thenReturn(singletonList(serviceInstance)); - Flux services = this.client.getInstances("existing-service"); - StepVerifier.create(services).expectNextCount(1).expectComplete().verify(); - } - - @Test - public void shouldReturnFluxOfServiceInstancesWhenNotHavingPathForAlias() throws Exception { - configureServiceInstance(); - when(zookeeperDependencies.hasDependencies()).thenReturn(true); - when(zookeeperDependencies.getPathForAlias("existing-service")).thenReturn(""); - when(zkClient.queryForInstances("existing-service")).thenReturn(singletonList(serviceInstance)); - Flux services = this.client.getInstances("existing-service"); - StepVerifier.create(services).expectNextCount(1).expectComplete().verify(); - } - - @Test - public void shouldReturnFluxOfServiceInstancesWhenHavingPathForAlias() throws Exception { - configureServiceInstance(); - when(zookeeperDependencies.hasDependencies()).thenReturn(true); - when(zookeeperDependencies.getPathForAlias("existing-service")).thenReturn("path-for-existing-service"); - when(zkClient.queryForInstances("path-for-existing-service")).thenReturn(singletonList(serviceInstance)); - Flux services = this.client.getInstances("existing-service"); - StepVerifier.create(services).expectNextCount(1).expectComplete().verify(); - } - - private void configureServiceInstance() { - when(serviceInstance.getAddress()).thenReturn("http://localhost"); - when(serviceInstance.getPort()).thenReturn(80); - when(serviceInstance.buildUriSpec()).thenReturn("http://localhost:80"); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/CommonTestConfig.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/CommonTestConfig.java deleted file mode 100644 index 69c786e59..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/CommonTestConfig.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.test; - -import org.apache.curator.test.TestingServer; - -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.test.TestSocketUtils; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.RestTemplate; - -/** - * - */ -@Configuration -public class CommonTestConfig { - - @Bean - @LoadBalanced - RestTemplate loadBalancedRestTemplate() { - return new RestTemplate(); - } - - @Bean(destroyMethod = "close") - TestingServer testingServer() throws Exception { - return new TestingServer(TestSocketUtils.findAvailableTcpPort()); - } - - @Bean - ZookeeperProperties zookeeperProperties(TestingServer testingServer) { - ZookeeperProperties zookeeperProperties = new ZookeeperProperties(); - zookeeperProperties.setConnectString("localhost:" + testingServer.getPort()); - return zookeeperProperties; - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestLoadBalancedClient.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestLoadBalancedClient.java deleted file mode 100644 index 9d37cc5ef..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestLoadBalancedClient.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.test; - -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.web.client.RestTemplate; - -/** - * @author Marcin Grzejszczak - */ -public class TestLoadBalancedClient extends TestServiceRestClient { - - public static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - - private final String thisAppName; - - public TestLoadBalancedClient(RestTemplate restTemplate) { - super(restTemplate); - this.thisAppName = "someName"; - } - - public TestLoadBalancedClient(RestTemplate restTemplate, String thisAppName) { - super(restTemplate); - this.thisAppName = thisAppName; - } - - public String thisHealthCheck() { - return this.restTemplate.getForObject( - "http://" + this.thisAppName + BASE_PATH + "/health", String.class); - } - - public Integer thisPort() { - return this.restTemplate.getForObject("http://" + this.thisAppName + "/port", - Integer.class); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestServiceRestClient.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestServiceRestClient.java deleted file mode 100644 index 4bce134f5..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestServiceRestClient.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.test; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.web.client.RestTemplate; - -/** - * @author Marcin Grzejszczak - */ -public class TestServiceRestClient { - - private static final Log log = LogFactory.getLog(TestServiceRestClient.class); - - protected final RestTemplate restTemplate; - - public TestServiceRestClient(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - public T callService(String alias, String endpoint, Class clazz) { - String url = "http://" + alias + "/" + endpoint; - log.info("Calling [" + url + "]"); - return this.restTemplate.getForObject(url, clazz); - } - - public String callService(String alias, String endpoint) { - return callService(alias, endpoint, String.class); - } - - public String callOnUrl(String url, String endpoint) { - if (!endpoint.startsWith("/")) { - endpoint = "/" + endpoint; - } - - return new RestTemplate().getForObject("http://" + url + endpoint, String.class); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcherSpringTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcherSpringTests.java deleted file mode 100644 index 635b6fbb7..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcherSpringTests.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher; - -import java.util.concurrent.Callable; - -import com.jayway.awaitility.Awaitility; -import org.apache.curator.x.discovery.ServiceCache; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier; -import org.springframework.cloud.zookeeper.discovery.watcher.presence.LogMissingDependencyChecker; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistry; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Marcin Grzejszczak - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = DefaultDependencyWatcherSpringTests.Config.class, webEnvironment = RANDOM_PORT) -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -@ActiveProfiles("watcher") -public class DefaultDependencyWatcherSpringTests { - - @Autowired - AssertableDependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier; - - @Autowired - AssertableDependencyWatcherListener dependencyWatcherListener; - - @Autowired - ZookeeperRegistration zookeeperRegistration; - - @Autowired - ZookeeperServiceRegistry registry; - - @Test - public void should_verify_that_presence_of_a_dependency_has_been_checked() { - then(this.dependencyPresenceOnStartupVerifier.startupPresenceVerified).isTrue(); - } - - @Ignore // FIXME 2.0.0 - @Test - public void should_verify_that_dependency_watcher_listener_is_successfully_registered_and_operational() - throws Exception { - // when: - this.registry.deregister(this.zookeeperRegistration); - - // then: - Awaitility.await().until(new Callable() { - @Override - public Boolean call() throws Exception { - then(DefaultDependencyWatcherSpringTests.this.dependencyWatcherListener.dependencyState) - .isEqualTo(DependencyState.DISCONNECTED); - return true; - } - }); - } - - @Configuration - @EnableAutoConfiguration - @Profile("watcher") - static class Config { - - @Bean - @LoadBalanced - RestTemplate loadBalancedRestTemplate() { - return new RestTemplate(); - } - - @Bean - static PropertySourcesPlaceholderConfigurer propertiesConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Bean - DependencyWatcherListener dependencyWatcherListener() { - return new AssertableDependencyWatcherListener(); - } - - @Bean - DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier() { - return new AssertableDependencyPresenceOnStartupVerifier(); - } - - } - - static class AssertableDependencyWatcherListener - implements DependencyWatcherListener { - - DependencyState dependencyState = DependencyState.CONNECTED; - - @Override - public void stateChanged(String dependencyName, DependencyState newState) { - dependencyState = newState; - } - - } - - static class AssertableDependencyPresenceOnStartupVerifier - extends DependencyPresenceOnStartupVerifier { - - boolean startupPresenceVerified = false; - - AssertableDependencyPresenceOnStartupVerifier() { - super(new LogMissingDependencyChecker()); - } - - @Override - public void verifyDependencyPresence(String dependencyName, - ServiceCache serviceCache, boolean required) { - startupPresenceVerified = true; - } - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifierTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifierTests.java deleted file mode 100644 index b93e3df4e..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifierTests.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher.presence; - -import java.util.Collections; - -import org.apache.curator.x.discovery.ServiceCache; -import org.junit.Assert; -import org.junit.Test; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * @author Marcin Grzejszczak - */ -public class DefaultDependencyPresenceOnStartupVerifierTests { - - private static final String SERVICE_NAME = "service01"; - - @Test - public void should_throw_exception_if_obligatory_dependencies_are_missing() { - // given: - DefaultDependencyPresenceOnStartupVerifier dependencyVerifier = new DefaultDependencyPresenceOnStartupVerifier(); - ServiceCache serviceCache = mock(ServiceCache.class); - given(serviceCache.getInstances()).willReturn(Collections.emptyList()); - // when: - try { - dependencyVerifier.verifyDependencyPresence(SERVICE_NAME, serviceCache, true); - Assert.fail("Should throw no instances running exception"); - } - catch (Exception e) { - // then: - then(e).isInstanceOf(NoInstancesRunningException.class); - } - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifierTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifierTests.java deleted file mode 100644 index ecb3a0b82..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifierTests.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.discovery.watcher.presence; - -import java.util.Collections; - -import org.apache.curator.x.discovery.ServiceCache; -import org.junit.Test; - -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.mock; - -/** - * @author Marcin Grzejszczak - */ -public class DependencyPresenceOnStartupVerifierTests { - - private static final String SERVICE_NAME = "service01"; - - @Test - public void should_check_optional_dependency_using_optional_dependency_checker() { - // given: - PresenceChecker optionalDependencyChecker = mock(PresenceChecker.class); - DependencyPresenceOnStartupVerifier dependencyVerifier = new DependencyPresenceOnStartupVerifier( - optionalDependencyChecker) { - }; - ServiceCache serviceCache = mock(ServiceCache.class); - given(serviceCache.getInstances()).willReturn(Collections.emptyList()); - // when: - dependencyVerifier.verifyDependencyPresence(SERVICE_NAME, serviceCache, false); - // then: - then(optionalDependencyChecker).should().checkPresence(SERVICE_NAME, - serviceCache.getInstances()); - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationTests.java deleted file mode 100644 index bc0c692b8..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationTests.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.serviceregistry; - -import java.util.Collection; - -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceInstance; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; -import org.springframework.cloud.zookeeper.support.StatusConstants; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author Spencer Gibb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "spring.application.name=myTestService1-F", - "spring.cloud.zookeeper.discovery.initial-status=OUT_OF_SERVICE" -}, webEnvironment = RANDOM_PORT) -@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class) -public class ZookeeperAutoServiceRegistrationTests { - - @Autowired - private ZookeeperRegistration registration; - - @Autowired - private ServiceDiscovery serviceDiscovery; - - @Autowired - private ZookeeperDiscoveryProperties properties; - - @Test - public void contextLoads() throws Exception { - Collection> instances = serviceDiscovery - .queryForInstances("myTestService1-F"); - assertThat(instances).hasSize(1); - - ServiceInstance instance = instances.iterator().next(); - assertThat(instance).isNotNull(); - assertThat(instance.getName()).isEqualTo("myTestService1-F"); - assertThat(instance.getPayload().getMetadata().get(StatusConstants.INSTANCE_STATUS_KEY)) - .isEqualTo(StatusConstants.STATUS_OUT_OF_SERVICE); - /* - * Response> response = consul.getAgentServices(); - * Map services = response.getValue(); Service service = - * services.get(registration.getServiceId()); assertNotNull("service was null", - * service); assertNotEquals("service port is 0", 0, - * service.getPort().intValue()); - * assertFalse("service id contained invalid character: " + service.getId(), - * service.getId().contains(":")); assertEquals("service id was wrong", - * registration.getServiceId(), service.getId()); - * assertEquals("service name was wrong", "myTestService1-FF-something", - * service.getService()); assertFalse("service address must not be empty", - * !StringUtils.hasLength(service.getAddress())); - * assertEquals("service address must equals hostname from discovery properties", - * discoveryProperties.getHostname(), service.getAddress()); - */ - } - - @SpringBootConfiguration - @EnableAutoConfiguration - @Import({ CommonTestConfig.class }) - /* - * @ImportAutoConfiguration({AutoServiceRegistrationAutoConfiguration.class, - * ZookeeperAutoServiceRegistration.class, - * ZookeeperServiceRegistryAutoConfiguration.class}) - */ - protected static class TestConfig { - - } - -} diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/application-client.yml b/spring-cloud-zookeeper-discovery/src/test/resources/application-client.yml deleted file mode 100644 index ea2cdc33a..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/application-client.yml +++ /dev/null @@ -1,9 +0,0 @@ -server.port: 0 -spring.application.name: client -spring.cloud.zookeeper: - dependencies: - testInstance: - path: /server -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR \ No newline at end of file diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/application-dependencies.yml b/spring-cloud-zookeeper-discovery/src/test/resources/application-dependencies.yml deleted file mode 100644 index 78beee7a5..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/application-dependencies.yml +++ /dev/null @@ -1,31 +0,0 @@ -spring.application.name: nameWithoutAlias -spring.cloud.zookeeper: - dependencies: - someAlias: - path: nameWithoutAlias - loadBalancerType: ROUND_ROBIN - contentTypeTemplate: application/vnd.newsletter.$version+json - version: v1 - headers: - header1: - - value1 - header2: - - value2 - required: false - stubs: org.springframework:foo:stubs - testInstance2: - path: somePath2 - loadBalancerType: ROUND_ROBIN - contentTypeTemplate: application/vnd.newsletter.$version+json - version: v1 - required: false - aliasIsPath: '' - anotherAlias: 'myPath' - some-service: - path: io/company/department/some-service -management: - security: - enabled: false -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/application-loadbalancer.yml b/spring-cloud-zookeeper-discovery/src/test/resources/application-loadbalancer.yml deleted file mode 100644 index 0971738a1..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/application-loadbalancer.yml +++ /dev/null @@ -1,16 +0,0 @@ -spring: - application: - name: loadBalancerApp - cloud: - zookeeper: - discovery: - metadata: - testMetadataKey: testMetadataValue - uriSpec: "{scheme}://{address}:{port}/contextPath" - instance-id: loadbalancer-instance-id-123 -management: - security: - enabled: false -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/application-loadbalancerclient.yml b/spring-cloud-zookeeper-discovery/src/test/resources/application-loadbalancerclient.yml deleted file mode 100644 index e260fca96..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/application-loadbalancerclient.yml +++ /dev/null @@ -1,9 +0,0 @@ -spring.application.name: loadbalancerclient -spring.cloud.zookeeper: - dependencies: - someAlias: - path: testInstance - loadBalancerType: STICKY -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/application-nestedstructure.yml b/spring-cloud-zookeeper-discovery/src/test/resources/application-nestedstructure.yml deleted file mode 100644 index 32edee40a..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/application-nestedstructure.yml +++ /dev/null @@ -1,8 +0,0 @@ -spring.cloud.zookeeper.dependency.enabled: false -spring.application.name: me -management: - security: - enabled: false -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/application-server.yml b/spring-cloud-zookeeper-discovery/src/test/resources/application-server.yml deleted file mode 100644 index efff89e42..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/application-server.yml +++ /dev/null @@ -1,5 +0,0 @@ -server.port: 0 -spring.application.name: server -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR \ No newline at end of file diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/application-watcher.yml b/spring-cloud-zookeeper-discovery/src/test/resources/application-watcher.yml deleted file mode 100644 index 25c998fdb..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/application-watcher.yml +++ /dev/null @@ -1,23 +0,0 @@ -spring.application.name: some/name/without/alias -spring.cloud.zookeeper: - dependencies: - someAlias: - path: testInstance - loadBalancerType: ROUND_ROBIN - contentTypeTemplate: application/vnd.newsletter.$version+json - version: v1 - headers: - header1: - - value1 - header2: - - value2 - required: false - testInstance2: - path: somePath2 - loadBalancerType: ROUND_ROBIN - contentTypeTemplate: application/vnd.newsletter.$version+json2 - version: v1 - required: false -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR \ No newline at end of file diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/application.yml b/spring-cloud-zookeeper-discovery/src/test/resources/application.yml deleted file mode 100644 index 18fc3feef..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/application.yml +++ /dev/null @@ -1,4 +0,0 @@ -testInstance.loadbalancer.ServerListRefreshInterval: 100 -logging: - level: - org.apache.zookeeper.ClientCnxn: ERROR \ No newline at end of file diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/bootstrapper.yaml b/spring-cloud-zookeeper-discovery/src/test/resources/bootstrapper.yaml deleted file mode 100644 index 7cde1d1b5..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/bootstrapper.yaml +++ /dev/null @@ -1,8 +0,0 @@ -spring: - config: - import: "optional:configserver:" - cloud: - config: - discovery: - service-id: zookeeper-configserver - enabled: true diff --git a/spring-cloud-zookeeper-discovery/src/test/resources/logback-test.xml b/spring-cloud-zookeeper-discovery/src/test/resources/logback-test.xml deleted file mode 100644 index 276cbbd2e..000000000 --- a/spring-cloud-zookeeper-discovery/src/test/resources/logback-test.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-cloud-zookeeper-sample/.flattened-pom.xml b/spring-cloud-zookeeper-sample/.flattened-pom.xml new file mode 100644 index 000000000..69f5feb7f --- /dev/null +++ b/spring-cloud-zookeeper-sample/.flattened-pom.xml @@ -0,0 +1,125 @@ + + + 4.0.0 + + org.springframework.cloud + spring-cloud-zookeeper + 4.1.0-SNAPSHOT + .. + + org.springframework.cloud + spring-cloud-zookeeper-sample + 4.1.0-SNAPSHOT + Spring Cloud Zookeeper Sample + Spring Cloud Zookeeper Sample + https://spring.io/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-sample + + Pivotal Software, Inc. + https://www.spring.io + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + Copyright 2014-2021 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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + + See the License for the specific language governing permissions and + limitations under the License. + + + + + dsyer + Dave Syer + dsyer at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + sgibb + Spencer Gibb + sgibb at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + lead + + + + mgrzejszczak + Marcin Grzejszczak + mgrzejszczak at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + rbaxter + Ryan Baxter + rbaxter at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + omaciaszeksharma + Olga Maciaszek-Sharma + omaciaszeksharma at pivotal.io + Pivotal Software, Inc. + https://www.spring.io + + developer + + + + + scm:git:git://github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-sample + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-zookeeper.git/spring-cloud-zookeeper-sample + https://github.com/spring-cloud/spring-cloud-zookeeper/spring-cloud-zookeeper-sample + + + + org.springframework.cloud + spring-cloud-starter-zookeeper-all + 4.1.0-SNAPSHOT + compile + + + org.springframework.boot + spring-boot-starter-web + 3.2.0-SNAPSHOT + compile + + + org.springframework.boot + spring-boot-starter-actuator + 3.2.0-SNAPSHOT + compile + + + org.springframework.cloud + spring-cloud-starter-openfeign + 4.1.0-SNAPSHOT + compile + + + diff --git a/spring-cloud-zookeeper-sample/pom.xml b/spring-cloud-zookeeper-sample/pom.xml deleted file mode 100644 index f1dae3bb8..000000000 --- a/spring-cloud-zookeeper-sample/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - 4.0.0 - - spring-cloud-zookeeper-sample - jar - Spring Cloud Zookeeper Sample - Spring Cloud Zookeeper Sample - - - org.springframework.cloud - spring-cloud-zookeeper - 4.1.0-SNAPSHOT - .. - - - - true - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - maven-deploy-plugin - - true - - - - - - - - org.springframework.cloud - spring-cloud-starter-zookeeper-all - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.cloud - spring-cloud-starter-openfeign - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - test - - - org.apache.curator - curator-test - test - - - org.springframework.cloud - spring-cloud-zookeeper-core - ${project.version} - test-jar - test - - - org.springframework.cloud - spring-cloud-test-support - test - - - - diff --git a/spring-cloud-zookeeper-sample/src/main/java/org/springframework/cloud/zookeeper/sample/SampleZookeeperApplication.java b/spring-cloud-zookeeper-sample/src/main/java/org/springframework/cloud/zookeeper/sample/SampleZookeeperApplication.java deleted file mode 100644 index cb0519457..000000000 --- a/spring-cloud-zookeeper-sample/src/main/java/org/springframework/cloud/zookeeper/sample/SampleZookeeperApplication.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.sample; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -/** - * @author Spencer Gibb - */ -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@RestController -@EnableFeignClients -public class SampleZookeeperApplication { - - @Value("${spring.application.name:testZookeeperApp}") - private String appName; - - @Autowired - private LoadBalancerClient loadBalancer; - - @Autowired - private DiscoveryClient discovery; - - @Autowired - private Environment env; - - @Autowired - private AppClient appClient; - - @Autowired(required = false) - private Registration registration; - - private RestTemplate rest; - - @RequestMapping("/") - public ServiceInstance lb() { - return this.loadBalancer.choose(this.appName); - } - - @RequestMapping("/hi") - public String hi() { - return "Hello World! from " + this.registration; - } - - @RequestMapping("/self") - public String self() { - return this.appClient.hi(); - } - - @RequestMapping("/myenv") - public String env(@RequestParam("prop") String prop) { - return this.env.getProperty(prop, "Not Found"); - } - - public String rt() { - return this.rest.getForObject("http://" + this.appName + "/hi", String.class); - } - - @Bean - @LoadBalanced - RestTemplate loadBalancedRestTemplate() { - this.rest = new RestTemplateBuilder().build(); - return this.rest; - } - - public static void main(String[] args) { - SpringApplication.run(SampleZookeeperApplication.class, args); - } - - @FeignClient("testZookeeperApp") - interface AppClient { - - @RequestMapping(path = "/hi", method = RequestMethod.GET) - String hi(); - - } - -} diff --git a/spring-cloud-zookeeper-sample/src/main/resources/application.yml b/spring-cloud-zookeeper-sample/src/main/resources/application.yml deleted file mode 100644 index 21ce589d0..000000000 --- a/spring-cloud-zookeeper-sample/src/main/resources/application.yml +++ /dev/null @@ -1,20 +0,0 @@ -server: - port: 8080 - -endpoints: - restart: - enabled: true - shutdown: - enabled: true - health: - sensitive: false - -logging.level: - org.apache.zookeeper.ClientCnxn: ERROR - -management: - security: - enabled: false - -#spring.cloud.zookeeper.dependencies: -# - testZookeeperApp: ~ \ No newline at end of file diff --git a/spring-cloud-zookeeper-sample/src/main/resources/bootstrap.yml b/spring-cloud-zookeeper-sample/src/main/resources/bootstrap.yml deleted file mode 100644 index 9a9223ee8..000000000 --- a/spring-cloud-zookeeper-sample/src/main/resources/bootstrap.yml +++ /dev/null @@ -1,3 +0,0 @@ -spring: - application: - name: testZookeeperApp diff --git a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/SampleApplicationTests.java b/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/SampleApplicationTests.java deleted file mode 100644 index a8ac137f9..000000000 --- a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/SampleApplicationTests.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.sample; - -import org.apache.curator.test.TestingServer; -import org.junit.Test; - -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.test.TestSocketUtils; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import static org.assertj.core.api.Assertions.assertThat; - -public class SampleApplicationTests { - - @Test - public void contextLoads() throws Exception { - int zkPort = TestSocketUtils.findAvailableTcpPort(); - TestingServer server = new TestingServer(zkPort); - - int port = TestSocketUtils.findAvailableTcpPort(zkPort + 1); - - ConfigurableApplicationContext context = new SpringApplicationBuilder( - SampleZookeeperApplication.class).run("--server.port=" + port, - "--spring.config.use-legacy-processing=true", - "--management.endpoints.web.exposure.include=*", - "--spring.cloud.zookeeper.connect-string=localhost:" + zkPort); - - ResponseEntity response = new TestRestTemplate() - .getForEntity("http://localhost:" + port + "/hi", String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - - context.close(); - server.close(); - } - -} diff --git a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperConfigDataOrderingIntegrationTests.java b/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperConfigDataOrderingIntegrationTests.java deleted file mode 100644 index 4df7aeef8..000000000 --- a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperConfigDataOrderingIntegrationTests.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2018-2021 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.sample; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.imps.CuratorFrameworkState; -import org.apache.curator.retry.RetryOneTime; -import org.apache.zookeeper.KeeperException; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.cloud.zookeeper.ZookeeperProperties; -import org.springframework.cloud.zookeeper.config.ZookeeperConfigProperties; -import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@SpringBootTest(classes = SampleZookeeperApplication.class, - properties = { "spring.application.name=" + ZookeeperConfigDataOrderingIntegrationTests.APP_NAME, - "spring.config.name=orderingtest", "spring.profiles.active=dev", - "management.endpoints.web.exposure.include=*", "management.endpoint.env.show-values=ALWAYS" }, - webEnvironment = RANDOM_PORT) -public class ZookeeperConfigDataOrderingIntegrationTests { - - private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - - static final String APP_NAME = "testZkConfigDataOrderingIntegration"; - - private static final String PREFIX = "_configDataOrderingIntegrationTests_config__"; - - private static final String ROOT = "/" + PREFIX + UUID.randomUUID(); - - private static final String VALUE = "my value from zk default profile"; - - private static final String TEST_PROP = "my.prop"; - - private static final String KEY = ROOT + "/" + APP_NAME + "/" + TEST_PROP; - - private static final String VALUE_PROFILE = "my value from zk dev profile"; - - private static final String KEY_PROFILE = ROOT + "/" + APP_NAME + ",dev/" + TEST_PROP; - private static ZookeeperTestingServer testingServer; - private static CuratorFramework curator; - - @Autowired - private Environment env; - - @BeforeAll - public static void initialize() throws Exception { - testingServer = new ZookeeperTestingServer(); - testingServer.start(); - System.setProperty(ZookeeperProperties.PREFIX + ".connect-string", "localhost:" + testingServer.getPort()); - System.setProperty(ZookeeperConfigProperties.PREFIX + ".root", ROOT); - String connectString = "localhost:" + testingServer.getPort(); - curator = CuratorFrameworkFactory.builder() - .retryPolicy(new RetryOneTime(500)).connectString(connectString).build(); - curator.start(); - List children = curator.getChildren().forPath("/"); - for (String child : children) { - if (child.startsWith(PREFIX) && child.length() > PREFIX.length()) { - delete("/" + child); - } - } - - StringBuilder create = new StringBuilder(1024); - create.append(curator.create().creatingParentsIfNeeded() - .forPath(KEY, VALUE.getBytes())).append('\n'); - create.append(curator.create().creatingParentsIfNeeded() - .forPath(KEY_PROFILE, VALUE_PROFILE.getBytes())).append('\n'); - curator.close(); - System.out.println(create); - } - - public static void delete(String path) throws Exception { - try { - if (curator.getState() == CuratorFrameworkState.STARTED) { - curator.delete().deletingChildrenIfNeeded().forPath(path); - } - } - catch (KeeperException e) { - if (e.code() != KeeperException.Code.NONODE) { - throw e; - } - } - } - @AfterAll - public static void close() throws Exception { - try { - delete(ROOT); - } - finally { - testingServer.close(); - } - System.clearProperty(ZookeeperProperties.PREFIX + ".connect-string"); - } - - @Test - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void contextLoads() { - Integer port = env.getProperty("local.server.port", Integer.class); - ResponseEntity response = new TestRestTemplate() - .getForEntity("http://localhost:" + port + BASE_PATH + "/env/my.prop", Map.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - Map res = response.getBody(); - assertThat(res).containsKey("propertySources"); - Map property = (Map) res.get("property"); - assertThat(property).containsEntry("value", VALUE_PROFILE); - } - -} diff --git a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperDisabledTests.java b/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperDisabledTests.java deleted file mode 100644 index 3fab5ab30..000000000 --- a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperDisabledTests.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.zookeeper.sample; - -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.cloud.zookeeper.ZookeeperAutoConfiguration; -import org.springframework.cloud.zookeeper.config.ZookeeperConfigAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.dependency.DependencyFeignClientAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.dependency.DependencyRestTemplateAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependenciesAutoConfiguration; -import org.springframework.cloud.zookeeper.discovery.watcher.DependencyWatcherAutoConfiguration; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperAutoServiceRegistrationAutoConfiguration; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistryAutoConfiguration; -import org.springframework.cloud.zookeeper.support.CuratorServiceDiscoveryAutoConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SampleZookeeperApplication.class, webEnvironment = RANDOM_PORT, - properties = "spring.cloud.zookeeper.enabled=false") -public class ZookeeperDisabledTests { - - @Autowired(required = false) - private ZookeeperAutoConfiguration zookeeperAutoConfiguration; - - @Autowired(required = false) - private ZookeeperConfigAutoConfiguration zookeeperConfigAutoConfiguration; - - @Autowired(required = false) - private ZookeeperDiscoveryAutoConfiguration zookeeperDiscoveryAutoConfiguration; - - @Autowired(required = false) - private DependencyFeignClientAutoConfiguration dependencyFeignClientAutoConfiguration; - - @Autowired(required = false) - private DependencyRestTemplateAutoConfiguration dependencyRestTemplateAutoConfiguration; - - @Autowired(required = false) - private ZookeeperDependenciesAutoConfiguration zookeeperDependenciesAutoConfiguration; - - @Autowired(required = false) - private DependencyWatcherAutoConfiguration dependencyWatcherAutoConfiguration; - - @Autowired(required = false) - private ZookeeperAutoServiceRegistrationAutoConfiguration zookeeperAutoServiceRegistrationAutoConfiguration; - - @Autowired(required = false) - private ZookeeperServiceRegistryAutoConfiguration zookeeperServiceRegistryAutoConfiguration; - - @Autowired(required = false) - private CuratorServiceDiscoveryAutoConfiguration curatorServiceDiscoveryAutoConfiguration; - - @Test - public void allPartsOfZookeeperDisabled() throws Exception { - assertThat(this.zookeeperAutoConfiguration) - .as("ZookeeperAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperConfigAutoConfiguration) - .as("ZookeeperConfigAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperDiscoveryAutoConfiguration) - .as("ZookeeperDiscoveryAutoConfiguration was not disabled").isNull(); - assertThat(this.dependencyFeignClientAutoConfiguration) - .as("DependencyFeignClientAutoConfiguration was not disabled").isNull(); - assertThat(this.dependencyRestTemplateAutoConfiguration) - .as("DependencyRestTemplateAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperDependenciesAutoConfiguration) - .as("ZookeeperDependenciesAutoConfiguration was not disabled").isNull(); - assertThat(this.dependencyWatcherAutoConfiguration) - .as("DependencyWatcherAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperAutoServiceRegistrationAutoConfiguration) - .as("ZookeeperAutoServiceRegistrationAutoConfiguration was not disabled") - .isNull(); - assertThat(this.zookeeperServiceRegistryAutoConfiguration) - .as("ZookeeperServiceRegistryAutoConfiguration was not disabled") - .isNull(); - assertThat(this.curatorServiceDiscoveryAutoConfiguration) - .as("CuratorServiceDiscoveryAutoConfiguration was not disabled").isNull(); - - } - -} diff --git a/spring-cloud-zookeeper-sample/src/test/resources/orderingtest-dev.properties b/spring-cloud-zookeeper-sample/src/test/resources/orderingtest-dev.properties deleted file mode 100644 index 9ca92ca8d..000000000 --- a/spring-cloud-zookeeper-sample/src/test/resources/orderingtest-dev.properties +++ /dev/null @@ -1 +0,0 @@ -my.prop=my value from local dev profile diff --git a/spring-cloud-zookeeper-sample/src/test/resources/orderingtest.properties b/spring-cloud-zookeeper-sample/src/test/resources/orderingtest.properties deleted file mode 100644 index f094a8902..000000000 --- a/spring-cloud-zookeeper-sample/src/test/resources/orderingtest.properties +++ /dev/null @@ -1 +0,0 @@ -spring.config.import=zookeeper: diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml deleted file mode 100644 index 6a8d857d3..000000000 --- a/src/checkstyle/checkstyle-suppressions.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - \ No newline at end of file diff --git a/supplemental-ui/partials/nav-search.hbs b/supplemental-ui/partials/nav-search.hbs new file mode 100644 index 000000000..5e3795528 --- /dev/null +++ b/supplemental-ui/partials/nav-search.hbs @@ -0,0 +1,11 @@ +{{#if env.ALGOLIA_API_KEY}} +

    +{{/if}} diff --git a/supplemental-ui/partials/search.hbs b/supplemental-ui/partials/search.hbs new file mode 100644 index 000000000..384e505f6 --- /dev/null +++ b/supplemental-ui/partials/search.hbs @@ -0,0 +1,27 @@ + +{{#if env.ALGOLIA_API_KEY}} + + + + + + + + +{{/if}}