Merge branch 'develop' into asoc#8458.t

# Conflicts:
#	client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java
#	common/src/main/java/com/alibaba/nacos/common/remote/client/ConnectionEventListener.java
#	common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java
#	common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java
#	common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java
#	core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java
#	core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcBiStreamRequestAcceptor.java
#	core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java
This commit is contained in:
Daydreamer-ia 2023-06-22 15:33:05 +08:00
commit fc3bb2f42c
1296 changed files with 69512 additions and 50237 deletions

View File

@ -1,7 +1,7 @@
# This workflow will build a Java project with Maven # 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 # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Continuous Integration name: "Continuous Integration"
on: on:
push: push:
@ -9,33 +9,41 @@ on:
pull_request: pull_request:
branches: [ develop, v1.x-develop ] branches: [ develop, v1.x-develop ]
permissions:
contents: read # to fetch code (actions/checkout)
jobs: jobs:
unix: ci:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest] os: [ubuntu-latest]
java: [8] java: [8]
steps: steps:
- name: Cache Maven Repos - name: "Cache Maven Repos"
uses: actions/cache@v2 uses: actions/cache@v3
with: with:
path: ~/.m2/repository path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: | restore-keys: |
${{ runner.os }}-maven- ${{ runner.os }}-maven-
- uses: actions/checkout@v2 - name: "Checkout"
- name: Set up JDK ${{ matrix.java }} uses: actions/checkout@v3
uses: actions/setup-java@v1 - name: "Set up JDK ${{ matrix.java }}"
uses: actions/setup-java@v3
with: with:
java-version: ${{ matrix.java }} java-version: ${{ matrix.java }}
- name: Check with Maven distribution: 'zulu'
run: mvn -B clean package apache-rat:check findbugs:findbugs -Dmaven.test.skip=true architecture: x64
- name: Build with Maven - name: "Print maven version"
run: mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U run: mvn -version
- name: Test With Maven - name: "Check with Maven"
run: mvn -Prelease-nacos clean test -DtrimStackTrace=false run: mvn -B clean package apache-rat:check findbugs:findbugs -DskipTests -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: Codecov - name: "Build with Maven"
run: mvn -Prelease-nacos -DskipTests clean install -U -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Test With Maven"
run: mvn -Prelease-nacos clean test -DtrimStackTrace=false -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Codecov"
uses: codecov/codecov-action@v3.1.0 uses: codecov/codecov-action@v3.1.0
with: with:
files: ./address/target/site/jacoco/jacoco.xml,./api/target/site/jacoco/jacoco.xml,./auth/target/site/jacoco/jacoco.xml,./client/target/site/jacoco/jacoco.xml,./common/target/site/jacoco/jacoco.xml,./consistency/target/site/jacoco/jacoco.xml,./console/target/site/jacoco/jacoco.xml,./core/target/site/jacoco/jacoco.xml,./naming/target/site/jacoco/jacoco.xml,./plugin-default-impl/target/site/jacoco/jacoco.xml,./plugin/auth/target/site/jacoco/jacoco.xml,./plugin/encryption/target/site/jacoco/jacoco.xml,./sys/target/site/jacoco/jacoco.xml files: ./address/target/site/jacoco/jacoco.xml,./api/target/site/jacoco/jacoco.xml,./auth/target/site/jacoco/jacoco.xml,./client/target/site/jacoco/jacoco.xml,./common/target/site/jacoco/jacoco.xml,./consistency/target/site/jacoco/jacoco.xml,./console/target/site/jacoco/jacoco.xml,./core/target/site/jacoco/jacoco.xml,./naming/target/site/jacoco/jacoco.xml,./plugin-default-impl/target/site/jacoco/jacoco.xml,./plugin/auth/target/site/jacoco/jacoco.xml,./plugin/encryption/target/site/jacoco/jacoco.xml,./sys/target/site/jacoco/jacoco.xml

View File

@ -1,7 +1,7 @@
# This workflow will build a Java project with Maven # 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 # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Integration Test name: "Integration Test"
on: on:
push: push:
@ -9,34 +9,40 @@ on:
pull_request: pull_request:
branches: [ develop, v1.x-develop ] branches: [ develop, v1.x-develop ]
permissions:
contents: read # to fetch code (actions/checkout)
jobs: jobs:
unix: test:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest] os: [ubuntu-latest]
java: [8, 8.0.192, 11, 11.0.3] java: [8, 8.0.192, 11, 11.0.3]
steps: steps:
- name: Cache Maven Repos - name: "Cache Maven Repos"
uses: actions/cache@v2 uses: actions/cache@v3
with: with:
path: ~/.m2/repository path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: | restore-keys: |
${{ runner.os }}-maven- ${{ runner.os }}-maven-
- uses: actions/checkout@v2 - name: "Checkout"
- name: Set up JDK ${{ matrix.java }} uses: actions/checkout@v3
uses: actions/setup-java@v2 - name: "Set up JDK ${{ matrix.java }}"
uses: actions/setup-java@v3
with: with:
java-version: ${{ matrix.java }} java-version: ${{ matrix.java }}
distribution: 'zulu' distribution: 'zulu'
architecture: x64 architecture: x64
- name: Test Config - name: "Print maven version"
run: mvn clean package -Pcit-test run: mvn -version
- name: Clean Env - name: "Test Config"
run: mvn clean -Premove-test-data run: mvn clean package -Pcit-test -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: Test Naming - name: "Clean Env"
run: mvn clean package -Pnit-test run: mvn clean -Premove-test-data -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: Clean Env - name: "Test Naming"
run: mvn clean -Premove-test-data run: mvn clean package -Pnit-test -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Clean Env"
run: mvn clean -Premove-test-data -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn

36
.github/workflows/pr-ci.yml vendored Normal file
View File

@ -0,0 +1,36 @@
name: PR-CI
on:
pull_request:
branches: [ develop, v1.x-develop ]
jobs:
dist-tar:
name: Build distribution tar
runs-on: ubuntu-latest
timeout-minutes: 120
steps:
- uses: actions/checkout@v3
with:
submodules: true
- uses: actions/setup-java@v3
with:
distribution: "temurin"
java-version: "8"
cache: "maven"
- name: Build distribution tar
run: |
mvn -Prelease-nacos -DskipTests clean install -U -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- uses: actions/upload-artifact@v3
name: Upload distribution tar
with:
name: nacos
path: distribution/target/nacos-server-*-SNAPSHOT.tar.gz
- name: Save PR number
run: |
mkdir -p ./pr
echo ${{ github.event.number }} > ./pr/NR
- uses: actions/upload-artifact@v2
with:
name: pr
path: pr/

210
.github/workflows/pr-e2e-test.yml vendored Normal file
View File

@ -0,0 +1,210 @@
name: E2E test for pull request
on:
workflow_run:
workflows: ["PR-CI"]
types:
- completed
env:
DOCKER_REPO: wuyfeedocker/nacos-ci
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
jobs:
docker:
runs-on: ubuntu-latest
if: >
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'success'
timeout-minutes: 30
strategy:
matrix:
base-image: ["ubuntu"]
java-version: ["8"]
steps:
- name: 'Download artifact'
uses: actions/github-script@v3.1.0
with:
script: |
var artifacts = await github.actions.listWorkflowRunArtifacts({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: ${{ github.event.workflow_run.id }},
});
var matchArtifactNacos = artifacts.data.artifacts.filter((artifact) => {
return artifact.name == "nacos"
})[0];
var download = await github.actions.downloadArtifact({
owner: context.repo.owner,
repo: context.repo.repo,
artifact_id: matchArtifactNacos.id,
archive_format: 'zip',
});
var fs = require('fs');
fs.writeFileSync('${{github.workspace}}/nacos.zip', Buffer.from(download.data));
- run: |
unzip nacos.zip
mkdir nacos
cp -r nacos-* nacos/
ls
- uses: actions/checkout@v3
with:
repository: nacos-group/nacos-e2e.git
ref: main
path: nacos-e2e
- name: docker-login
uses: docker/login-action@v2
with:
registry: ${{ env.REGISTRY }}
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and save docker images
id: build-images
run: |
mv nacos-server-*-SNAPSHOT.tar.gz nacos-e2e/cicd/build
cd nacos-e2e/cicd/build
version=${{ github.event.pull_request.number || github.ref_name }}-$(uuidgen)
mkdir versionlist
touch versionlist/"${version}-`echo ${{ matrix.java-version }} | sed -e "s/:/-/g"`"
ls versionlist/
tag=${version}-$(echo ${{ matrix.java-version }} | sed -e "s/:/-/g")
echo $tag
docker build --no-cache -f Dockerfile -t ${DOCKER_REPO}:${tag} .
docker push ${DOCKER_REPO}:${tag}
- uses: actions/upload-artifact@v3
name: Upload distribution tar
with:
name: versionlist
path: nacos-e2e/cicd/build/versionlist/*
list-version:
if: always()
name: List version
needs: [docker]
runs-on: ubuntu-latest
timeout-minutes: 30
outputs:
version-json: ${{ steps.show_versions.outputs.version-json }}
steps:
- uses: actions/download-artifact@v3
name: Download versionlist
with:
name: versionlist
path: versionlist
- name: Show versions
id: show_versions
run: |
a=(`ls versionlist`)
printf '%s\n' "${a[@]}" | jq -R . | jq -s .
echo version-json=`printf '%s\n' "${a[@]}" | jq -R . | jq -s .` >> $GITHUB_OUTPUT
deploy:
if: ${{ success() }}
name: Deploy nacos
needs: [list-version,docker]
runs-on: ubuntu-latest
timeout-minutes: 60
env:
REPLICA_COUNT: 3
DATABASE: mysql
NODE_PORT: 30000
strategy:
matrix:
mode: ["cluster","standalone"]
version: ${{ fromJSON(needs.list-version.outputs.version-json) }}
steps:
- name: set nodeport
run: |
echo "::set-env name=NODE_PORT::$(expr $(expr $(expr $(expr 1 * $(expr ${{ github.run_number }} - 1)) + ${{ strategy.job-index }}) % 30000) + 30000)"
- name: set cluster params
if: ${{ matrix.mode == 'standalone' }}
run: |
echo "::set-env name=REPLICA_COUNT::1"
echo "::set-env name=DATABASE::embedded"
- uses: apache/rocketmq-test-tool@136205caa6e97f81744e30adea114dd2f09cc55e
name: Deploy nacos
with:
action: "deploy"
ask-config: "${{ secrets.ASK_CONFIG_VIRGINA }}"
test-version: "${{ matrix.version }}"
chart-git: "https://ghproxy.com/https://github.com/nacos-group/nacos-e2e.git"
chart-branch: "main"
chart-path: "./cicd/helm"
job-id: ${{ strategy.job-index }}
helm-values: |
namespace: nacos-${{ github.run_id }}-${{ strategy.job-index }}
global:
mode: ${{ matrix.mode }}
nacos:
replicaCount: ${{ env.REPLICA_COUNT }}
image:
repository: ${{ env.DOCKER_REPO }}
tag: ${{ matrix.version }}
storage:
type: ${{ env.DATABASE }}
db:
port: 3306
username: nacos
password: nacos
param: characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false
service:
nodePort: ${{ env.NODE_PORT }}
type: ClusterIP
e2e-test:
if: ${{ success() }}
name: E2E Test
needs: [list-version, deploy]
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
matrix:
mode: ["cluster","standalone"]
version: ${{ fromJSON(needs.list-version.outputs.version-json) }}
steps:
- uses: apache/rocketmq-test-tool@136205caa6e97f81744e30adea114dd2f09cc55e
name: e2e test
with:
action: "test"
ask-config: "${{ secrets.ASK_CONFIG_VIRGINA }}"
test-version: "${{ matrix.version }}"
test-code-git: "https://github.com/nacos-group/nacos-e2e.git"
test-code-branch: "master"
test-code-path: "java/nacos-2X"
test-cmd: 'mvn clean test -B -Dnacos.client.version=2.2.3'
job-id: ${{ strategy.job-index }}
- name: Publish Test Report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
report_paths: '**/test_report/TEST-*.xml'
annotate_only: true
include_passed: true
detailed_summary: true
- uses: actions/upload-artifact@v3
if: always()
name: Upload test log
with:
name: testlog.txt ${{ matrix.mode }}
path: testlog.txt
clean:
if: always()
name: Clean
needs: [list-version, e2e-test]
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
matrix:
mode: ["cluster","standalone"]
version: ${{ fromJSON(needs.list-version.outputs.version-json) }}
steps:
- uses: apache/rocketmq-test-tool@136205caa6e97f81744e30adea114dd2f09cc55e
name: clean
with:
action: "clean"
ask-config: "${{ secrets.ASK_CONFIG_VIRGINA }}"
test-version: "${{ matrix.version }}"
job-id: ${{ strategy.job-index }}

221
.github/workflows/push-ci.yaml vendored Normal file
View File

@ -0,0 +1,221 @@
name: PUSH-CI
on:
push:
branches: [master, develop, v1.x-develop, v1.X]
permissions:
contents: read # to fetch code (actions/checkout)
concurrency:
group: nacos-${{ github.ref }}
env:
DOCKER_REPO: wuyfeedocker/nacos-ci
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
jobs:
dist-tar:
name: Build dist tar
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- uses: actions/checkout@v3
with:
submodules: true
- uses: actions/setup-java@v3
with:
distribution: "temurin"
java-version: "8"
cache: "maven"
- name: Build distribution tar
run: |
mvn -Prelease-nacos -DskipTests clean install -U -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- uses: actions/upload-artifact@v3
name: Upload distribution tar
with:
name: nacos
path: distribution/target/nacos-server-*-SNAPSHOT.tar.gz
docker:
if: ${{ success() }}
name: Docker images
needs: [dist-tar]
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
matrix:
base-image: ["centos"]
java-version: ["8"]
steps:
- uses: actions/checkout@v3
with:
repository: nacos-group/nacos-e2e.git
ref: main
path: nacos-e2e
- uses: actions/download-artifact@v3
name: Download distribution tar
with:
name: nacos
path: ./
- name: docker-login
uses: docker/login-action@v2
with:
registry: ${{ env.REGISTRY }}
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and save docker images
id: build-images
run: |
mv nacos-server-*-SNAPSHOT.tar.gz nacos-e2e/cicd/build/
cd nacos-e2e/cicd/build
version=${{ github.event.pull_request.number || github.ref_name }}-$(uuidgen)
mkdir versionlist
touch versionlist/"${version}-`echo ${{ matrix.java-version }} | sed -e "s/:/-/g"`"
ls versionlist/
tag=${version}-$(echo ${{ matrix.java-version }} | sed -e "s/:/-/g")
echo $tag
docker build --no-cache -f Dockerfile -t ${DOCKER_REPO}:${tag} .
docker push ${DOCKER_REPO}:${tag}
- uses: actions/upload-artifact@v3
name: Upload distribution tar
with:
name: versionlist
path: nacos-e2e/cicd/build/versionlist/*
list-version:
if: always()
name: List version
needs: [docker]
runs-on: ubuntu-latest
timeout-minutes: 30
outputs:
version-json: ${{ steps.show_versions.outputs.version-json }}
steps:
- uses: actions/download-artifact@v3
name: Download versionlist
with:
name: versionlist
path: versionlist
- name: Show versions
id: show_versions
run: |
a=(`ls versionlist`)
printf '%s\n' "${a[@]}" | jq -R . | jq -s .
echo version-json=`printf '%s\n' "${a[@]}" | jq -R . | jq -s .` >> $GITHUB_OUTPUT
deploy:
if: ${{ success() }}
name: Deploy nacos
needs: [list-version,docker]
runs-on: ubuntu-latest
timeout-minutes: 60
env:
REPLICA_COUNT: 3
DATABASE: mysql
NODE_PORT: 30000
strategy:
matrix:
mode: ["cluster","standalone"]
version: ${{ fromJSON(needs.list-version.outputs.version-json) }}
steps:
- name: set nodeport
run: |
echo "::set-env name=NODE_PORT::$(expr $(expr $(expr $(expr 1 * $(expr ${{ github.run_number }} - 1)) + ${{ strategy.job-index }}) % 30000) + 30000)"
- name: set cluster params
if: ${{ matrix.mode == 'standalone' }}
run: |
echo "::set-env name=REPLICA_COUNT::1"
echo "::set-env name=DATABASE::embedded"
- uses: apache/rocketmq-test-tool@136205caa6e97f81744e30adea114dd2f09cc55e
name: Deploy nacos
with:
action: "deploy"
ask-config: "${{ secrets.ASK_CONFIG_VIRGINA }}"
test-version: "${{ matrix.version }}"
chart-git: "https://ghproxy.com/https://github.com/nacos-group/nacos-e2e.git"
chart-branch: "main"
chart-path: "./cicd/helm"
job-id: ${{ strategy.job-index }}
helm-values: |
namespace: nacos-${{ github.run_id }}-${{ strategy.job-index }}
global:
mode: ${{ matrix.mode }}
nacos:
replicaCount: ${{ env.REPLICA_COUNT }}
image:
repository: ${{ env.DOCKER_REPO }}
tag: ${{ matrix.version }}
storage:
type: ${{ env.DATABASE }}
db:
port: 3306
username: nacos
password: nacos
param: characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false
service:
nodePort: ${{ env.NODE_PORT }}
type: ClusterIP
e2e-test:
if: ${{ success() }}
name: E2E Test
needs: [list-version, deploy]
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
matrix:
mode: ["cluster","standalone"]
version: ${{ fromJSON(needs.list-version.outputs.version-json) }}
steps:
- uses: apache/rocketmq-test-tool@136205caa6e97f81744e30adea114dd2f09cc55e
name: e2e test
with:
action: "test"
ask-config: "${{ secrets.ASK_CONFIG_VIRGINA }}"
test-version: "${{ matrix.version }}"
test-code-git: "https://github.com/nacos-group/nacos-e2e.git"
test-code-branch: "main"
test-code-path: "java/nacos-2X"
test-cmd: 'mvn clean test -B -Dnacos.client.version=2.2.3'
job-id: ${{ strategy.job-index }}
- name: Publish Test Report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
report_paths: '**/test_report/TEST-*.xml'
annotate_only: true
include_passed: true
detailed_summary: true
- uses: actions/upload-artifact@v3
if: always()
name: Upload test log
with:
name: testlog.txt ${{ matrix.mode }}
path: testlog.txt
clean:
if: always()
name: Clean
needs: [list-version, e2e-test]
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
matrix:
mode: ["cluster","standalone"]
version: ${{ fromJSON(needs.list-version.outputs.version-json) }}
steps:
- uses: apache/rocketmq-test-tool@136205caa6e97f81744e30adea114dd2f09cc55e
name: clean
with:
action: "clean"
ask-config: "${{ secrets.ASK_CONFIG_VIRGINA }}"
test-version: "${{ matrix.version }}"
job-id: ${{ strategy.job-index }}

View File

@ -172,7 +172,7 @@
## 0.2.1-release(Sept 28, 2018) ## 0.2.1-release(Sept 28, 2018)
* FIx deregister last instance failed error. * Fix deregister last instance failed error.
* Fix url pattern error. * Fix url pattern error.
* Fully integrate with and seamlessly support Spring framework, Spring Boot and Spring Cloud * Fully integrate with and seamlessly support Spring framework, Spring Boot and Spring Cloud
* Separate nacos-api from nacos client implementation * Separate nacos-api from nacos client implementation

View File

@ -5,6 +5,7 @@
[![Gitter](https://badges.gitter.im/alibaba/nacos.svg)](https://gitter.im/alibaba/nacos?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) [![Gitter](https://badges.gitter.im/alibaba/nacos.svg)](https://gitter.im/alibaba/nacos?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html)
[![Gitter](https://travis-ci.org/alibaba/nacos.svg?branch=master)](https://travis-ci.org/alibaba/nacos) [![Gitter](https://travis-ci.org/alibaba/nacos.svg?branch=master)](https://travis-ci.org/alibaba/nacos)
[![](https://img.shields.io/badge/Nacos-Check%20Your%20Contribution-orange)](https://opensource.alibaba.com/contribution_leaderboard/details?projectValue=nacos)
------- -------
@ -83,6 +84,8 @@ For more details, see [quick-start.](https://nacos.io/en-us/docs/quick-start.htm
You can view the full documentation from the [Nacos website](https://nacos.io/en-us/docs/what-is-nacos.html). You can view the full documentation from the [Nacos website](https://nacos.io/en-us/docs/what-is-nacos.html).
You can also read this online eBook from the [NACOS ARCHITECTURE & PRINCIPLES](https://www.yuque.com/nacos/ebook/kbyo6n).
All the latest and long-term notice can also be found here from [Github notice issue](https://github.com/alibaba/nacos/labels/notice). All the latest and long-term notice can also be found here from [Github notice issue](https://github.com/alibaba/nacos/labels/notice).
## Contributing ## Contributing
@ -116,9 +119,9 @@ Contributors are welcomed to join Nacos project. Please check [CONTRIBUTING](./C
* users-nacos@googlegroups.com: Nacos usage general discussion. * users-nacos@googlegroups.com: Nacos usage general discussion.
* dev-nacos@googlegroups.com: Nacos developer discussion (APIs, feature design, etc). * dev-nacos@googlegroups.com: Nacos developer discussion (APIs, feature design, etc).
* commits-nacos@googlegroups.com: Commits notice, very high frequency. * commits-nacos@googlegroups.com: Commits notice, very high frequency.
* Join us from DingDing(Group 1: 21708933(full), Group 2: 30438813). * Join us from DingDing(Group 1: 21708933(full), Group 2: 30438813(full), Group 3: 31222241(full), Group 4: 12810027056).
![Nacos](https://nacos.io/img/nacos_dingding.jpg) ![Nacos](https://img.alicdn.com/imgextra/i1/O1CN01ULSVXu1DRbANwVC6r_!!6000000000213-2-tps-666-884.png)
## Enterprise Service ## Enterprise Service
If you need Nacos enterprise service support, or purchase cloud product services, you can join the discussion by scanning the following DingTalk group. It can also be directly activated and used through the microservice engine (MSE) provided by Alibaba Cloud. If you need Nacos enterprise service support, or purchase cloud product services, you can join the discussion by scanning the following DingTalk group. It can also be directly activated and used through the microservice engine (MSE) provided by Alibaba Cloud.
@ -146,31 +149,19 @@ These are only part of the companies using Nacos, for reference only. If you are
![瑞安农村商业银行](https://img.alicdn.com/tfs/TB1lxu7EBLoK1RjSZFuXXXn0XXa-409-74.png) ![瑞安农村商业银行](https://img.alicdn.com/tfs/TB1lxu7EBLoK1RjSZFuXXXn0XXa-409-74.png)
![司法大数据](https://img.alicdn.com/tfs/TB1L16eEzTpK1RjSZKPXXa3UpXa-302-50.png) ![司法大数据](https://img.alicdn.com/tfs/TB1L16eEzTpK1RjSZKPXXa3UpXa-302-50.png)
![搜易贷](https://www.souyidai.com/www-style/images/logo.gif) ![搜易贷](https://www.souyidai.com/www-style/images/logo.gif)
![美菜](https://www.meicai.cn/assets/images/new-img/logo.png)
![松格科技](http://songe.so/images/logo.gif)
![平行云](https://img.alicdn.com/tfs/TB1OigyDyLaK1RjSZFxXXamPFXa-168-70.png) ![平行云](https://img.alicdn.com/tfs/TB1OigyDyLaK1RjSZFxXXamPFXa-168-70.png)
![甘肃紫光](https://img.alicdn.com/tfs/TB1gJ4vIhTpK1RjSZR0XXbEwXXa-462-60.jpg) ![甘肃紫光](https://img.alicdn.com/tfs/TB1gJ4vIhTpK1RjSZR0XXbEwXXa-462-60.jpg)
![海云天](http://www.seaskylight.com/cn/uploadfiles/image/logo.png) ![海云天](http://www.seaskylight.com/cn/uploadfiles/image/logo.png)
![集萃智能](http://www.iimt.org.cn/pic/logosy.png)
![Acmedcare+](https://img.alicdn.com/tfs/TB1DZWSEzDpK1RjSZFrXXa78VXa-240-62.png) ![Acmedcare+](https://img.alicdn.com/tfs/TB1DZWSEzDpK1RjSZFrXXa78VXa-240-62.png)
![吾享](https://w.wuuxiang.com/theme/images/common/logo1.png)
![北京天合互联信息有限公司](https://14605854.s21i.faiusr.com/4/ABUIABAEGAAg4OvkzwUo8b-qlwUwxQ449gM!300x300.png) ![北京天合互联信息有限公司](https://14605854.s21i.faiusr.com/4/ABUIABAEGAAg4OvkzwUo8b-qlwUwxQ449gM!300x300.png)
![上海密尔克卫化工](http://www.mwclg.com/static-resource/front/images/home/img_logo_nav.png) ![上海密尔克卫化工](http://www.mwclg.com/static-resource/front/images/home/img_logo_nav.png)
![大连新唯](https://www.synwe.com/logo-full.png) ![大连新唯](https://www.synwe.com/logo-full.png)
![立思辰](https://user-images.githubusercontent.com/10215557/51593180-7563af00-1f2c-11e9-95b1-ec2c645d6a0b.png) ![立思辰](https://user-images.githubusercontent.com/10215557/51593180-7563af00-1f2c-11e9-95b1-ec2c645d6a0b.png)
![拓深科技](http://www.tpson.cn/images/new/icon/LOGO_1.png)
![东家](https://img.alicdn.com/tfs/TB1zWW2EpYqK1RjSZLeXXbXppXa-262-81.png) ![东家](https://img.alicdn.com/tfs/TB1zWW2EpYqK1RjSZLeXXbXppXa-262-81.png)
![上海克垚](http://www.sh-guiyao.com/images/logo.jpg) ![上海克垚](http://www.sh-guiyao.com/images/logo.jpg)
![郑州山水](http://www.zzssxx.com/style/images/logo.png)
![联采科技](http://www.lckjep.com:80//theme/img/logoTop.png) ![联采科技](http://www.lckjep.com:80//theme/img/logoTop.png)
![南京28研究所](https://img.alicdn.com/tfs/TB1G216EsbpK1RjSZFyXXX_qFXa-325-53.jpg) ![南京28研究所](https://img.alicdn.com/tfs/TB1G216EsbpK1RjSZFyXXX_qFXa-325-53.jpg)
![长亮科技](http://www.sunline.cn/Uploads/image/20170724/59759a405c3b2.png)
![深圳易停车库](http://www.ytparking.com/yiting/images/logo.png)
![凤凰网-汽车](https://p1.ifengimg.com/auto/image/2017/0922/auto_logo.png) ![凤凰网-汽车](https://p1.ifengimg.com/auto/image/2017/0922/auto_logo.png)
![武汉日创科技](http://www.dragonwake.cn/static/css/default/images/logo.png)
![易管智能](http://ebmsw.mro1598.com/UpLoadFile/MainCompany/20170308-1501-495c-a62f-fc03424f86f1/20170405/20170405-1056-4fe5-90e8-c055f8a1bb23.png)
![云帐房](http://www.yunzhangfang.com/yzf-pc/img/logo.png)
![知氏教育](https://www.chyeth.com/622e88980a5d091eaa6449f82d48ca43.png)
![中化信息](http://www.sinochem.com/Portals/0/xinlogo.png) ![中化信息](http://www.sinochem.com/Portals/0/xinlogo.png)
![一点车](https://img.alicdn.com/tfs/TB1DXerNgDqK1RjSZSyXXaxEVXa-333-103.png) ![一点车](https://img.alicdn.com/tfs/TB1DXerNgDqK1RjSZSyXXaxEVXa-333-103.png)
![明传无线](https://img.alicdn.com/tfs/TB1VfOANgHqK1RjSZFPXXcwapXa-313-40.png) ![明传无线](https://img.alicdn.com/tfs/TB1VfOANgHqK1RjSZFPXXcwapXa-313-40.png)
@ -193,12 +184,22 @@ These are only part of the companies using Nacos, for reference only. If you are
![康美](https://img.alicdn.com/tfs/TB19RCANgHqK1RjSZFPXXcwapXa-180-180.jpg) ![康美](https://img.alicdn.com/tfs/TB19RCANgHqK1RjSZFPXXcwapXa-180-180.jpg)
![环球易购](https://img.alicdn.com/tfs/TB1iCGyNb2pK1RjSZFsXXaNlXXa-143-143.jpg) ![环球易购](https://img.alicdn.com/tfs/TB1iCGyNb2pK1RjSZFsXXaNlXXa-143-143.jpg)
![Nepxion](https://avatars0.githubusercontent.com/u/16344119?s=200&v=4) ![Nepxion](https://avatars0.githubusercontent.com/u/16344119?s=200&v=4)
![东莞最佳拍档](https://img.alicdn.com/tfs/TB11ugsDzTpK1RjSZKPXXa3UpXa-300-300.png)
![chigua](https://img.alicdn.com/tfs/TB1aUe5EpzqK1RjSZSgXXcpAVXa-248-124.png) ![chigua](https://img.alicdn.com/tfs/TB1aUe5EpzqK1RjSZSgXXcpAVXa-248-124.png)
![宅无限](https://img.alicdn.com/tfs/TB1H9O5EAvoK1RjSZFNXXcxMVXa-221-221.jpg) ![宅无限](https://img.alicdn.com/tfs/TB1H9O5EAvoK1RjSZFNXXcxMVXa-221-221.jpg)
![天阙](https://img.alicdn.com/tfs/TB1rNq4EwHqK1RjSZFgXXa7JXXa-200-200.jpg) ![天阙](https://img.alicdn.com/tfs/TB1rNq4EwHqK1RjSZFgXXa7JXXa-200-200.jpg)
![联合永道](https://img.alicdn.com/tfs/TB1CRAxDxYaK1RjSZFnXXa80pXa-190-190.jpg) ![联合永道](https://img.alicdn.com/tfs/TB1CRAxDxYaK1RjSZFnXXa80pXa-190-190.jpg)
![明源云](https://img.alicdn.com/tfs/TB1.q14ErrpK1RjSZTEXXcWAVXa-219-219.jpg) ![明源云](https://img.alicdn.com/tfs/TB1.q14ErrpK1RjSZTEXXcWAVXa-219-219.jpg)
![三诺生物](http://www.sinocare.com/public/static/images/logored6000321.png) ![DaoCloud](https://www.daocloud.io/static/Logo-Light.png)
![美菜](https://www.meicai.cn/img/logo.9210b6eb.jpg)
![松格科技](https://img5.tianyancha.com/logo/lll/3aad34039972b57e70874df8c919ae8b.png@!f_200x200)
![集萃智能](https://www.jsic-tech.com/Public/uploads/20191206/5de9b9baac696.jpg)
![吾享](https://www.wuuxiang.com/theme/images/common/logo1.png)
![拓深科技](http://www.tpson.cn/static/upload/image/20230111/1673427385140440.png)
![长亮科技](https://www.sunline.cn/u_file/fileUpload/2021-06/25/2021062586431.png)
![深圳易停车库](http://pmt2f499f.pic44.websiteonline.cn/upload/wv0c.png)
![武汉日创科技](http://www.dragonwake.cn/static/css/default/img/logo.png)
![易管智能](https://i4im-web.oss-cn-shanghai.aliyuncs.com/images/logo.png)
![云帐房](https://www.yunzhangfang.com/assets/img/logo.4096cf52.png)
![三诺生物](https://www.sinocare.com/sannuo/templates/web/img/bocweb-logo.svg)
郑州山水, 知氏教育

View File

@ -1,6 +1,6 @@
# How to report bugs # How to report bugs
If any part of the Nacos project has bugs or documentation mistakes, please let us know by [opening an issue][Nacos-issue]. We treat bugs and mistakes very seriously and believe no issue is too small, anyOne is implement. Before creating a bug report, please check that an issue reporting the same problem does not already exist. If any part of the Nacos project has bugs or documentation mistakes, please let us know by [opening an issue][Nacos-issue]. We treat bugs and mistakes very seriously and believe no issue is too small, anyone is implement. Before creating a bug report, please check that an issue reporting the same problem does not already exist.
To make the bug report accurate and easy to understand, please try to create bug reports that are: To make the bug report accurate and easy to understand, please try to create bug reports that are:

View File

@ -27,13 +27,7 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<name>nacos-address ${project.version}</name> <name>nacos-address ${project.version}</name>
<url>http://nacos.io</url> <url>https://nacos.io</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies> <dependencies>
<dependency> <dependency>

View File

@ -18,8 +18,8 @@ package com.alibaba.nacos.address.component;
import com.alibaba.nacos.address.constant.AddressServerConstants; import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.utils.InternetAddressUtil; import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -76,9 +76,9 @@ public class AddressServerGeneratorManager {
instance.setPort(Integer.parseInt(ipAndPort[1])); instance.setPort(Integer.parseInt(ipAndPort[1]));
instance.setClusterName(clusterName); instance.setClusterName(clusterName);
instance.setServiceName(serviceName); instance.setServiceName(serviceName);
instance.setTenant(Constants.DEFAULT_NAMESPACE_ID);
instance.setApp(rawProductName);
instance.setEphemeral(false); instance.setEphemeral(false);
instance.getMetadata().put("app", rawProductName);
instance.getMetadata().put("tenant", Constants.DEFAULT_NAMESPACE_ID);
instanceList.add(instance); instanceList.add(instance);
} }
@ -99,7 +99,7 @@ public class AddressServerGeneratorManager {
* @param instanceList a instance set will generate string response to client. * @param instanceList a instance set will generate string response to client.
* @return the result of response to client * @return the result of response to client
*/ */
public String generateResponseIps(List<Instance> instanceList) { public String generateResponseIps(List<com.alibaba.nacos.api.naming.pojo.Instance> instanceList) {
StringBuilder ips = new StringBuilder(); StringBuilder ips = new StringBuilder();
instanceList.forEach(instance -> { instanceList.forEach(instance -> {

View File

@ -21,13 +21,19 @@ import com.alibaba.nacos.address.component.AddressServerManager;
import com.alibaba.nacos.address.constant.AddressServerConstants; import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.address.misc.Loggers; import com.alibaba.nacos.address.misc.Loggers;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker; import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.common.utils.InternetAddressUtil; import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.naming.core.ClusterOperator;
import com.alibaba.nacos.naming.core.InstanceOperator;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@ -36,6 +42,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
import java.util.Optional;
/** /**
* Address server cluster controller. * Address server cluster controller.
@ -47,15 +54,22 @@ import java.util.List;
@RequestMapping({AddressServerConstants.ADDRESS_SERVER_REQUEST_URL + "/nodes"}) @RequestMapping({AddressServerConstants.ADDRESS_SERVER_REQUEST_URL + "/nodes"})
public class AddressServerClusterController { public class AddressServerClusterController {
private final ServiceManager serviceManager; private final InstanceOperator instanceOperator;
private final NamingMetadataManager metadataManager;
private final ClusterOperator clusterOperator;
private final AddressServerManager addressServerManager; private final AddressServerManager addressServerManager;
private final AddressServerGeneratorManager addressServerGeneratorManager; private final AddressServerGeneratorManager addressServerGeneratorManager;
public AddressServerClusterController(ServiceManager serviceManager, AddressServerManager addressServerManager, public AddressServerClusterController(InstanceOperator instanceOperator, NamingMetadataManager metadataManager,
ClusterOperator clusterOperator, AddressServerManager addressServerManager,
AddressServerGeneratorManager addressServerGeneratorManager) { AddressServerGeneratorManager addressServerGeneratorManager) {
this.serviceManager = serviceManager; this.instanceOperator = instanceOperator;
this.metadataManager = metadataManager;
this.clusterOperator = clusterOperator;
this.addressServerManager = addressServerManager; this.addressServerManager = addressServerManager;
this.addressServerGeneratorManager = addressServerGeneratorManager; this.addressServerGeneratorManager = addressServerGeneratorManager;
} }
@ -86,23 +100,13 @@ public class AddressServerClusterController {
try { try {
String serviceName = addressServerGeneratorManager.generateNacosServiceName(productName); String serviceName = addressServerGeneratorManager.generateNacosServiceName(productName);
Cluster clusterObj = new Cluster(); Result result = registerCluster(serviceName, rawProductName, clusterName, ips);
clusterObj.setName(clusterName); if (InternetAddressUtil.checkOK(result.getCheckResult())) {
clusterObj.setHealthChecker(new AbstractHealthChecker.None());
serviceManager.createServiceIfAbsent(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, clusterObj);
String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = InternetAddressUtil.checkIPs(ipArray);
if (InternetAddressUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
for (Instance instance : instanceList) {
serviceManager.registerInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, instance);
}
responseEntity = ResponseEntity responseEntity = ResponseEntity
.ok("product=" + rawProductName + ",cluster=" + rawClusterName + "; put success with size=" .ok("product=" + rawProductName + ",cluster=" + rawClusterName + "; put success with size="
+ instanceList.size()); + result.getSize());
} else { } else {
responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(checkResult); responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result.getCheckResult());
} }
} catch (Exception e) { } catch (Exception e) {
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
@ -111,6 +115,35 @@ public class AddressServerClusterController {
return responseEntity; return responseEntity;
} }
private Result registerCluster(String serviceName, String productName, String clusterName, String ips)
throws NacosException {
String serviceWithoutGroup = NamingUtils.getServiceName(serviceName);
String groupName = NamingUtils.getGroupName(serviceName);
Service service = Service.newService(Constants.DEFAULT_NAMESPACE_ID, groupName, serviceWithoutGroup, false);
service = ServiceManager.getInstance().getSingleton(service);
if (service.isEphemeral()) {
return new Result(
String.format("Service %s is ephemeral service, can't use as address server", serviceName), 0);
}
ServiceMetadata serviceMetadata = metadataManager.getServiceMetadata(service).orElse(new ServiceMetadata());
if (!serviceMetadata.getClusters().containsKey(clusterName)) {
ClusterMetadata metadata = new ClusterMetadata();
metadata.setHealthyCheckType(AbstractHealthChecker.None.TYPE);
metadata.setHealthChecker(new AbstractHealthChecker.None());
clusterOperator.updateClusterMetadata(Constants.DEFAULT_NAMESPACE_ID, serviceName, clusterName, metadata);
}
String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = InternetAddressUtil.checkIPs(ipArray);
if (InternetAddressUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, productName, clusterName, ipArray);
for (Instance instance : instanceList) {
instanceOperator.registerInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, instance);
}
}
return new Result(checkResult, ipArray.length);
}
/** /**
* Delete cluster. * Delete cluster.
* *
@ -134,9 +167,12 @@ public class AddressServerClusterController {
try { try {
String serviceName = addressServerGeneratorManager.generateNacosServiceName(productName); String serviceName = addressServerGeneratorManager.generateNacosServiceName(productName);
Service service = serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, serviceName); String serviceWithoutGroup = NamingUtils.getServiceName(serviceName);
String groupName = NamingUtils.getGroupName(serviceName);
Optional<com.alibaba.nacos.naming.core.v2.pojo.Service> service = com.alibaba.nacos.naming.core.v2.ServiceManager
.getInstance().getSingletonIfExist(Constants.DEFAULT_NAMESPACE_ID, groupName, serviceWithoutGroup);
if (service == null) { if (!service.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("product=" + rawProductName + " not found."); return ResponseEntity.status(HttpStatus.NOT_FOUND).body("product=" + rawProductName + " not found.");
} }
if (StringUtils.isBlank(ips)) { if (StringUtils.isBlank(ips)) {
@ -149,8 +185,9 @@ public class AddressServerClusterController {
if (InternetAddressUtil.checkOK(checkResult)) { if (InternetAddressUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray); .generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
serviceManager.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, for (Instance each : instanceList) {
instanceList.toArray(new Instance[0])); instanceOperator.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, each);
}
} else { } else {
responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(checkResult); responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(checkResult);
} }
@ -162,4 +199,23 @@ public class AddressServerClusterController {
return responseEntity; return responseEntity;
} }
private class Result {
private final String checkResult;
private final int size;
public Result(String checkResult, int size) {
this.checkResult = checkResult;
this.size = size;
}
public String getCheckResult() {
return checkResult;
}
public int getSize() {
return size;
}
}
} }

View File

@ -18,9 +18,15 @@ package com.alibaba.nacos.address.controller;
import com.alibaba.nacos.address.component.AddressServerGeneratorManager; import com.alibaba.nacos.address.component.AddressServerGeneratorManager;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.utils.ServiceUtil;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@ -28,6 +34,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
/** /**
* Server list controller. * Server list controller.
* *
@ -37,14 +45,17 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
public class ServerListController { public class ServerListController {
private final ServiceManager serviceManager;
private final AddressServerGeneratorManager addressServerBuilderManager; private final AddressServerGeneratorManager addressServerBuilderManager;
public ServerListController(ServiceManager serviceManager, private final NamingMetadataManager metadataManager;
AddressServerGeneratorManager addressServerBuilderManager) {
this.serviceManager = serviceManager; private final ServiceStorage serviceStorage;
public ServerListController(AddressServerGeneratorManager addressServerBuilderManager,
NamingMetadataManager metadataManager, ServiceStorage serviceStorage) {
this.addressServerBuilderManager = addressServerBuilderManager; this.addressServerBuilderManager = addressServerBuilderManager;
this.metadataManager = metadataManager;
this.serviceStorage = serviceStorage;
} }
/** /**
@ -59,20 +70,22 @@ public class ServerListController {
String productName = addressServerBuilderManager.generateProductName(product); String productName = addressServerBuilderManager.generateProductName(product);
String serviceName = addressServerBuilderManager.generateNacosServiceName(productName); String serviceName = addressServerBuilderManager.generateNacosServiceName(productName);
Service service = serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, serviceName); String serviceWithoutGroup = NamingUtils.getServiceName(serviceName);
if (service == null) { String groupName = NamingUtils.getGroupName(serviceName);
Optional<Service> service = ServiceManager.getInstance()
.getSingletonIfExist(Constants.DEFAULT_NAMESPACE_ID, groupName, serviceWithoutGroup);
if (!service.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("product=" + product + " not found."); return ResponseEntity.status(HttpStatus.NOT_FOUND).body("product=" + product + " not found.");
} }
ClusterMetadata metadata = metadataManager.getServiceMetadata(service.get()).orElse(new ServiceMetadata())
if (!service.getClusterMap().containsKey(cluster)) { .getClusters().get(cluster);
if (null == metadata) {
return ResponseEntity.status(HttpStatus.NOT_FOUND) return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("product=" + product + ",cluster=" + cluster + " not found."); .body("product=" + product + ",cluster=" + cluster + " not found.");
} }
ServiceInfo serviceInfo = serviceStorage.getData(service.get());
Cluster clusterObj = service.getClusterMap().get(cluster); serviceInfo = ServiceUtil.selectInstances(serviceInfo, cluster, false);
return ResponseEntity.status(HttpStatus.OK) return ResponseEntity.status(HttpStatus.OK)
.body(addressServerBuilderManager.generateResponseIps(clusterObj.allIPs(false))); .body(addressServerBuilderManager.generateResponseIps(serviceInfo.getHosts()));
} }
} }

View File

@ -1,248 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.address;
import com.alibaba.nacos.common.codec.Base64;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = {
"spring.security.user.password=123456", "spring.security.user.name=user"})
public class AddressServerControllerTests {
private static final String PRODUCT_CONFIG = "config";
private static final String PRODUCT_NAMING = "naming";
private static final String HTTP_BASIC_INFO = getHttpBasicInfo();
@Autowired
private TestRestTemplate restTemplate;
@BeforeClass
public static void before() {
System.setProperty("nacos.standalone", "true");
System.setProperty("embeddedStorage", "true");
}
@AfterClass
public static void teardown() {
System.clearProperty("nacos.standalone");
System.clearProperty("embeddedStorage");
}
private static String getHttpBasicInfo() {
String userName = "user";
String password = "123456";
String info = userName + ":" + password;
final byte[] bytes = Base64.encodeBase64(info.getBytes(StandardCharsets.UTF_8));
return "Basic " + new String(bytes, StandardCharsets.UTF_8);
}
@Test
public void postClusterWithoutLogin() {
String ips = "127.0.0.100,127.0.0.102,127.0.0.104";
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", ips);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertEquals(postClusterResponseEntity.getStatusCode(), HttpStatus.UNAUTHORIZED);
}
@Test
public void postCluster() throws InterruptedException {
String ips = "127.0.0.100,127.0.0.102,127.0.0.104";
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", ips);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> getClusterResponseEntity = restTemplate.exchange(
RequestEntity.get("/nacos/serverlist").build(), String.class);
Assert.assertNotNull(getClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue());
}
@Test
public void deleteClusterWithoutLogin() {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertEquals(postClusterResponseEntity.getStatusCode(), HttpStatus.UNAUTHORIZED);
}
@Test
public void deleteCluster() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> deleteClusterResponseEntity = restTemplate.exchange(
RequestEntity.delete("/nacos/v1/as/nodes?ips={ips}", "127.0.0.104")
.header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO).build(), String.class);
Assert.assertNotNull(deleteClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue());
}
@Test
public void postClusterWithProduct() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(2);
String ips = "127.0.0.101,127.0.0.102,127.0.0.103";
params.add("ips", ips);
params.add("product", PRODUCT_CONFIG);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> getClusterResponseEntity = restTemplate.exchange(
RequestEntity.get("/{product}/serverlist", PRODUCT_CONFIG).build(), String.class);
Assert.assertNotNull(getClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue());
final String body = getClusterResponseEntity.getBody();
Assert.assertNotNull(body);
}
@Test
public void deleteClusterWithProduct() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
params.add("product", PRODUCT_CONFIG);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> deleteClusterResponseEntity = restTemplate.exchange(
RequestEntity.delete("/nacos/v1/as/nodes?product={product}&ips={ips}", PRODUCT_CONFIG, "127.0.0.104")
.header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO).build(), String.class);
Assert.assertNotNull(deleteClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue());
}
@Test
public void postClusterWithProductAndCluster() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
String ips = "127.0.0.100,127.0.0.200,127.0.0.31";
params.add("ips", ips);
params.add("product", PRODUCT_NAMING);
params.add("cluster", "cluster01");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> getClusterResponseEntity = restTemplate.exchange(
RequestEntity.get("/{product}/{cluster}", PRODUCT_NAMING, "cluster01").build(), String.class);
Assert.assertNotNull(getClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue());
final String body = getClusterResponseEntity.getBody();
Assert.assertNotNull(body);
}
@Test
public void deleteClusterWithProductAndCluster() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
params.add("product", PRODUCT_NAMING);
params.add("cluster", "cluster01");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> deleteClusterResponseEntity = restTemplate.exchange(
RequestEntity.delete("/nacos/v1/as/nodes?product={product}&cluster={cluster}&ips={ips}", PRODUCT_NAMING,
"cluster01", "127.0.0.104").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO).build(),
String.class);
Assert.assertNotNull(deleteClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue());
}
}

View File

@ -17,7 +17,7 @@
package com.alibaba.nacos.address.component; package com.alibaba.nacos.address.component;
import com.alibaba.nacos.address.constant.AddressServerConstants; import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -67,7 +67,7 @@ public class AddressServerGeneratorManagerTest {
@Test @Test
public void testGenerateResponseIps() { public void testGenerateResponseIps() {
final List<Instance> instanceList = new ArrayList<>(); final List<com.alibaba.nacos.api.naming.pojo.Instance> instanceList = new ArrayList<>();
Instance instance1 = new Instance(); Instance instance1 = new Instance();
instance1.setIp("192.168.3.1"); instance1.setIp("192.168.3.1");
instance1.setPort(8848); instance1.setPort(8848);

View File

@ -21,8 +21,12 @@ import com.alibaba.nacos.address.component.AddressServerManager;
import com.alibaba.nacos.address.constant.AddressServerConstants; import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.ClusterOperator;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.InstanceOperator;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -40,124 +44,94 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class AddressServerClusterControllerTest { public class AddressServerClusterControllerTest {
@Mock @Mock
private ServiceManager serviceManager; private InstanceOperator instanceOperator;
@Mock
private NamingMetadataManager metadataManager;
@Mock
private ClusterOperator clusterOperator;
private MockMvc mockMvc; private MockMvc mockMvc;
@Before @Before
public void before() { public void before() {
mockMvc = MockMvcBuilders.standaloneSetup(new AddressServerClusterController(serviceManager, new AddressServerManager(), mockMvc = MockMvcBuilders.standaloneSetup(
new AddressServerGeneratorManager())).build(); new AddressServerClusterController(instanceOperator, metadataManager, clusterOperator,
new AddressServerManager(), new AddressServerGeneratorManager())).build();
Service service = Service
.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceManager.getInstance().getSingleton(service);
}
@After
public void tearDown() {
Service service = Service
.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceManager.getInstance().removeSingleton(service);
} }
@Test @Test
public void testPostCluster() throws Exception { public void testPostCluster() throws Exception {
mockMvc.perform(post("/nacos/v1/as/nodes") mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("product", "default") .param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isOk());
.param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2"))
.andExpect(status().isOk());
} }
@Test @Test
public void testPostClusterWithErrorIps() throws Exception { public void testPostClusterWithErrorIps() throws Exception {
mockMvc.perform(post("/nacos/v1/as/nodes") mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("product", "default") .param("ips", "192.168.1")).andExpect(status().isBadRequest());
.param("cluster", "serverList")
.param("ips", "192.168.1"))
.andExpect(status().isBadRequest());
} }
@Test @Test
public void testPostClusterThrowException() throws Exception { public void testPostClusterThrowException() throws Exception {
Mockito.doThrow(new NacosException(500, "create service error")).when(serviceManager) Mockito.doThrow(new NacosException(500, "create service error")).when(clusterOperator)
.createServiceIfAbsent(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq( .updateClusterMetadata(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq(
Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"), Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"),
Mockito.eq(false), Mockito.any()); Mockito.eq("serverList"), Mockito.any());
mockMvc.perform(post("/nacos/v1/as/nodes") mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("product", "default") .param("ips", "192.168.1")).andExpect(status().isInternalServerError());
.param("cluster", "serverList")
.param("ips", "192.168.1"))
.andExpect(status().isInternalServerError());
} }
@Test @Test
public void testDeleteCluster() throws Exception { public void testDeleteCluster() throws Exception {
mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), .param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isOk());
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"));
mockMvc.perform(delete("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")
).andExpect(status().isOk());
} }
@Test @Test
public void testDeleteClusterCannotFindService() throws Exception { public void testDeleteClusterCannotFindService() throws Exception {
tearDown();
mockMvc.perform(delete("/nacos/v1/as/nodes") mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("product", "default") .param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isNotFound());
.param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")
).andExpect(status().isNotFound());
} }
@Test @Test
public void testDeleteClusterEmptyIps() throws Exception { public void testDeleteClusterEmptyIps() throws Exception {
mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), .param("ips", "")).andExpect(status().isBadRequest());
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"));
mockMvc.perform(delete("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "")
).andExpect(status().isBadRequest());
} }
@Test @Test
public void testDeleteClusterErrorIps() throws Exception { public void testDeleteClusterErrorIps() throws Exception {
mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), .param("ips", "192.168.1")).andExpect(status().isBadRequest());
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"));
mockMvc.perform(delete("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.1")
).andExpect(status().isBadRequest());
} }
@Test @Test
public void testDeleteClusterThrowException() throws Exception { public void testDeleteClusterThrowException() throws Exception {
Mockito.doThrow(new NacosException(500, "remove service error")).when(instanceOperator)
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), .removeInstance(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq(
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"))) Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"),
.thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"));
Mockito.doThrow(new NacosException(500, "remove service error"))
.when(serviceManager)
.removeInstance(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"),
Mockito.eq(false),
Mockito.any()); Mockito.any());
mockMvc.perform(delete("/nacos/v1/as/nodes") mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("product", "default") .param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isInternalServerError());
.param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")
).andExpect(status().isInternalServerError());
} }
} }

View File

@ -17,25 +17,29 @@
package com.alibaba.nacos.address.controller; package com.alibaba.nacos.address.controller;
import com.alibaba.nacos.address.component.AddressServerGeneratorManager; import com.alibaba.nacos.address.component.AddressServerGeneratorManager;
import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Optional;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -43,68 +47,56 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class ServerListControllerTest { public class ServerListControllerTest {
@Mock @Mock
private ServiceManager serviceManager; private NamingMetadataManager metadataManager;
@Mock
private ServiceStorage serviceStorage;
private Service service;
private MockMvc mockMvc; private MockMvc mockMvc;
@Before @Before
public void before() { public void before() {
this.mockMvc = MockMvcBuilders this.mockMvc = MockMvcBuilders.standaloneSetup(
.standaloneSetup(new ServerListController(serviceManager, new AddressServerGeneratorManager())) new ServerListController(new AddressServerGeneratorManager(), metadataManager, serviceStorage)).build();
.build(); service = Service
.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceManager.getInstance().getSingleton(service);
}
@After
public void tearDown() {
ServiceManager.getInstance().removeSingleton(service);
} }
@Test @Test
public void testGetCluster() throws Exception { public void testGetCluster() throws Exception {
final Service service = new Service( final Service service = Service
Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"); .newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceMetadata serviceMetadata = new ServiceMetadata();
Cluster cluster = new Cluster(); serviceMetadata.getClusters().put("serverList", new ClusterMetadata());
cluster.setName("serverList"); when(metadataManager.getServiceMetadata(service)).thenReturn(Optional.of(serviceMetadata));
cluster.setService(service);
final HashMap<String, Cluster> clusterMap = new HashMap<>(1);
clusterMap.put("serverList", cluster);
service.setClusterMap(clusterMap);
List<Instance> list = new ArrayList<>(2); List<Instance> list = new ArrayList<>(2);
list.add(new Instance("192.168.3.1", 8848)); list.add(new Instance());
list.add(new Instance("192.168.3.2", 8848)); list.add(new Instance());
cluster.updateIps(list, false); ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setHosts(list);
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), when(serviceStorage.getData(service)).thenReturn(serviceInfo);
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"))) mockMvc.perform(get("/nacos/serverList")).andExpect(status().isOk());
.thenReturn(service);
mockMvc.perform(get("/nacos/serverList"))
.andExpect(status().isOk());
} }
@Test @Test
public void testGetClusterCannotFindService() throws Exception { public void testGetClusterCannotFindService() throws Exception {
tearDown();
mockMvc.perform(get("/default/serverList")) mockMvc.perform(get("/default/serverList")).andExpect(status().isNotFound());
.andExpect(status().isNotFound());
} }
@Test @Test
public void testGetClusterCannotFindCluster() throws Exception { public void testGetClusterCannotFindCluster() throws Exception {
mockMvc.perform(get("/nacos/serverList")).andExpect(status().isNotFound());
final Service service = new Service(
Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default");
final HashMap<String, Cluster> clusterMap = new HashMap<>(1);
service.setClusterMap(clusterMap);
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(service);
mockMvc.perform(get("/nacos/serverList"))
.andExpect(status().isNotFound());
} }
} }

View File

@ -28,7 +28,8 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<name>nacos-api ${project.version}</name> <name>nacos-api ${project.version}</name>
<url>http://nacos.io</url> <url>https://nacos.io</url>
<description>Nacos api pom.xml file</description>
<build> <build>
<plugins> <plugins>
<!-- reuse when you need to update grpc model --> <!-- reuse when you need to update grpc model -->
@ -50,22 +51,9 @@
</execution> </execution>
</executions> </executions>
</plugin>--> </plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
@ -105,11 +93,6 @@
<groupId>com.google.protobuf</groupId> <groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId> <artifactId>protobuf-java</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>protoc-gen-grpc-java</artifactId>
<type>pom</type>
</dependency>
<dependency> <dependency>
<groupId>javax.annotation</groupId> <groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId> <artifactId>javax.annotation-api</artifactId>

View File

@ -75,7 +75,7 @@ public class PropertyKeyConst {
public static final String NAMING_PUSH_EMPTY_PROTECTION = "namingPushEmptyProtection"; public static final String NAMING_PUSH_EMPTY_PROTECTION = "namingPushEmptyProtection";
public static final String PUSH_RECEIVER_UDP_PORT = "push.receiver.udp.port"; public static final String NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE = "namingAsyncQuerySubscribeService";
/** /**
* Get the key value of some variable value from the system property. * Get the key value of some variable value from the system property.

View File

@ -27,8 +27,6 @@ public interface SystemPropertyKeyConst {
String NAMING_SERVER_PORT = "nacos.naming.exposed.port"; String NAMING_SERVER_PORT = "nacos.naming.exposed.port";
String NAMING_WEB_CONTEXT = "nacos.naming.web.context";
/** /**
* In the cloud (Alibaba Cloud or other cloud vendors) environment, whether to enable namespace resolution in the * In the cloud (Alibaba Cloud or other cloud vendors) environment, whether to enable namespace resolution in the
* cloud environment. * cloud environment.

View File

@ -0,0 +1,36 @@
/*
* Copyright 1999-2022 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for Nacos API v2 Controller.
* @author dongyafei
* @date 2022/7/22
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosApi {
}

View File

@ -249,8 +249,12 @@ public class Constants {
*/ */
public static class Exception { public static class Exception {
public static final int SERIALIZE_ERROR_CODE = 100;
public static final int DESERIALIZE_ERROR_CODE = 101; public static final int DESERIALIZE_ERROR_CODE = 101;
public static final int SERIALIZE_ERROR_CODE = 100; public static final int FIND_DATASOURCE_ERROR_CODE = 102;
public static final int FIND_TABLE_ERROR_CODE = 103;
} }
} }

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.api.config; package com.alibaba.nacos.api.config;
import com.alibaba.nacos.api.config.filter.IConfigFilter;
import com.alibaba.nacos.api.config.listener.Listener; import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
@ -144,6 +145,15 @@ public interface ConfigService {
*/ */
String getServerStatus(); String getServerStatus();
/**
* add config filter.
* It is recommended to use {@link com.alibaba.nacos.api.config.filter.AbstractConfigFilter} to expand the filter.
*
* @param configFilter filter
* @since 2.3.0
*/
void addConfigFilter(IConfigFilter configFilter);
/** /**
* Shutdown the resource service. * Shutdown the resource service.
* *

View File

@ -62,13 +62,6 @@ public @interface NacosConfigurationProperties {
*/ */
String dataId(); String dataId();
/**
* set config type is yaml this method is deprecated, we support you use {@link #type()} to set config type.
*
* @return default value <code>false</code>
*/
@Deprecated boolean yaml() default false;
/** /**
* config style. * config style.
* *

View File

@ -23,12 +23,4 @@ package com.alibaba.nacos.api.config.filter;
*/ */
public abstract class AbstractConfigFilter implements IConfigFilter { public abstract class AbstractConfigFilter implements IConfigFilter {
/**
* init.
*
* @param filterConfig Filter Config
*/
@Override
public void init(IFilterConfig filterConfig) {
}
} }

View File

@ -30,14 +30,6 @@ import java.util.Properties;
*/ */
public interface IConfigFilter { public interface IConfigFilter {
/**
* Init.
*
* @param filterConfig Filter Config
*/
@Deprecated
void init(IFilterConfig filterConfig);
/** /**
* Init. * Init.
* *

View File

@ -38,6 +38,8 @@ public class ConfigChangeClusterSyncRequest extends AbstractConfigRequest {
boolean isBeta; boolean isBeta;
boolean isBatch;
public boolean isBeta() { public boolean isBeta() {
return isBeta; return isBeta;
} }
@ -46,6 +48,14 @@ public class ConfigChangeClusterSyncRequest extends AbstractConfigRequest {
isBeta = beta; isBeta = beta;
} }
public boolean isBatch() {
return isBatch;
}
public void setBatch(boolean batch) {
isBatch = batch;
}
/** /**
* Getter method for property <tt>dataId</tt>. * Getter method for property <tt>dataId</tt>.
* *

View File

@ -0,0 +1,74 @@
/*
* Copyright 1999-2022 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.api;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.utils.StringUtils;
/** Exception for open API. <BR/>
* errCode -> HTTP status code inherited from {@link NacosException} <BR/>
* errMsg -> detail error message inherited from {@link NacosException} <BR/>
* detailErrCode -> error code for api v2.0 <BR/>
* errAbstract -> abstract error message for api v2.0
* @author dongyafei
* @date 2022/7/22
*/
public class NacosApiException extends NacosException {
/**
* serialVersionUID.
*/
private static final long serialVersionUID = 2245627968556056573L;
/**
* error code for api v2.0.
*/
private int detailErrCode;
/**
* abstract error description for api v2.0.
*/
private String errAbstract;
public NacosApiException() {
}
public NacosApiException(int statusCode, ErrorCode errorCode, Throwable throwable, String message) {
super(statusCode, message, throwable);
this.detailErrCode = errorCode.getCode();
this.errAbstract = errorCode.getMsg();
}
public NacosApiException(int statusCode, ErrorCode errorCode, String message) {
super(statusCode, message);
this.detailErrCode = errorCode.getCode();
this.errAbstract = errorCode.getMsg();
}
public int getDetailErrCode() {
return detailErrCode;
}
public String getErrAbstract() {
if (!StringUtils.isBlank(this.errAbstract)) {
return this.errAbstract;
}
return Constants.NULL;
}
}

View File

@ -27,7 +27,7 @@ public class NacosRuntimeException extends RuntimeException {
public static final String ERROR_MESSAGE_FORMAT = "errCode: %d, errMsg: %s "; public static final String ERROR_MESSAGE_FORMAT = "errCode: %d, errMsg: %s ";
private int errCode; private final int errCode;
public NacosRuntimeException(int errCode) { public NacosRuntimeException(int errCode) {
super(); super();
@ -52,8 +52,4 @@ public class NacosRuntimeException extends RuntimeException {
public int getErrCode() { public int getErrCode() {
return errCode; return errCode;
} }
public void setErrCode(int errCode) {
this.errCode = errCode;
}
} }

View File

@ -0,0 +1,204 @@
/*
* Copyright 1999-2022 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.model.v2;
/**
* Response Error Code.
*
* @author dongyafei
* @date 2022/7/22
*/
public enum ErrorCode {
/**
* success.
*/
SUCCESS(0, "success"),
/**
* parameter missing.
*/
PARAMETER_MISSING(10000, "parameter missing"),
/**
* access denied.
*/
ACCESS_DENIED(10001, "access denied"),
/**
* data access error.
*/
DATA_ACCESS_ERROR(10002, "data access error"),
/**
* 'tenant' parameter error.
*/
TENANT_PARAM_ERROR(20001, "'tenant' parameter error"),
/**
* parameter validate error.
*/
PARAMETER_VALIDATE_ERROR(20002, "parameter validate error"),
/**
* MediaType Error.
*/
MEDIA_TYPE_ERROR(20003, "MediaType Error"),
/**
* resource not found.
*/
RESOURCE_NOT_FOUND(20004, "resource not found"),
/**
* resource conflict.
*/
RESOURCE_CONFLICT(20005, "resource conflict"),
/**
* config listener is null.
*/
CONFIG_LISTENER_IS_NULL(20006, "config listener is null"),
/**
* config listener error.
*/
CONFIG_LISTENER_ERROR(20007, "config listener error"),
/**
* invalid dataId.
*/
INVALID_DATA_ID(20008, "invalid dataId"),
/**
* parameter mismatch.
*/
PARAMETER_MISMATCH(20009, "parameter mismatch"),
/**
* service name error.
*/
SERVICE_NAME_ERROR(21000, "service name error"),
/**
* weight error.
*/
WEIGHT_ERROR(21001, "weight error"),
/**
* instance metadata error.
*/
INSTANCE_METADATA_ERROR(21002, "instance metadata error"),
/**
* instance not found.
*/
INSTANCE_NOT_FOUND(21003, "instance not found"),
/**
* instance error.
*/
INSTANCE_ERROR(21004, "instance error"),
/**
* service metadata error.
*/
SERVICE_METADATA_ERROR(21005, "service metadata error"),
/**
* selector error.
*/
SELECTOR_ERROR(21006, "selector error"),
/**
* service already exist.
*/
SERVICE_ALREADY_EXIST(21007, "service already exist"),
/**
* service not exist.
*/
SERVICE_NOT_EXIST(21008, "service not exist"),
/**
* service delete failure.
*/
SERVICE_DELETE_FAILURE(21009, "service delete failure"),
/**
* healthy param miss.
*/
HEALTHY_PARAM_MISS(21010, "healthy param miss"),
/**
* health check still running.
*/
HEALTH_CHECK_STILL_RUNNING(21011, "health check still running"),
/**
* illegal namespace.
*/
ILLEGAL_NAMESPACE(22000, "illegal namespace"),
/**
* namespace not exist.
*/
NAMESPACE_NOT_EXIST(22001, "namespace not exist"),
/**
* namespace already exist.
*/
NAMESPACE_ALREADY_EXIST(22002, "namespace already exist"),
/**
* illegal state.
*/
ILLEGAL_STATE(23000, "illegal state"),
/**
* node info error.
*/
NODE_INFO_ERROR(23001, "node info error"),
/**
* node down failure.
*/
NODE_DOWN_FAILURE(23001, "node down failure"),
/**
* server error.
*/
SERVER_ERROR(30000, "server error");
private final Integer code;
private final String msg;
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
ErrorCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}

View File

@ -0,0 +1,115 @@
/*
* Copyright 1999-2022 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.model.v2;
import java.io.Serializable;
/**
* Response Result.
*
* @author dongyafei
* @date 2022/7/12
*/
public class Result<T> implements Serializable {
private static final long serialVersionUID = 6258345442767540526L;
private final Integer code;
private final String message;
private final T data;
public Result(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public Result() {
this(null);
}
public Result(T data) {
this(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg(), data);
}
public Result(Integer code, String message) {
this(code, message, null);
}
/**
* Success return with nothing.
* @param <T> data type
* @return Result
*/
public static <T> Result<T> success() {
return new Result<>();
}
/**
* Success return with data.
* @param <T> data type
* @return Result
*/
public static <T> Result<T> success(T data) {
return new Result<>(data);
}
/**
* Failed return with message and detail error information.
* @return Result
*/
public static Result<String> failure(String message) {
return new Result<>(ErrorCode.SERVER_ERROR.getCode(), message);
}
/**
* Failed return with errorCode and message.
* @param <T> data type
* @return Result
*/
public static <T> Result<T> failure(ErrorCode errorCode) {
return new Result<>(errorCode.getCode(), errorCode.getMsg());
}
/**
* Failed return with errorCode, message and data.
* @param <T> data type
* @return Result
*/
public static <T> Result<T> failure(ErrorCode errorCode, T data) {
return new Result<>(errorCode.getCode(), errorCode.getMsg(), data);
}
@Override
public String toString() {
return "Result{" + "errorCode=" + code + ", message='" + message + '\'' + ", data=" + data + '}';
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
public T getData() {
return data;
}
}

View File

@ -107,6 +107,17 @@ public interface NamingService {
*/ */
void batchRegisterInstance(String serviceName, String groupName, List<Instance> instances) throws NacosException; void batchRegisterInstance(String serviceName, String groupName, List<Instance> instances) throws NacosException;
/**
* batch deRegister instance to service with specified instance properties.
*
* @param serviceName name of service
* @param groupName group of service
* @param instances instances to deRegister
* @throws NacosException nacos exception
* @since 2.2.0
*/
void batchDeregisterInstance(String serviceName, String groupName, List<Instance> instances) throws NacosException;
/** /**
* deregister instance from a service. * deregister instance from a service.
* *

View File

@ -25,6 +25,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* Instance. * Instance.
@ -209,7 +210,7 @@ public class Instance implements Serializable {
} }
private static boolean strEquals(final String str1, final String str2) { private static boolean strEquals(final String str1, final String str2) {
return str1 == null ? str2 == null : str1.equals(str2); return Objects.equals(str1, str2);
} }
public long getInstanceHeartBeatInterval() { public long getInstanceHeartBeatInterval() {

View File

@ -24,7 +24,6 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
/** /**
@ -36,15 +35,22 @@ import java.util.List;
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.NON_NULL)
public class ServiceInfo { public class ServiceInfo {
/**
* file name pattern: groupName@@name@clusters.
*/
private static final int GROUP_POSITION = 0;
private static final int SERVICE_POSITION = 1;
private static final int CLUSTER_POSITION = 2;
private static final int FILE_NAME_PARTS = 3;
@JsonIgnore @JsonIgnore
private String jsonFromServer = EMPTY; private String jsonFromServer = EMPTY;
private static final String EMPTY = ""; private static final String EMPTY = "";
private static final String ALL_IPS = "000--00-ALL_IPS--00--000";
public static final String SPLITER = "@@";
private static final String DEFAULT_CHARSET = "UTF-8"; private static final String DEFAULT_CHARSET = "UTF-8";
private String name; private String name;
@ -80,20 +86,15 @@ public class ServiceInfo {
* There is only one form of the key:groupName@@name@clusters. This constructor used by DiskCache.read(String) and * There is only one form of the key:groupName@@name@clusters. This constructor used by DiskCache.read(String) and
* FailoverReactor.FailoverFileReader,you should know that 'groupName' must not be null,and 'clusters' can be null. * FailoverReactor.FailoverFileReader,you should know that 'groupName' must not be null,and 'clusters' can be null.
*/ */
public ServiceInfo(String key) { public ServiceInfo(final String key) {
int maxIndex = 2;
int clusterIndex = 2;
int serviceNameIndex = 1;
int groupIndex = 0;
String[] keys = key.split(Constants.SERVICE_INFO_SPLITER); String[] keys = key.split(Constants.SERVICE_INFO_SPLITER);
if (keys.length >= maxIndex + 1) { if (keys.length >= FILE_NAME_PARTS) {
this.groupName = keys[groupIndex]; this.groupName = keys[GROUP_POSITION];
this.name = keys[serviceNameIndex]; this.name = keys[SERVICE_POSITION];
this.clusters = keys[clusterIndex]; this.clusters = keys[CLUSTER_POSITION];
} else if (keys.length == maxIndex) { } else if (keys.length == CLUSTER_POSITION) {
this.groupName = keys[groupIndex]; this.groupName = keys[GROUP_POSITION];
this.name = keys[serviceNameIndex]; this.name = keys[SERVICE_POSITION];
} else { } else {
//defensive programming //defensive programming
throw new IllegalArgumentException("Can't parse out 'groupName',but it must not be null!"); throw new IllegalArgumentException("Can't parse out 'groupName',but it must not be null!");
@ -231,8 +232,7 @@ public class ServiceInfo {
String serviceName = getGroupedServiceName(); String serviceName = getGroupedServiceName();
try { try {
serviceName = URLEncoder.encode(serviceName, DEFAULT_CHARSET); serviceName = URLEncoder.encode(serviceName, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException ignored) {
//do nothing
} }
return getKey(serviceName, clusters); return getKey(serviceName, clusters);
} }
@ -251,19 +251,8 @@ public class ServiceInfo {
* @param key key of service info * @param key key of service info
* @return new service info * @return new service info
*/ */
public static ServiceInfo fromKey(String key) { public static ServiceInfo fromKey(final String key) {
ServiceInfo serviceInfo = new ServiceInfo(); return new ServiceInfo(key);
int maxSegCount = 3;
String[] segs = key.split(Constants.SERVICE_INFO_SPLITER);
if (segs.length == maxSegCount - 1) {
serviceInfo.setGroupName(segs[0]);
serviceInfo.setName(segs[1]);
} else if (segs.length == maxSegCount) {
serviceInfo.setGroupName(segs[0]);
serviceInfo.setName(segs[1]);
serviceInfo.setClusters(segs[2]);
}
return serviceInfo;
} }
@Override @Override
@ -283,14 +272,6 @@ public class ServiceInfo {
return str == null || str.length() == 0; return str == null || str.length() == 0;
} }
private static boolean isEmpty(Collection coll) {
return (coll == null || coll.isEmpty());
}
private static boolean strEquals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
public boolean isReachProtectionThreshold() { public boolean isReachProtectionThreshold() {
return reachProtectionThreshold; return reachProtectionThreshold;
} }

View File

@ -21,10 +21,10 @@ import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.api.utils.StringUtils; import com.alibaba.nacos.api.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Objects;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* Implementation of health checker for HTTP. * Implementation of health checker for HTTP.
@ -100,10 +100,6 @@ public class Http extends AbstractHealthChecker {
final Http other = (Http) obj; final Http other = (Http) obj;
if (!StringUtils.equals(type, other.getType())) {
return false;
}
if (!StringUtils.equals(path, other.getPath())) { if (!StringUtils.equals(path, other.getPath())) {
return false; return false;
} }

View File

@ -16,25 +16,18 @@
package com.alibaba.nacos.api.naming.remote.response; package com.alibaba.nacos.api.naming.remote.response;
import com.alibaba.nacos.api.remote.response.Response;
/** /**
* batch instance response. * batch instance response.
* *
* @author <a href="mailto:chenhao26@xiaomi.com">chenhao26</a> * @author <a href="mailto:chenhao26@xiaomi.com">chenhao26</a>
*/ */
public class BatchInstanceResponse extends Response { public class BatchInstanceResponse extends InstanceResponse {
private String type;
public BatchInstanceResponse() { public BatchInstanceResponse() {
super();
} }
public BatchInstanceResponse(String type) { public BatchInstanceResponse(String type) {
this.type = type; super(type);
}
public void setType(String type) {
this.type = type;
} }
} }

View File

@ -38,4 +38,7 @@ public class InstanceResponse extends Response {
this.type = type; this.type = type;
} }
public String getType() {
return type;
}
} }

View File

@ -18,6 +18,8 @@ package com.alibaba.nacos.api.naming.utils;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.api.NacosApiException;
import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.utils.StringUtils; import com.alibaba.nacos.api.utils.StringUtils;
@ -138,11 +140,11 @@ public class NamingUtils {
public static void checkInstanceIsLegal(Instance instance) throws NacosException { public static void checkInstanceIsLegal(Instance instance) throws NacosException {
if (instance.getInstanceHeartBeatTimeOut() < instance.getInstanceHeartBeatInterval() if (instance.getInstanceHeartBeatTimeOut() < instance.getInstanceHeartBeatInterval()
|| instance.getIpDeleteTimeout() < instance.getInstanceHeartBeatInterval()) { || instance.getIpDeleteTimeout() < instance.getInstanceHeartBeatInterval()) {
throw new NacosException(NacosException.INVALID_PARAM, throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR,
"Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'."); "Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'.");
} }
if (!StringUtils.isEmpty(instance.getClusterName()) && !CLUSTER_NAME_PATTERN.matcher(instance.getClusterName()).matches()) { if (!StringUtils.isEmpty(instance.getClusterName()) && !CLUSTER_NAME_PATTERN.matcher(instance.getClusterName()).matches()) {
throw new NacosException(NacosException.INVALID_PARAM, throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR,
String.format("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: %s)", String.format("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: %s)",
instance.getClusterName())); instance.getClusterName()));
} }
@ -155,7 +157,7 @@ public class NamingUtils {
*/ */
public static void checkInstanceIsEphemeral(Instance instance) throws NacosException { public static void checkInstanceIsEphemeral(Instance instance) throws NacosException {
if (!instance.isEphemeral()) { if (!instance.isEphemeral()) {
throw new NacosException(NacosException.INVALID_PARAM, throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR,
String.format("Batch registration does not allow persistent instance registration , Instance%s", instance)); String.format("Batch registration does not allow persistent instance registration , Instance%s", instance));
} }
} }

View File

@ -68,9 +68,6 @@ public class DefaultRequestFuture implements RequestFuture {
return timeStamp; return timeStamp;
} }
public DefaultRequestFuture() {
}
public DefaultRequestFuture(String connectionId, String requestId) { public DefaultRequestFuture(String connectionId, String requestId) {
this(connectionId, requestId, null, null); this(connectionId, requestId, null, null);
} }
@ -167,7 +164,9 @@ public class DefaultRequestFuture implements RequestFuture {
if (timeoutInnerTrigger != null) { if (timeoutInnerTrigger != null) {
timeoutInnerTrigger.triggerOnTimeout(); timeoutInnerTrigger.triggerOnTimeout();
} }
throw new TimeoutException("request timeout after " + timeout + " milliseconds, requestId=" + requestId); throw new TimeoutException(
"request timeout after " + timeout + " milliseconds, requestId=" + requestId + ", connectionId="
+ connectionId);
} }
} }
@ -191,7 +190,8 @@ public class DefaultRequestFuture implements RequestFuture {
@Override @Override
public void run() { public void run() {
setFailResult(new TimeoutException( setFailResult(new TimeoutException(
"Timeout After " + requestCallBack.getTimeout() + " milliseconds,requestId =" + requestId)); "Timeout After " + requestCallBack.getTimeout() + " milliseconds, requestId=" + requestId
+ ", connectionId=" + connectionId));
if (timeoutInnerTrigger != null) { if (timeoutInnerTrigger != null) {
timeoutInnerTrigger.triggerOnTimeout(); timeoutInnerTrigger.triggerOnTimeout();
} }
@ -203,7 +203,7 @@ public class DefaultRequestFuture implements RequestFuture {
/** /**
* triggered on timeout . * triggered on timeout .
*/ */
public void triggerOnTimeout(); void triggerOnTimeout();
} }
@ -215,14 +215,4 @@ public class DefaultRequestFuture implements RequestFuture {
public String getConnectionId() { public String getConnectionId() {
return connectionId; return connectionId;
} }
/**
* Setter method for property <tt>timeoutFuture</tt>.
*
* @param timeoutFuture value to be assigned to property timeoutFuture
*/
public void setTimeoutFuture(ScheduledFuture timeoutFuture) {
this.timeoutFuture = timeoutFuture;
}
} }

View File

@ -17,6 +17,8 @@
package com.alibaba.nacos.api.remote; package com.alibaba.nacos.api.remote;
import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
/** /**
* rpc scheduler executor . * rpc scheduler executor .
@ -33,7 +35,16 @@ public class RpcScheduledExecutor extends ScheduledThreadPoolExecutor {
"com.alibaba.nacos.remote.ServerCommonScheduler"); "com.alibaba.nacos.remote.ServerCommonScheduler");
public RpcScheduledExecutor(int corePoolSize, final String threadName) { public RpcScheduledExecutor(int corePoolSize, final String threadName) {
super(corePoolSize, r -> new Thread(r, threadName)); super(corePoolSize, new ThreadFactory() {
private AtomicLong index = new AtomicLong();
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, threadName + "." + index.getAndIncrement());
thread.setDaemon(true);
return thread;
}
});
} }
} }

View File

@ -34,6 +34,11 @@ public class ServerRemoteAbility implements Serializable {
*/ */
private boolean supportRemoteConnection; private boolean supportRemoteConnection;
/**
* if support grpc report.
*/
private boolean grpcReportEnabled = true;
public boolean isSupportRemoteConnection() { public boolean isSupportRemoteConnection() {
return this.supportRemoteConnection; return this.supportRemoteConnection;
} }
@ -42,6 +47,14 @@ public class ServerRemoteAbility implements Serializable {
this.supportRemoteConnection = supportRemoteConnection; this.supportRemoteConnection = supportRemoteConnection;
} }
public boolean isGrpcReportEnabled() {
return grpcReportEnabled;
}
public void setGrpcReportEnabled(boolean grpcReportEnabled) {
this.grpcReportEnabled = grpcReportEnabled;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
@ -51,11 +64,11 @@ public class ServerRemoteAbility implements Serializable {
return false; return false;
} }
ServerRemoteAbility that = (ServerRemoteAbility) o; ServerRemoteAbility that = (ServerRemoteAbility) o;
return supportRemoteConnection == that.supportRemoteConnection; return supportRemoteConnection == that.supportRemoteConnection && grpcReportEnabled == that.grpcReportEnabled;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(supportRemoteConnection); return Objects.hash(supportRemoteConnection, grpcReportEnabled);
} }
} }

View File

@ -52,15 +52,6 @@ public enum ResponseCode {
return code; return code;
} }
/**
* Setter method for property <tt>code</tt>.
*
* @param code value to be assigned to property code
*/
public void setCode(int code) {
this.code = code;
}
/** /**
* Getter method for property <tt>desc</tt>. * Getter method for property <tt>desc</tt>.
* *
@ -69,13 +60,4 @@ public enum ResponseCode {
public String getDesc() { public String getDesc() {
return desc; return desc;
} }
/**
* Setter method for property <tt>desc</tt>.
*
* @param desc value to be assigned to property desc
*/
public void setDesc(String desc) {
this.desc = desc;
}
} }

View File

@ -34,6 +34,8 @@ import static com.alibaba.nacos.api.common.Constants.Naming.CMDB_CONTEXT_TYPE;
*/ */
public abstract class AbstractCmdbSelector<T extends Instance> implements Selector<List<T>, CmdbContext<T>, String> { public abstract class AbstractCmdbSelector<T extends Instance> implements Selector<List<T>, CmdbContext<T>, String> {
private static final long serialVersionUID = 56587385358330901L;
/** /**
* the labels expression. * the labels expression.
*/ */

View File

@ -16,7 +16,6 @@
package com.alibaba.nacos.api.utils; package com.alibaba.nacos.api.utils;
import java.io.IOException;
import java.net.Inet4Address; import java.net.Inet4Address;
import java.net.Inet6Address; import java.net.Inet6Address;
import java.net.InetAddress; import java.net.InetAddress;
@ -31,9 +30,6 @@ import java.util.Enumeration;
*/ */
public class NetUtils { public class NetUtils {
@Deprecated
private static final String CLIENT_NAMING_LOCAL_IP_PROPERTY = "com.alibaba.nacos.client.naming.local.ip";
private static final String CLIENT_LOCAL_IP_PROPERTY = "com.alibaba.nacos.client.local.ip"; private static final String CLIENT_LOCAL_IP_PROPERTY = "com.alibaba.nacos.client.local.ip";
private static final String CLIENT_LOCAL_PREFER_HOSTNAME_PROPERTY = "com.alibaba.nacos.client.local.preferHostname"; private static final String CLIENT_LOCAL_PREFER_HOSTNAME_PROPERTY = "com.alibaba.nacos.client.local.preferHostname";
@ -53,15 +49,11 @@ public class NetUtils {
if (!StringUtils.isEmpty(localIp)) { if (!StringUtils.isEmpty(localIp)) {
return localIp; return localIp;
} }
if (System.getProperties().containsKey(CLIENT_LOCAL_IP_PROPERTY)) { if (System.getProperties().containsKey(CLIENT_LOCAL_IP_PROPERTY)) {
return localIp = System.getProperty(CLIENT_LOCAL_IP_PROPERTY, getAddress()); return localIp = System.getProperty(CLIENT_LOCAL_IP_PROPERTY, getAddress());
} }
localIp = getAddress();
String ip = System.getProperty(CLIENT_NAMING_LOCAL_IP_PROPERTY, getAddress()); return localIp;
return localIp = ip;
} }
private static String getAddress() { private static String getAddress() {
@ -91,9 +83,8 @@ public class NetUtils {
for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements(); ) { for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements(); ) {
InetAddress address = addrs.nextElement(); InetAddress address = addrs.nextElement();
boolean isLegalIpVersion = boolean isLegalIpVersion = Boolean.parseBoolean(System.getProperty(LEGAL_LOCAL_IP_PROPERTY))
Boolean.parseBoolean(System.getProperty(LEGAL_LOCAL_IP_PROPERTY)) ? address instanceof Inet6Address : address instanceof Inet4Address;
? address instanceof Inet6Address : address instanceof Inet4Address;
if (isLegalIpVersion && !address.isLoopbackAddress()) { if (isLegalIpVersion && !address.isLoopbackAddress()) {
result = address; result = address;
} }
@ -101,8 +92,7 @@ public class NetUtils {
} }
} }
} catch (IOException ex) { } catch (Exception ignore) {
//ignore
} }
if (result != null) { if (result != null) {
@ -111,8 +101,7 @@ public class NetUtils {
try { try {
return InetAddress.getLocalHost(); return InetAddress.getLocalHost();
} catch (UnknownHostException e) { } catch (UnknownHostException ignore) {
//ignore
} }
return null; return null;

View File

@ -0,0 +1,57 @@
#
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
com.alibaba.nacos.api.remote.request.ClientDetectionRequest
com.alibaba.nacos.api.remote.request.ConnectionSetupRequest
com.alibaba.nacos.api.remote.request.ConnectResetRequest
com.alibaba.nacos.api.remote.request.HealthCheckRequest
com.alibaba.nacos.api.remote.request.PushAckRequest
com.alibaba.nacos.api.remote.request.ServerCheckRequest
com.alibaba.nacos.api.remote.request.ServerLoaderInfoRequest
com.alibaba.nacos.api.remote.request.ServerReloadRequest
com.alibaba.nacos.api.remote.response.ClientDetectionResponse
com.alibaba.nacos.api.remote.response.ConnectResetResponse
com.alibaba.nacos.api.remote.response.ErrorResponse
com.alibaba.nacos.api.remote.response.HealthCheckResponse
com.alibaba.nacos.api.remote.response.ServerCheckResponse
com.alibaba.nacos.api.remote.response.ServerLoaderInfoResponse
com.alibaba.nacos.api.remote.response.ServerReloadResponse
com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequest
com.alibaba.nacos.api.config.remote.request.ConfigBatchListenRequest
com.alibaba.nacos.api.config.remote.request.ConfigChangeNotifyRequest
com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest
com.alibaba.nacos.api.config.remote.request.ConfigQueryRequest
com.alibaba.nacos.api.config.remote.request.ConfigRemoveRequest
com.alibaba.nacos.api.config.remote.response.ClientConfigMetricResponse
com.alibaba.nacos.api.config.remote.response.ConfigChangeBatchListenResponse
com.alibaba.nacos.api.config.remote.response.ConfigChangeNotifyResponse
com.alibaba.nacos.api.config.remote.response.ConfigPublishResponse
com.alibaba.nacos.api.config.remote.response.ConfigQueryResponse
com.alibaba.nacos.api.config.remote.response.ConfigRemoveResponse
com.alibaba.nacos.api.config.remote.request.cluster.ConfigChangeClusterSyncRequest
com.alibaba.nacos.api.config.remote.response.cluster.ConfigChangeClusterSyncResponse
com.alibaba.nacos.api.naming.remote.request.BatchInstanceRequest
com.alibaba.nacos.api.naming.remote.request.InstanceRequest
com.alibaba.nacos.api.naming.remote.request.NotifySubscriberRequest
com.alibaba.nacos.api.naming.remote.request.ServiceListRequest
com.alibaba.nacos.api.naming.remote.request.ServiceQueryRequest
com.alibaba.nacos.api.naming.remote.request.SubscribeServiceRequest
com.alibaba.nacos.api.naming.remote.response.BatchInstanceResponse
com.alibaba.nacos.api.naming.remote.response.InstanceResponse
com.alibaba.nacos.api.naming.remote.response.NotifySubscriberResponse
com.alibaba.nacos.api.naming.remote.response.QueryServiceResponse
com.alibaba.nacos.api.naming.remote.response.ServiceListResponse
com.alibaba.nacos.api.naming.remote.response.SubscribeServiceResponse

View File

@ -0,0 +1,59 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.ability;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ClientAbilitiesTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
ClientAbilities abilities = new ClientAbilities();
String json = mapper.writeValueAsString(abilities);
assertTrue(json.contains("\"remoteAbility\":{"));
assertTrue(json.contains("\"configAbility\":{"));
assertTrue(json.contains("\"namingAbility\":{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"remoteAbility\":{\"supportRemoteConnection\":false},"
+ "\"configAbility\":{\"supportRemoteMetrics\":false},\"namingAbility\":{\"supportDeltaPush\":false,"
+ "\"supportRemoteMetric\":false}}";
ClientAbilities abilities = mapper.readValue(json, ClientAbilities.class);
assertNotNull(abilities.getRemoteAbility());
assertNotNull(abilities.getNamingAbility());
assertNotNull(abilities.getConfigAbility());
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.ability;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ServerAbilitiesTest {
private static ObjectMapper mapper;
private ServerAbilities serverAbilities;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Before
public void setUp() throws Exception {
serverAbilities = new ServerAbilities();
}
@Test
public void testSerialize() throws JsonProcessingException {
serverAbilities = new ServerAbilities();
String json = mapper.writeValueAsString(serverAbilities);
assertTrue(json.contains("\"remoteAbility\":{"));
assertTrue(json.contains("\"configAbility\":{"));
assertTrue(json.contains("\"namingAbility\":{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"remoteAbility\":{\"supportRemoteConnection\":false},"
+ "\"configAbility\":{\"supportRemoteMetrics\":false},\"namingAbility\":{\"supportDeltaPush\":false,"
+ "\"supportRemoteMetric\":false}}";
ServerAbilities abilities = mapper.readValue(json, ServerAbilities.class);
assertNotNull(abilities.getRemoteAbility());
assertNotNull(abilities.getNamingAbility());
assertNotNull(abilities.getConfigAbility());
}
@Test
public void testEqualsAndHashCode() {
assertEquals(serverAbilities, serverAbilities);
assertEquals(serverAbilities.hashCode(), serverAbilities.hashCode());
assertNotEquals(serverAbilities, null);
assertNotEquals(serverAbilities, new ClientAbilities());
ServerAbilities test = new ServerAbilities();
assertEquals(serverAbilities, test);
assertEquals(serverAbilities.hashCode(), test.hashCode());
test.setRemoteAbility(null);
assertNotEquals(serverAbilities, test);
assertNotEquals(serverAbilities.hashCode(), test.hashCode());
}
}

View File

@ -0,0 +1,60 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.cmdb.pojo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EntityEventTest {
ObjectMapper mapper = new ObjectMapper();
@Before
public void setUp() throws Exception {
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialization() throws JsonProcessingException {
EntityEvent entity = new EntityEvent();
entity.setEntityName("test-entity");
entity.setEntityType("CMDB");
entity.setType(EntityEventType.ENTITY_ADD_OR_UPDATE);
String actual = mapper.writeValueAsString(entity);
System.out.println(actual);
assertTrue(actual.contains("\"entityName\":\"test-entity\""));
assertTrue(actual.contains("\"entityType\":\"CMDB\""));
assertTrue(actual.contains("\"type\":\"ENTITY_ADD_OR_UPDATE\""));
}
@Test
public void testDeserialization() throws JsonProcessingException {
String json = "{\"type\":\"ENTITY_REMOVE\",\"entityName\":\"test-entity\",\"entityType\":\"CMDB\"}";
EntityEvent entity = mapper.readValue(json, EntityEvent.class);
assertEquals("test-entity", entity.getEntityName());
assertEquals("CMDB", entity.getEntityType());
assertEquals(EntityEventType.ENTITY_REMOVE, entity.getType());
}
}

View File

@ -0,0 +1,63 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.cmdb.pojo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EntityTest {
ObjectMapper mapper = new ObjectMapper();
@Before
public void setUp() throws Exception {
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialization() throws JsonProcessingException {
Entity entity = new Entity();
entity.setName("test-entity");
entity.setType(PreservedEntityTypes.ip.name());
entity.setLabels(Collections.singletonMap("test-label-key", "test-label-value"));
String actual = mapper.writeValueAsString(entity);
assertTrue(actual.contains("\"type\":\"ip\""));
assertTrue(actual.contains("\"name\":\"test-entity\""));
assertTrue(actual.contains("\"labels\":{\"test-label-key\":\"test-label-value\"}"));
}
@Test
public void testDeserialization() throws JsonProcessingException {
String json = "{\"type\":\"service\",\"name\":\"test-entity\",\"labels\":{\"test-label-key\":\"test-label-value\"}}";
Entity entity = mapper.readValue(json, Entity.class);
assertEquals("test-entity", entity.getName());
assertEquals(PreservedEntityTypes.service.name(), entity.getType());
assertEquals(1, entity.getLabels().size());
assertTrue(entity.getLabels().containsKey("test-label-key"));
assertEquals("test-label-value", entity.getLabels().get("test-label-key"));
}
}

View File

@ -0,0 +1,64 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.cmdb.pojo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class LabelTest {
ObjectMapper mapper = new ObjectMapper();
@Before
public void setUp() throws Exception {
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialization() throws JsonProcessingException {
Label label = new Label();
label.setName("test-label");
label.setDescription("CMDB description");
label.setValues(Collections.singletonMap("test-value", "test-value").keySet());
String actual = mapper.writeValueAsString(label);
System.out.println(actual);
assertTrue(actual.contains("\"name\":\"test-label\""));
assertTrue(actual.contains("\"description\":\"CMDB description\""));
assertTrue(actual.contains("\"values\":[\"test-value\"]"));
}
@Test
public void testDeserialization() throws JsonProcessingException {
String json = "{\"values\":[\"test-value\"],\"name\":\"test-label\",\"description\":\"CMDB description\"}";
Label label = mapper.readValue(json, Label.class);
assertEquals("test-label", label.getName());
assertEquals("CMDB description", label.getDescription());
assertEquals(1, label.getValues().size());
assertEquals("test-value", label.getValues().iterator().next());
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ConfigChangeEventTest {
@Test
public void testConstructor() {
Map<String, ConfigChangeItem> mockData = new HashMap<>();
mockData.put("test", new ConfigChangeItem("testKey", null, "testValue"));
ConfigChangeEvent event = new ConfigChangeEvent(mockData);
assertEquals(1, event.getChangeItems().size());
assertEquals("testKey", event.getChangeItem("test").getKey());
assertNull(event.getChangeItem("test").getOldValue());
assertEquals("testValue", event.getChangeItem("test").getNewValue());
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ConfigChangeItemTest {
@Test
public void testSetNewValue() {
ConfigChangeItem item = new ConfigChangeItem("testKey", null, "testValue");
item.setType(PropertyChangeType.ADDED);
assertEquals("testKey", item.getKey());
assertNull(item.getOldValue());
assertEquals("testValue", item.getNewValue());
assertEquals(PropertyChangeType.ADDED, item.getType());
item.setOldValue("testValue");
item.setNewValue("testValue2");
item.setType(PropertyChangeType.MODIFIED);
assertEquals("testKey", item.getKey());
assertEquals("testValue", item.getOldValue());
assertEquals("testValue2", item.getNewValue());
assertEquals(PropertyChangeType.MODIFIED, item.getType());
item.setKey("deletedKey");
item.setType(PropertyChangeType.DELETED);
assertEquals("deletedKey", item.getKey());
assertEquals(PropertyChangeType.DELETED, item.getType());
}
@Test
public void testToString() {
ConfigChangeItem item = new ConfigChangeItem("testKey", null, "testValue");
item.setType(PropertyChangeType.ADDED);
assertEquals("ConfigChangeItem{key='testKey', oldValue='null', newValue='testValue', type=ADDED}",
item.toString());
}
}

View File

@ -0,0 +1,44 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTypeTest {
@Test
public void isValidType() {
assertTrue(ConfigType.isValidType("xml"));
assertTrue(ConfigType.isValidType("properties"));
assertTrue(ConfigType.isValidType("json"));
assertTrue(ConfigType.isValidType("text"));
assertTrue(ConfigType.isValidType("html"));
assertTrue(ConfigType.isValidType("yaml"));
assertTrue(ConfigType.isValidType("unset"));
assertFalse(ConfigType.isValidType(""));
assertFalse(ConfigType.isValidType("yml"));
}
@Test
public void testGetDefaultType() {
assertEquals("text", ConfigType.getDefaultType().getType());
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.ability;
import com.alibaba.nacos.api.remote.ability.ClientRemoteAbility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ClientRemoteAbilityTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
ClientRemoteAbility abilities = new ClientRemoteAbility();
String json = mapper.writeValueAsString(abilities);
assertEquals("{\"supportRemoteConnection\":false}", json);
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"supportRemoteConnection\":true}";
ClientRemoteAbility abilities = mapper.readValue(json, ClientRemoteAbility.class);
assertTrue(abilities.isSupportRemoteConnection());
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.ability;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
public class ServerConfigAbilityTest {
@Test
public void testEquals() {
ServerConfigAbility ability = new ServerConfigAbility();
ability.setSupportRemoteMetrics(true);
assertEquals(ability, ability);
assertFalse(ability.equals(null));
assertFalse(ability.equals(new ClientConfigAbility()));
ServerConfigAbility newOne = new ServerConfigAbility();
assertNotEquals(ability, newOne);
newOne.setSupportRemoteMetrics(true);
assertEquals(ability, newOne);
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.ability;
import com.alibaba.nacos.api.ability.ClientAbilities;
import com.alibaba.nacos.api.remote.ability.ServerRemoteAbility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ServerRemoteAbilityTest {
private static ObjectMapper mapper;
private ServerRemoteAbility serverAbilities;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Before
public void setUp() throws Exception {
serverAbilities = new ServerRemoteAbility();
}
@Test
public void testSerialize() throws JsonProcessingException {
serverAbilities = new ServerRemoteAbility();
String json = mapper.writeValueAsString(serverAbilities);
assertEquals("{\"supportRemoteConnection\":false,\"grpcReportEnabled\":true}", json);
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"supportRemoteConnection\":true,\"grpcReportEnabled\":true}";
ServerRemoteAbility abilities = mapper.readValue(json, ServerRemoteAbility.class);
assertTrue(abilities.isSupportRemoteConnection());
assertTrue(abilities.isGrpcReportEnabled());
}
@Test
public void testEqualsAndHashCode() {
assertEquals(serverAbilities, serverAbilities);
assertEquals(serverAbilities.hashCode(), serverAbilities.hashCode());
assertNotEquals(serverAbilities, null);
assertNotEquals(serverAbilities, new ClientAbilities());
ServerRemoteAbility test = new ServerRemoteAbility();
assertEquals(serverAbilities, test);
assertEquals(serverAbilities.hashCode(), test.hashCode());
test.setSupportRemoteConnection(true);
assertNotEquals(serverAbilities, test);
assertNotEquals(serverAbilities.hashCode(), test.hashCode());
test.setSupportRemoteConnection(false);
test.setGrpcReportEnabled(false);
assertNotEquals(serverAbilities, test);
assertNotEquals(serverAbilities.hashCode(), test.hashCode());
}
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 1999-2018 Alibaba Group Holding Ltd. * Copyright 1999-2023 Alibaba Group Holding Ltd.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -14,20 +14,21 @@
* limitations under the License. * limitations under the License.
*/ */
package com.alibaba.nacos.naming.consistency.persistent.raft; package com.alibaba.nacos.api.config.listener;
/** import org.junit.Test;
* Leader election finished event.
*
* @deprecated will remove in 1.4.x
* @author pbting
* @date 2019-07-01 8:25 PM
*/
@Deprecated
public class LeaderElectFinishedEvent extends BaseRaftEvent {
public LeaderElectFinishedEvent(Object source, RaftPeer raftPeer, RaftPeer local) { import static org.junit.Assert.assertNull;
super(source, raftPeer, local);
public class AbstractListenerTest {
@Test
public void testGetExecutor() {
// Default listener executor is null.
assertNull(new AbstractListener() {
@Override
public void receiveConfigInfo(String configInfo) {
}
}.getExecutor());
} }
} }

View File

@ -0,0 +1,69 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.listener;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class AbstractSharedListenerTest {
private static final String CONFIG_CONTENT = "test";
private static Map<String, String> receivedMap;
@Before
public void setUp() {
receivedMap = new HashMap<>();
}
@Test
public void testFillContext() {
assertEquals(0, receivedMap.size());
MockShardListener listener = new MockShardListener();
listener.receiveConfigInfo(CONFIG_CONTENT);
assertEquals(2, receivedMap.size());
assertNull(receivedMap.get("group"));
assertNull(receivedMap.get("dataId"));
listener.fillContext("aaa", "ggg");
listener.receiveConfigInfo(CONFIG_CONTENT);
assertEquals(2, receivedMap.size());
assertEquals("ggg", receivedMap.get("group"));
assertEquals("aaa", receivedMap.get("dataId"));
}
@Test
public void getExecutor() {
// Default listener executor is null.
assertNull(new MockShardListener().getExecutor());
}
private static class MockShardListener extends AbstractSharedListener {
@Override
public void innerReceive(String dataId, String group, String configInfo) {
assertEquals(CONFIG_CONTENT, configInfo);
receivedMap.put("group", group);
receivedMap.put("dataId", dataId);
}
}
}

View File

@ -0,0 +1,74 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.request;
import com.alibaba.nacos.api.remote.request.Request;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public abstract class BasedConfigRequestTest {
protected static ObjectMapper mapper;
protected static final String DATA_ID = "test_data";
protected static final String GROUP = "group";
protected static final String TENANT = "test_tenant";
protected static final String MD5 = "test_MD5";
protected static final String TAG = "tag";
protected static final String[] KEY = new String[] {DATA_ID, GROUP, TENANT};
protected static final Map<String, String> HEADERS = new HashMap<>();
protected static final String HEADER_KEY = "header1";
protected static final String HEADER_VALUE = "test_header1";
protected static final String CONTENT = "content";
static {
HEADERS.put(HEADER_KEY, HEADER_VALUE);
}
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public abstract void testSerialize() throws JsonProcessingException;
public abstract void testDeserialize() throws JsonProcessingException;
protected String injectRequestUuId(Request request) {
String uuid = UUID.randomUUID().toString();
request.setRequestId(uuid);
return uuid;
}
}

View File

@ -0,0 +1,91 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.request;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import java.util.Objects;
import static com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequest.MetricsKey.CACHE_DATA;
import static com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequest.MetricsKey.SNAPSHOT_DATA;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ClientConfigMetricRequestTest extends BasedConfigRequestTest {
@Override
@Test
public void testSerialize() throws JsonProcessingException {
ClientConfigMetricRequest clientMetrics = new ClientConfigMetricRequest();
clientMetrics.putAllHeader(HEADERS);
clientMetrics.getMetricsKeys()
.add(ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, String.join("+", KEY)));
clientMetrics.getMetricsKeys()
.add(ClientConfigMetricRequest.MetricsKey.build(SNAPSHOT_DATA, String.join("+", KEY)));
final String requestId = injectRequestUuId(clientMetrics);
String json = mapper.writeValueAsString(clientMetrics);
assertTrue(json.contains("\"type\":\"" + "cacheData" + "\""));
assertTrue(json.contains("\"type\":\"" + "snapshotData" + "\""));
assertTrue(json.contains("\"key\":\"" + String.join("+", KEY) + "\""));
assertTrue(json.contains("\"module\":\"" + Constants.Config.CONFIG_MODULE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json =
"{\"headers\":{\"header1\":\"test_header1\"}," + "\"metricsKeys\":[{\"type\":\"cacheData\",\"key\":"
+ "\"test_data+group+test_tenant\"},{\"type\":\"snapshotData\","
+ "\"key\":\"test_data+group+test_tenant\"}],\"module\":\"config\"}";
ClientConfigMetricRequest actual = mapper.readValue(json, ClientConfigMetricRequest.class);
assertEquals(actual.getMetricsKeys().size(), 2);
assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE);
assertEquals(actual.getHeader(HEADER_KEY), HEADER_VALUE);
}
@Test
public void testMetricsKeysEquals() {
String dataKey = String.join("+", KEY);
ClientConfigMetricRequest.MetricsKey key = ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, dataKey);
assertEquals(key, key);
assertFalse(key.equals(null));
assertFalse(key.equals(new ClientConfigMetricRequest()));
ClientConfigMetricRequest.MetricsKey newOne = ClientConfigMetricRequest.MetricsKey
.build(SNAPSHOT_DATA, dataKey);
assertNotEquals(key, newOne);
newOne.setType(CACHE_DATA);
assertEquals(key, newOne);
}
@Test
public void testMetricsHashCode() {
String dataKey = String.join("+", KEY);
ClientConfigMetricRequest.MetricsKey key = ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, dataKey);
assertEquals(Objects.hash(CACHE_DATA, dataKey), key.hashCode());
}
@Test
public void testMetricsToString() {
ClientConfigMetricRequest.MetricsKey key = ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, String.join("+", KEY));
assertEquals("MetricsKey{type='cacheData', key='test_data+group+test_tenant'}", key.toString());
}
}

View File

@ -0,0 +1,63 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.request;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConfigBatchListenRequestTest extends BasedConfigRequestTest {
@Override
@Test
public void testSerialize() throws JsonProcessingException {
ConfigBatchListenRequest configBatchListenRequest = new ConfigBatchListenRequest();
configBatchListenRequest.putAllHeader(HEADERS);
configBatchListenRequest.addConfigListenContext(GROUP, DATA_ID, TENANT, MD5);
final String requestId = injectRequestUuId(configBatchListenRequest);
String json = mapper.writeValueAsString(configBatchListenRequest);
assertTrue(json.contains("\"listen\":" + "true"));
assertTrue(json.contains(
"\"configListenContexts\":[{\"group\":\"group\",\"md5\":\"test_MD5\",\"dataId\":\"test_data\",\"tenant\":\"test_tenant\"}]"));
assertTrue(json.contains("\"module\":\"" + Constants.Config.CONFIG_MODULE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{\"header1\":\"test_header1\"},\"listen\":true,"
+ "\"configListenContexts\":[{\"group\":\"group\",\"md5\":\"test_MD5\","
+ "\"dataId\":\"test_data\",\"tenant\":\"test_tenant\"}],\"module\":\"config\"}";
ConfigBatchListenRequest actual = mapper.readValue(json, ConfigBatchListenRequest.class);
assertEquals(actual.isListen(), true);
assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE);
assertEquals(actual.getHeader(HEADER_KEY), HEADER_VALUE);
assertEquals(actual.getConfigListenContexts().size(), 1);
}
@Test
public void testConfigListenContextToString() {
ConfigBatchListenRequest configBatchListenRequest = new ConfigBatchListenRequest();
configBatchListenRequest.addConfigListenContext(GROUP, DATA_ID, TENANT, MD5);
assertEquals("ConfigListenContext{group='group', md5='test_MD5', dataId='test_data', tenant='test_tenant'}",
configBatchListenRequest.getConfigListenContexts().get(0).toString());
}
}

View File

@ -0,0 +1,63 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.request;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConfigChangeNotifyRequestTest extends BasedConfigRequestTest {
ConfigChangeNotifyRequest configChangeNotifyRequest;
String requestId;
@Before
public void before() {
configChangeNotifyRequest = ConfigChangeNotifyRequest.build(DATA_ID, GROUP, TENANT);
configChangeNotifyRequest.putAllHeader(HEADERS);
requestId = injectRequestUuId(configChangeNotifyRequest);
}
@Override
@Test
public void testSerialize() throws JsonProcessingException {
String json = mapper.writeValueAsString(configChangeNotifyRequest);
assertTrue(json.contains("\"module\":\"" + Constants.Config.CONFIG_MODULE));
assertTrue(json.contains("\"dataId\":\"" + DATA_ID));
assertTrue(json.contains("\"group\":\"" + GROUP));
assertTrue(json.contains("\"tenant\":\"" + TENANT));
assertTrue(json.contains("\"requestId\":\"" + requestId));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{\"header1\":\"test_header1\"},\"dataId\":\"test_data\",\"group\":"
+ "\"group\",\"tenant\":\"test_tenant\",\"module\":\"config\"}";
ConfigChangeNotifyRequest actual = mapper.readValue(json, ConfigChangeNotifyRequest.class);
assertEquals(actual.getDataId(), DATA_ID);
assertEquals(actual.getGroup(), GROUP);
assertEquals(actual.getTenant(), TENANT);
assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE);
assertEquals(actual.getHeader(HEADER_KEY), HEADER_VALUE);
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.request;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConfigPublishRequestTest extends BasedConfigRequestTest {
ConfigPublishRequest configPublishRequest;
private static final String TAG_PARAM = "tag";
private static final String APP_NAME_PARAM = "appName";
String requestId;
@Before
public void before() {
configPublishRequest = new ConfigPublishRequest(DATA_ID, GROUP, TENANT, CONTENT);
configPublishRequest.putAdditionalParam(TAG_PARAM, TAG_PARAM);
configPublishRequest.putAdditionalParam(APP_NAME_PARAM, APP_NAME_PARAM);
configPublishRequest.setCasMd5(MD5);
configPublishRequest.putAllHeader(HEADERS);
requestId = injectRequestUuId(configPublishRequest);
}
@Override
@Test
public void testSerialize() throws JsonProcessingException {
String json = mapper.writeValueAsString(configPublishRequest);
assertTrue(json.contains("\"module\":\"" + Constants.Config.CONFIG_MODULE));
assertTrue(json.contains("\"dataId\":\"" + DATA_ID));
assertTrue(json.contains("\"group\":\"" + GROUP));
assertTrue(json.contains("\"tenant\":\"" + TENANT));
assertTrue(json.contains("\"content\":\"" + CONTENT));
assertTrue(json.contains("\"casMd5\":\"" + MD5));
assertTrue(json.contains("\"requestId\":\"" + requestId));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{\"header1\":\"test_header1\"},\"dataId\":\"test_data\",\"group\":\"group\","
+ "\"tenant\":\"test_tenant\",\"content\":\"content\",\"casMd5\":\"test_MD5\","
+ "\"additionMap\":{\"appName\":\"appName\",\"tag\":\"tag\"},\"module\":\"config\"}";
ConfigPublishRequest actual = mapper.readValue(json, ConfigPublishRequest.class);
assertEquals(actual.getDataId(), DATA_ID);
assertEquals(actual.getGroup(), GROUP);
assertEquals(actual.getTenant(), TENANT);
assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE);
assertEquals(actual.getContent(), CONTENT);
assertEquals(actual.getCasMd5(), MD5);
assertEquals(actual.getAdditionParam(TAG_PARAM), TAG_PARAM);
assertEquals(actual.getAdditionParam(APP_NAME_PARAM), APP_NAME_PARAM);
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.request;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConfigQueryRequestTest extends BasedConfigRequestTest {
ConfigQueryRequest configQueryRequest;
Map<String, String> headers = new HashMap<>();
String requestId;
@Before
public void before() {
headers.put(Constants.Config.NOTIFY_HEADER, Boolean.TRUE.toString());
configQueryRequest = ConfigQueryRequest.build(DATA_ID, GROUP, TENANT);
configQueryRequest.putAllHeader(headers);
configQueryRequest.setTag(TAG);
requestId = injectRequestUuId(configQueryRequest);
}
@Test
public void testIsNotify() {
assertTrue(configQueryRequest.isNotify());
}
@Override
@Test
public void testSerialize() throws JsonProcessingException {
String json = mapper.writeValueAsString(configQueryRequest);
assertTrue(json.contains("\"module\":\"" + Constants.Config.CONFIG_MODULE));
assertTrue(json.contains("\"dataId\":\"" + DATA_ID));
assertTrue(json.contains("\"group\":\"" + GROUP));
assertTrue(json.contains("\"tenant\":\"" + TENANT));
assertTrue(json.contains("\"tag\":\"" + TAG));
assertTrue(json.contains("\"requestId\":\"" + requestId));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{\"notify\":\"true\"},\"dataId\":\"test_data\",\"group\":\"group\","
+ "\"tenant\":\"test_tenant\",\"notify\":true,\"module\":\"config\",\"tag\":\"tag\"}";
ConfigQueryRequest actual = mapper.readValue(json, ConfigQueryRequest.class);
assertEquals(actual.getDataId(), DATA_ID);
assertEquals(actual.getGroup(), GROUP);
assertEquals(actual.getTenant(), TENANT);
assertEquals(actual.getTag(), TAG);
assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE);
}
}

View File

@ -0,0 +1,65 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.request;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConfigRemoveRequestTest extends BasedConfigRequestTest {
ConfigRemoveRequest configRemoveRequest;
String requestId;
@Before
public void before() {
configRemoveRequest = new ConfigRemoveRequest(DATA_ID, GROUP, TENANT, TAG);
requestId = injectRequestUuId(configRemoveRequest);
}
@Override
@Test
public void testSerialize() throws JsonProcessingException {
String json = mapper.writeValueAsString(configRemoveRequest);
assertTrue(json.contains("\"module\":\"" + Constants.Config.CONFIG_MODULE));
assertTrue(json.contains("\"dataId\":\"" + DATA_ID));
assertTrue(json.contains("\"group\":\"" + GROUP));
assertTrue(json.contains("\"tenant\":\"" + TENANT));
assertTrue(json.contains("\"tag\":\"" + TAG));
assertTrue(json.contains("\"requestId\":\"" + requestId));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"dataId\":\"test_data\",\"group\":\"group\",\"tenant\":\"test_tenant\""
+ ",\"tag\":\"tag\",\"module\":\"config\"}";
ConfigRemoveRequest actual = mapper.readValue(json, ConfigRemoveRequest.class);
assertEquals(actual.getDataId(), DATA_ID);
assertEquals(actual.getGroup(), GROUP);
assertEquals(actual.getTenant(), TENANT);
assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE);
assertEquals(actual.getTag(), TAG);
}
}

View File

@ -0,0 +1,77 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.request.cluster;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.config.remote.request.BasedConfigRequestTest;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConfigChangeClusterSyncRequestTest extends BasedConfigRequestTest {
ConfigChangeClusterSyncRequest configChangeClusterSyncRequest;
String requestId;
@Before
public void before() {
configChangeClusterSyncRequest = new ConfigChangeClusterSyncRequest();
configChangeClusterSyncRequest.setDataId(DATA_ID);
configChangeClusterSyncRequest.setGroup(GROUP);
configChangeClusterSyncRequest.setTenant(TENANT);
configChangeClusterSyncRequest.setTag(TAG);
configChangeClusterSyncRequest.setBeta(Boolean.TRUE);
configChangeClusterSyncRequest.setLastModified(0L);
configChangeClusterSyncRequest.putAllHeader(HEADERS);
requestId = injectRequestUuId(configChangeClusterSyncRequest);
}
@Override
@Test
public void testSerialize() throws JsonProcessingException {
String json = mapper.writeValueAsString(configChangeClusterSyncRequest);
System.out.println(json);
assertTrue(json.contains("\"module\":\"" + Constants.Config.CONFIG_MODULE));
assertTrue(json.contains("\"dataId\":\"" + DATA_ID));
assertTrue(json.contains("\"group\":\"" + GROUP));
assertTrue(json.contains("\"tenant\":\"" + TENANT));
assertTrue(json.contains("\"tag\":\"" + TAG));
assertTrue(json.contains("\"beta\":" + Boolean.TRUE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
assertTrue(json.contains("\"lastModified\":" + 0));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{\"header1\":\"test_header1\"},\"requestId\":\"ece89111-3c42-4055-aca4-c95e16ec564b\",\"dataId\":\"test_data\","
+ "\"group\":\"group\",\"tenant\":\"test_tenant\","
+ "\"tag\":\"tag\",\"lastModified\":0,\"beta\":true,\"module\":\"config\"}";
ConfigChangeClusterSyncRequest actual = mapper.readValue(json, ConfigChangeClusterSyncRequest.class);
assertEquals(actual.getDataId(), DATA_ID);
assertEquals(actual.getGroup(), GROUP);
assertEquals(actual.getTenant(), TENANT);
assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE);
assertEquals(actual.getLastModified(), 0L);
assertTrue(actual.isBeta());
}
}

View File

@ -0,0 +1,48 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.response;
import com.alibaba.nacos.api.config.remote.request.BasedConfigRequestTest;
import com.alibaba.nacos.api.remote.response.Response;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.UUID;
public abstract class BasedConfigResponseTest extends BasedConfigRequestTest {
protected String requestId;
@Override
public void testSerialize() throws JsonProcessingException {
}
@Override
public void testDeserialize() throws JsonProcessingException {
}
public abstract void testSerializeSuccessResponse() throws JsonProcessingException;
public abstract void testSerializeFailResponse() throws JsonProcessingException;
protected String injectResponseUuId(Response response) {
String uuid = UUID.randomUUID().toString();
response.setRequestId(uuid);
return uuid;
}
}

View File

@ -0,0 +1,69 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.response;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ClientConfigMetricResponseTest extends BasedConfigResponseTest {
ClientConfigMetricResponse clientConfigMetricResponse;
Map<String, Object> metric = new HashMap<>(16);
@Before
public void before() {
metric.put("m1", "v1");
clientConfigMetricResponse = new ClientConfigMetricResponse();
clientConfigMetricResponse.setMetrics(metric);
clientConfigMetricResponse.putMetric("m2", "v2");
requestId = injectResponseUuId(clientConfigMetricResponse);
}
@Override
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
String json = mapper.writeValueAsString(clientConfigMetricResponse);
assertTrue(json.contains("\"success\":" + Boolean.TRUE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode()));
}
@Override
public void testSerializeFailResponse() throws JsonProcessingException {
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"requestId\":\"6ef9237b-24f3-448a-87fc-713f18ee06a1\","
+ "\"metrics\":{\"m1\":\"v1\",\"m2\":\"v2\"},\"success\":true}";
ClientConfigMetricResponse actual = mapper.readValue(json, ClientConfigMetricResponse.class);
assertTrue(actual.isSuccess());
assertEquals(actual.getResultCode(), ResponseCode.SUCCESS.getCode());
assertEquals(actual.getMetrics(), metric);
}
}

View File

@ -0,0 +1,77 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.response;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConfigChangeBatchListenResponseTest extends BasedConfigResponseTest {
ConfigChangeBatchListenResponse configChangeBatchListenResponse;
@Before
public void before() {
configChangeBatchListenResponse = new ConfigChangeBatchListenResponse();
requestId = injectResponseUuId(configChangeBatchListenResponse);
configChangeBatchListenResponse.addChangeConfig(DATA_ID, GROUP, TENANT);
}
@Override
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
String json = mapper.writeValueAsString(configChangeBatchListenResponse);
assertTrue(json.contains("\"success\":" + Boolean.TRUE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode()));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains(
"\"changedConfigs\":[{\"group\":\"group\",\"dataId\":\"test_data\",\"tenant\":\"test_tenant\"}]"));
}
@Override
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
ConfigChangeBatchListenResponse configChangeBatchListenResponse = ConfigChangeBatchListenResponse
.buildFailResponse("Fail");
String json = mapper.writeValueAsString(configChangeBatchListenResponse);
assertTrue(json.contains("\"resultCode\":" + ResponseCode.FAIL.getCode()));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"message\":\"Fail\""));
assertTrue(json.contains("\"success\":false"));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"requestId\":\"061e36b0-c7bd-4fd0-950c-73b13ca1cb2f\","
+ "\"changedConfigs\":[{\"group\":\"group\",\"dataId\":\"test_data\",\"tenant\":\"test_tenant\"}],\"success\":true}";
ConfigChangeBatchListenResponse actual = mapper.readValue(json, ConfigChangeBatchListenResponse.class);
assertTrue(actual.isSuccess());
assertEquals(ResponseCode.SUCCESS.getCode(), actual.getResultCode());
assertEquals("061e36b0-c7bd-4fd0-950c-73b13ca1cb2f", actual.getRequestId());
assertEquals(TENANT, actual.getChangedConfigs().get(0).getTenant());
assertEquals(GROUP, actual.getChangedConfigs().get(0).getGroup());
assertEquals(DATA_ID, actual.getChangedConfigs().get(0).getDataId());
assertEquals("ConfigContext{group='group', dataId='test_data', tenant='test_tenant'}",
actual.getChangedConfigs().get(0).toString());
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.response;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ConfigChangeNotifyResponseTest extends BasedConfigResponseTest {
ConfigChangeNotifyResponse configChangeNotifyResponse;
@Before
public void before() {
configChangeNotifyResponse = new ConfigChangeNotifyResponse();
requestId = injectResponseUuId(configChangeNotifyResponse);
}
@Override
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
String json = mapper.writeValueAsString(configChangeNotifyResponse);
assertTrue(json.contains("\"success\":" + Boolean.TRUE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode()));
assertTrue(json.contains("\"errorCode\":0"));
}
@Override
public void testSerializeFailResponse() throws JsonProcessingException {
}
}

View File

@ -0,0 +1,56 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.response;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ConfigPublishResponseTest extends BasedConfigResponseTest {
ConfigPublishResponse configPublishResponse;
@Before
public void before() {
configPublishResponse = ConfigPublishResponse.buildSuccessResponse();
requestId = injectResponseUuId(configPublishResponse);
}
@Override
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
String json = mapper.writeValueAsString(configPublishResponse);
assertTrue(json.contains("\"success\":" + Boolean.TRUE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode()));
assertTrue(json.contains("\"errorCode\":0"));
}
@Override
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
ConfigPublishResponse configPublishResponse = ConfigPublishResponse.buildFailResponse(500, "Fail");
String json = mapper.writeValueAsString(configPublishResponse);
assertTrue(json.contains("\"resultCode\":" + ResponseCode.FAIL.getCode()));
assertTrue(json.contains("\"errorCode\":500"));
assertTrue(json.contains("\"message\":\"Fail\""));
assertTrue(json.contains("\"success\":false"));
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.response;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConfigQueryResponseTest extends BasedConfigResponseTest {
ConfigQueryResponse configQueryResponse;
@Before
public void before() {
configQueryResponse = ConfigQueryResponse.buildSuccessResponse("success");
configQueryResponse.setContentType("text");
configQueryResponse.setEncryptedDataKey("encryptedKey");
configQueryResponse.setLastModified(1111111L);
configQueryResponse.setMd5(MD5);
configQueryResponse.setTag(TAG);
requestId = injectResponseUuId(configQueryResponse);
}
@Override
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
String json = mapper.writeValueAsString(configQueryResponse);
assertTrue(json.contains("\"success\":" + Boolean.TRUE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode()));
assertTrue(json.contains("\"md5\":\"" + MD5 + "\""));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"content\":\"success\""));
assertTrue(json.contains("\"contentType\":\"text\""));
assertTrue(json.contains("\"lastModified\":1111111"));
}
@Override
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
ConfigQueryResponse configQueryResponse = ConfigQueryResponse.buildFailResponse(500, "Fail");
String json = mapper.writeValueAsString(configQueryResponse);
assertTrue(json.contains("\"resultCode\":" + ResponseCode.FAIL.getCode()));
assertTrue(json.contains("\"errorCode\":500"));
assertTrue(json.contains("\"message\":\"Fail\""));
assertTrue(json.contains("\"success\":false"));
}
@Override
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"requestId\":\"2239753e-e682-441c-83cf-fb8129ca68a4\","
+ "\"content\":\"success\",\"encryptedDataKey\":\"encryptedKey\",\"contentType\":\"text\",\"md5\":\"test_MD5\","
+ "\"lastModified\":1111111,\"tag\":\"tag\",\"beta\":false,\"success\":true}\n";
ConfigQueryResponse actual = mapper.readValue(json, ConfigQueryResponse.class);
assertTrue(actual.isSuccess());
assertEquals(ResponseCode.SUCCESS.getCode(), actual.getResultCode());
assertEquals("success", actual.getContent());
assertEquals("text", actual.getContentType());
assertEquals("2239753e-e682-441c-83cf-fb8129ca68a4", actual.getRequestId());
assertEquals(MD5, actual.getMd5());
assertEquals(TAG, actual.getTag());
assertEquals("text", actual.getContentType());
assertEquals(1111111L, actual.getLastModified());
}
}

View File

@ -0,0 +1,56 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.response;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ConfigRemoveResponseTest extends BasedConfigResponseTest {
ConfigRemoveResponse configRemoveResponse;
@Before
public void before() {
configRemoveResponse = ConfigRemoveResponse.buildSuccessResponse();
requestId = injectResponseUuId(configRemoveResponse);
}
@Override
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
String json = mapper.writeValueAsString(configRemoveResponse);
assertTrue(json.contains("\"success\":" + Boolean.TRUE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode()));
assertTrue(json.contains("\"errorCode\":0"));
}
@Override
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
ConfigRemoveResponse configRemoveResponse = ConfigRemoveResponse.buildFailResponse("Fail");
String json = mapper.writeValueAsString(configRemoveResponse);
assertTrue(json.contains("\"resultCode\":" + ResponseCode.FAIL.getCode()));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"message\":\"Fail\""));
assertTrue(json.contains("\"success\":false"));
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.remote.response.cluster;
import com.alibaba.nacos.api.config.remote.response.BasedConfigResponseTest;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ConfigChangeClusterSyncResponseTest extends BasedConfigResponseTest {
ConfigChangeClusterSyncResponse configChangeClusterSyncResponse;
@Before
public void before() {
configChangeClusterSyncResponse = new ConfigChangeClusterSyncResponse();
requestId = injectResponseUuId(configChangeClusterSyncResponse);
}
@Override
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
String json = mapper.writeValueAsString(configChangeClusterSyncResponse);
assertTrue(json.contains("\"success\":" + Boolean.TRUE));
assertTrue(json.contains("\"requestId\":\"" + requestId));
assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode()));
assertTrue(json.contains("\"errorCode\":0"));
}
@Override
public void testSerializeFailResponse() throws JsonProcessingException {
}
}

View File

@ -0,0 +1,70 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception;
import com.alibaba.nacos.api.common.Constants;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NacosExceptionTest {
@Test
public void testEmptyConstructor() {
NacosException exception = new NacosException();
assertEquals(0, exception.getErrCode());
assertEquals(Constants.NULL, exception.getErrMsg());
assertEquals("ErrCode:0, ErrMsg:", exception.toString());
exception.setErrCode(NacosException.INVALID_PARAM);
exception.setErrMsg("test");
assertEquals("ErrCode:400, ErrMsg:test", exception.toString());
}
@Test
public void testConstructorWithErrMsg() {
NacosException exception = new NacosException(NacosException.SERVER_ERROR, "test");
assertEquals(NacosException.SERVER_ERROR, exception.getErrCode());
assertEquals("test", exception.getErrMsg());
assertEquals("ErrCode:500, ErrMsg:test", exception.toString());
}
@Test
public void testConstructorWithCause() {
NacosException exception = new NacosException(NacosException.SERVER_ERROR, new RuntimeException("cause test"));
assertEquals(NacosException.SERVER_ERROR, exception.getErrCode());
assertEquals("cause test", exception.getErrMsg());
assertEquals("ErrCode:500, ErrMsg:cause test", exception.toString());
}
@Test
public void testConstructorWithMultiCauses() {
NacosException exception = new NacosException(NacosException.SERVER_ERROR,
new RuntimeException("cause test", new RuntimeException("multi")));
assertEquals(NacosException.SERVER_ERROR, exception.getErrCode());
assertEquals("multi", exception.getErrMsg());
assertEquals("ErrCode:500, ErrMsg:multi", exception.toString());
}
@Test
public void testConstructorWithFull() {
NacosException exception = new NacosException(NacosException.SERVER_ERROR, "test",
new RuntimeException("cause test"));
assertEquals(NacosException.SERVER_ERROR, exception.getErrCode());
assertEquals("test", exception.getErrMsg());
assertEquals("ErrCode:500, ErrMsg:test", exception.toString());
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.api;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.model.v2.ErrorCode;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NacosApiExceptionTest {
@Test
public void testEmptyConstructor() {
NacosApiException exception = new NacosApiException();
assertEquals(0, exception.getErrCode());
assertEquals(0, exception.getDetailErrCode());
assertEquals(Constants.NULL, exception.getErrMsg());
assertEquals(Constants.NULL, exception.getErrAbstract());
}
@Test
public void testConstructorWithoutCause() {
NacosApiException exception = new NacosApiException(500, ErrorCode.SERVER_ERROR, "test");
assertEquals(500, exception.getErrCode());
assertEquals(ErrorCode.SERVER_ERROR.getCode().intValue(), exception.getDetailErrCode());
assertEquals("test", exception.getErrMsg());
assertEquals(ErrorCode.SERVER_ERROR.getMsg(), exception.getErrAbstract());
}
@Test
public void testConstructorWithCause() {
NacosApiException exception = new NacosApiException(500, ErrorCode.SERVER_ERROR,
new RuntimeException("cause test"), "test");
assertEquals(500, exception.getErrCode());
assertEquals(ErrorCode.SERVER_ERROR.getCode().intValue(), exception.getDetailErrCode());
assertEquals("test", exception.getErrMsg());
assertEquals(ErrorCode.SERVER_ERROR.getMsg(), exception.getErrAbstract());
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.runtime;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.databind.type.SimpleType;
import org.junit.Test;
import java.lang.reflect.Type;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class NacosDeserializationExceptionTest {
@Test
public void testEmptyConstructor() {
NacosDeserializationException exception = new NacosDeserializationException();
assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode());
assertNull(exception.getMessage());
assertNull(exception.getTargetClass());
}
@Test
public void testConstructorWithTargetClass() {
NacosDeserializationException exception = new NacosDeserializationException(
NacosDeserializationExceptionTest.class);
assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals(String.format("errCode: 101, errMsg: Nacos deserialize for class [%s] failed. ",
NacosDeserializationExceptionTest.class.getName()), exception.getMessage());
assertEquals(NacosDeserializationExceptionTest.class, exception.getTargetClass());
}
@Test
public void testConstructorWithTargetType() {
Type type = SimpleType.constructUnsafe(NacosDeserializationExceptionTest.class);
NacosDeserializationException exception = new NacosDeserializationException(type);
assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals(
String.format("errCode: 101, errMsg: Nacos deserialize for class [%s] failed. ", type.getTypeName()),
exception.getMessage());
assertNull(exception.getTargetClass());
}
@Test
public void testConstructorWithCause() {
NacosDeserializationException exception = new NacosDeserializationException(new RuntimeException("test"));
assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals("errCode: 101, errMsg: Nacos deserialize failed. ", exception.getMessage());
assertNull(exception.getTargetClass());
}
@Test
public void testConstructorWithTargetClassAndCause() {
NacosDeserializationException exception = new NacosDeserializationException(
NacosDeserializationExceptionTest.class, new RuntimeException("test"));
assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals(String.format("errCode: 101, errMsg: Nacos deserialize for class [%s] failed, cause error[%s]. ",
NacosDeserializationExceptionTest.class.getName(), "test"), exception.getMessage());
assertEquals(NacosDeserializationExceptionTest.class, exception.getTargetClass());
}
@Test
public void testConstructorWithTargetTypeAndCause() {
Type type = SimpleType.constructUnsafe(NacosDeserializationExceptionTest.class);
NacosDeserializationException exception = new NacosDeserializationException(type, new RuntimeException("test"));
assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals(String.format("errCode: 101, errMsg: Nacos deserialize for class [%s] failed, cause error[%s]. ",
type.getTypeName(), "test"), exception.getMessage());
assertNull(exception.getTargetClass());
}
}

View File

@ -0,0 +1,32 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.runtime;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class NacosLoadExceptionTest {
@Test
public void testConstructor() {
NacosLoadException exception = new NacosLoadException("test");
assertEquals("test", exception.getMessage());
assertNull(exception.getCause());
}
}

View File

@ -0,0 +1,61 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.runtime;
import com.alibaba.nacos.api.exception.NacosException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class NacosRuntimeExceptionTest {
@Test
public void testConstructorWithErrorCode() {
NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM);
assertEquals(NacosException.INVALID_PARAM, exception.getErrCode());
assertNull(exception.getMessage());
assertNull(exception.getCause());
}
@Test
public void testConstructorWithErrorCodeAndMsg() {
NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM, "test");
assertEquals(NacosException.INVALID_PARAM, exception.getErrCode());
assertEquals("errCode: 400, errMsg: test ", exception.getMessage());
assertNull(exception.getCause());
}
@Test
public void testConstructorWithErrorCodeAndCause() {
NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM,
new RuntimeException("test"));
assertEquals(NacosException.INVALID_PARAM, exception.getErrCode());
assertEquals("java.lang.RuntimeException: test", exception.getMessage());
assertTrue(exception.getCause() instanceof RuntimeException);
}
@Test
public void testConstructorWithFull() {
NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM,
"test", new RuntimeException("cause test"));
assertEquals(NacosException.INVALID_PARAM, exception.getErrCode());
assertEquals("errCode: 400, errMsg: test ", exception.getMessage());
assertTrue(exception.getCause() instanceof RuntimeException);
}
}

View File

@ -0,0 +1,61 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.runtime;
import com.alibaba.nacos.api.common.Constants;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class NacosSerializationExceptionTest {
@Test
public void testEmptyConstructor() {
NacosSerializationException exception = new NacosSerializationException();
assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode());
assertNull(exception.getMessage());
assertNull(exception.getSerializedClass());
}
@Test
public void testConstructorWithSerializedClass() {
NacosSerializationException exception = new NacosSerializationException(NacosSerializationExceptionTest.class);
assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals(String.format("errCode: 100, errMsg: Nacos serialize for class [%s] failed. ",
NacosSerializationExceptionTest.class.getName()), exception.getMessage());
assertEquals(NacosSerializationExceptionTest.class, exception.getSerializedClass());
}
@Test
public void testConstructorWithCause() {
NacosSerializationException exception = new NacosSerializationException(new RuntimeException("test"));
assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals("errCode: 100, errMsg: Nacos serialize failed. ", exception.getMessage());
assertNull(exception.getSerializedClass());
}
@Test
public void testConstructorWithSerializedClassAndCause() {
NacosSerializationException exception = new NacosSerializationException(NacosSerializationExceptionTest.class,
new RuntimeException("test"));
assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals(String.format("errCode: 100, errMsg: Nacos serialize for class [%s] failed. ",
NacosSerializationExceptionTest.class.getName(), "test"), exception.getMessage());
assertEquals(NacosSerializationExceptionTest.class, exception.getSerializedClass());
}
}

View File

@ -0,0 +1,71 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.model.v2;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ResultTest {
@Test
public void testSuccessEmptyResult() {
Result<String> result = Result.success();
assertNull(result.getData());
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals(ErrorCode.SUCCESS.getMsg(), result.getMessage());
}
@Test
public void testSuccessWithData() {
Result<String> result = Result.success("test");
assertEquals("test", result.getData());
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals(ErrorCode.SUCCESS.getMsg(), result.getMessage());
}
@Test
public void testFailureMessageResult() {
Result<String> result = Result.failure("test");
assertNull(result.getData());
assertEquals(ErrorCode.SERVER_ERROR.getCode(), result.getCode());
assertEquals("test", result.getMessage());
}
@Test
public void testFailureWithoutData() {
Result<String> result = Result.failure(ErrorCode.DATA_ACCESS_ERROR);
assertNull(result.getData());
assertEquals(ErrorCode.DATA_ACCESS_ERROR.getCode(), result.getCode());
assertEquals(ErrorCode.DATA_ACCESS_ERROR.getMsg(), result.getMessage());
}
@Test
public void testFailureWithData() {
Result<String> result = Result.failure(ErrorCode.DATA_ACCESS_ERROR, "error");
assertEquals("error", result.getData());
assertEquals(ErrorCode.DATA_ACCESS_ERROR.getCode(), result.getCode());
assertEquals(ErrorCode.DATA_ACCESS_ERROR.getMsg(), result.getMessage());
}
@Test
public void testToString() {
Result<String> result = Result.success("test");
assertEquals("Result{errorCode=0, message='success', data=test}", result.toString());
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.ability;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ClientNamingAbilityTest {
@Test
public void testGetAndSet() {
ClientNamingAbility ability = new ClientNamingAbility();
assertFalse(ability.isSupportDeltaPush());
assertFalse(ability.isSupportRemoteMetric());
ability.setSupportDeltaPush(true);
ability.setSupportRemoteMetric(true);
assertTrue(ability.isSupportDeltaPush());
assertTrue(ability.isSupportRemoteMetric());
}
}

View File

@ -26,6 +26,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ServerNamingAbilityTest { public class ServerNamingAbilityTest {
@ -57,4 +58,29 @@ public class ServerNamingAbilityTest {
actual.setSupportJraft(true); actual.setSupportJraft(true);
assertEquals(expected, actual); assertEquals(expected, actual);
} }
@Test
public void testEqualsForOneObject() {
ServerNamingAbility ability = new ServerNamingAbility();
assertTrue(ability.equals(ability));
}
@Test
public void testEqualsForOtherAbility() {
ServerNamingAbility ability = new ServerNamingAbility();
assertFalse(ability.equals(new ClientNamingAbility()));
}
@Test
public void testHashCode() throws JsonProcessingException {
ServerNamingAbility expected = new ServerNamingAbility();
expected.setSupportJraft(true);
String serializeJson = jacksonMapper.writeValueAsString(expected);
ServerNamingAbility actual = jacksonMapper.readValue(serializeJson, ServerNamingAbility.class);
assertEquals(expected, actual);
actual = new ServerNamingAbility();
assertNotEquals(expected, actual);
actual.setSupportJraft(true);
assertEquals(expected.hashCode(), actual.hashCode());
}
} }

View File

@ -0,0 +1,77 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.listener;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class NamingEventTest {
private MockNamingEventListener eventListener;
@Before
public void setUp() throws Exception {
eventListener = new MockNamingEventListener();
}
@Test
public void testNamingEventWithSimpleConstructor() {
NamingEvent event = new NamingEvent("serviceName", Collections.EMPTY_LIST);
assertEquals("serviceName", event.getServiceName());
assertNull(event.getGroupName());
assertNull(event.getClusters());
assertTrue(event.getInstances().isEmpty());
eventListener.onEvent(event);
assertNull(event.getServiceName());
assertNull(event.getGroupName());
assertNull(event.getClusters());
assertNull(event.getInstances());
}
@Test
public void testNamingEventWithFullConstructor() {
NamingEvent event = new NamingEvent("serviceName", "group", "clusters", Collections.EMPTY_LIST);
assertEquals("serviceName", event.getServiceName());
assertEquals("group", event.getGroupName());
assertEquals("clusters", event.getClusters());
assertTrue(event.getInstances().isEmpty());
eventListener.onEvent(event);
assertNull(event.getServiceName());
assertNull(event.getGroupName());
assertNull(event.getClusters());
assertNull(event.getInstances());
}
private static class MockNamingEventListener extends AbstractEventListener {
@Override
public void onEvent(Event event) {
assertNull(getExecutor());
NamingEvent namingEvent = (NamingEvent) event;
namingEvent.setServiceName(null);
namingEvent.setGroupName(null);
namingEvent.setClusters(null);
namingEvent.setInstances(null);
}
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ClusterTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSetAndGet() {
Cluster actual = new Cluster();
assertNull(actual.getName());
assertNull(actual.getServiceName());
assertEquals(Tcp.TYPE, actual.getHealthChecker().getType());
assertEquals(80, actual.getDefaultPort());
assertEquals(80, actual.getDefaultCheckPort());
assertTrue(actual.isUseIPPort4Check());
assertTrue(actual.getMetadata().isEmpty());
actual.setName("cluster");
actual.setServiceName("group@@service");
actual.setHealthChecker(new Http());
actual.setDefaultPort(81);
actual.setDefaultCheckPort(82);
actual.setUseIPPort4Check(false);
actual.setMetadata(Collections.singletonMap("a", "a"));
assertEquals("cluster", actual.getName());
assertEquals("group@@service", actual.getServiceName());
assertEquals(Http.TYPE, actual.getHealthChecker().getType());
assertEquals(81, actual.getDefaultPort());
assertEquals(82, actual.getDefaultCheckPort());
assertFalse(actual.isUseIPPort4Check());
assertFalse(actual.getMetadata().isEmpty());
assertTrue(actual.getMetadata().containsKey("a"));
assertEquals("a", actual.getMetadata().get("a"));
}
@Test
public void testJsonSerialize() throws JsonProcessingException {
Cluster actual = new Cluster("cluster");
actual.setServiceName("group@@service");
actual.setHealthChecker(new Http());
actual.setDefaultPort(81);
actual.setDefaultCheckPort(82);
actual.setUseIPPort4Check(false);
actual.setMetadata(Collections.singletonMap("a", "a"));
String json = mapper.writeValueAsString(actual);
assertTrue(json.contains("\"serviceName\":\"group@@service\""));
assertTrue(json.contains("\"name\":\"cluster\""));
assertTrue(json.contains("\"type\":\"HTTP\""));
assertTrue(json.contains("\"defaultPort\":81"));
assertTrue(json.contains("\"defaultCheckPort\":82"));
assertTrue(json.contains("\"useIPPort4Check\":false"));
assertTrue(json.contains("\"metadata\":{\"a\":\"a\"}"));
}
@Test
public void testJsonDeserialize() throws JsonProcessingException {
String json = "{\"serviceName\":\"group@@service\",\"name\":\"cluster\","
+ "\"healthChecker\":{\"type\":\"HTTP\",\"path\":\"\",\"headers\":\"\",\"expectedResponseCode\":200},"
+ "\"defaultPort\":81,\"defaultCheckPort\":82,\"useIPPort4Check\":false,\"metadata\":{\"a\":\"a\"}}";
Cluster actual = mapper.readValue(json, Cluster.class);
assertEquals("cluster", actual.getName());
assertEquals("group@@service", actual.getServiceName());
assertEquals(Http.TYPE, actual.getHealthChecker().getType());
assertEquals(81, actual.getDefaultPort());
assertEquals(82, actual.getDefaultCheckPort());
assertFalse(actual.isUseIPPort4Check());
assertFalse(actual.getMetadata().isEmpty());
assertTrue(actual.getMetadata().containsKey("a"));
assertEquals("a", actual.getMetadata().get("a"));
}
}

View File

@ -16,10 +16,80 @@
package com.alibaba.nacos.api.naming.pojo; package com.alibaba.nacos.api.naming.pojo;
import junit.framework.TestCase; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
public class InstanceTest extends TestCase { import java.util.Collections;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class InstanceTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSetAndGet() {
Instance instance = new Instance();
assertNull(instance.getInstanceId());
assertNull(instance.getIp());
assertEquals(0, instance.getPort());
assertEquals(1.0D, instance.getWeight(), 0.1);
assertTrue(instance.isHealthy());
assertTrue(instance.isEnabled());
assertTrue(instance.isEphemeral());
assertNull(instance.getClusterName());
assertNull(instance.getServiceName());
assertTrue(instance.getMetadata().isEmpty());
setInstance(instance);
checkInstance(instance);
}
@Test
public void testJsonSerialize() throws JsonProcessingException {
Instance instance = new Instance();
setInstance(instance);
String actual = mapper.writeValueAsString(instance);
assertTrue(actual.contains("\"instanceId\":\"id\""));
assertTrue(actual.contains("\"ip\":\"1.1.1.1\""));
assertTrue(actual.contains("\"port\":1000"));
assertTrue(actual.contains("\"weight\":100.0"));
assertTrue(actual.contains("\"healthy\":false"));
assertTrue(actual.contains("\"enabled\":false"));
assertTrue(actual.contains("\"ephemeral\":false"));
assertTrue(actual.contains("\"clusterName\":\"cluster\""));
assertTrue(actual.contains("\"serviceName\":\"group@@serviceName\""));
assertTrue(actual.contains("\"metadata\":{\"a\":\"b\"}"));
assertTrue(actual.contains("\"instanceHeartBeatInterval\":5000"));
assertTrue(actual.contains("\"instanceHeartBeatTimeOut\":15000"));
assertTrue(actual.contains("\"ipDeleteTimeout\":30000"));
}
@Test
public void testJsonDeserialize() throws JsonProcessingException {
String json = "{\"instanceId\":\"id\",\"ip\":\"1.1.1.1\",\"port\":1000,\"weight\":100.0,\"healthy\":false,"
+ "\"enabled\":false,\"ephemeral\":false,\"clusterName\":\"cluster\","
+ "\"serviceName\":\"group@@serviceName\",\"metadata\":{\"a\":\"b\"},\"instanceHeartBeatInterval\":5000,"
+ "\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000}";
Instance instance = mapper.readValue(json, Instance.class);
checkInstance(instance);
}
@Test @Test
public void testCheckClusterNameFormat() { public void testCheckClusterNameFormat() {
@ -27,4 +97,73 @@ public class InstanceTest extends TestCase {
instance.setClusterName("demo"); instance.setClusterName("demo");
assertEquals("demo", instance.getClusterName()); assertEquals("demo", instance.getClusterName());
} }
@Test
public void testToInetAddr() {
Instance instance = new Instance();
setInstance(instance);
assertEquals("1.1.1.1:1000", instance.toInetAddr());
}
@Test
public void testContainsMetadata() {
Instance instance = new Instance();
assertFalse(instance.containsMetadata("a"));
instance.setMetadata(null);
assertFalse(instance.containsMetadata("a"));
instance.addMetadata("a", "b");
assertTrue(instance.containsMetadata("a"));
}
@Test
public void testGetInstanceIdGenerator() {
Instance instance = new Instance();
assertEquals(Constants.DEFAULT_INSTANCE_ID_GENERATOR, instance.getInstanceIdGenerator());
instance.addMetadata(PreservedMetadataKeys.INSTANCE_ID_GENERATOR, "test");
assertEquals("test", instance.getInstanceIdGenerator());
}
@Test
public void testEquals() {
Instance actual = new Instance();
setInstance(actual);
actual.setMetadata(new HashMap<>());
actual.addMetadata("a", "b");
assertFalse(actual.equals(new Object()));
Instance expected = new Instance();
setInstance(expected);
expected.setMetadata(new HashMap<>());
expected.addMetadata("a", "b");
assertTrue(actual.equals(expected));
expected.addMetadata("a", "c");
assertFalse(actual.equals(expected));
}
private void setInstance(Instance instance) {
instance.setInstanceId("id");
instance.setIp("1.1.1.1");
instance.setPort(1000);
instance.setWeight(100);
instance.setHealthy(false);
instance.setEnabled(false);
instance.setEphemeral(false);
instance.setClusterName("cluster");
instance.setServiceName("group@@serviceName");
instance.setMetadata(Collections.singletonMap("a", "b"));
}
private void checkInstance(Instance instance) {
assertEquals("id", instance.getInstanceId());
assertEquals("1.1.1.1", instance.getIp());
assertEquals(1000, instance.getPort());
assertEquals(100D, instance.getWeight(), 0.1);
assertFalse(instance.isHealthy());
assertFalse(instance.isEnabled());
assertFalse(instance.isEphemeral());
assertEquals("cluster", instance.getClusterName());
assertEquals("group@@serviceName", instance.getServiceName());
assertFalse(instance.getMetadata().isEmpty());
assertTrue(instance.containsMetadata("a"));
assertEquals("b", instance.getMetadata().get("a"));
}
} }

View File

@ -0,0 +1,53 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo;
import org.junit.Test;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ListViewTest {
@Test
public void testToString() {
List<String> data = new LinkedList<>();
data.add("1");
data.add("2");
data.add("3");
ListView<String> listView = new ListView<>();
listView.setData(data);
listView.setCount(data.size());
String actual = listView.toString();
assertEquals("ListView{data=[1, 2, 3], count=3}", actual);
}
@Test
public void testSetAndGet() {
ListView<String> listView = new ListView<>();
assertEquals(0, listView.getCount());
assertNull(listView.getData());
listView.setCount(1);
listView.setData(Collections.singletonList("1"));
assertEquals(1, listView.getCount());
assertEquals(1, listView.getData().size());
}
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.api.naming.pojo; package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.nacos.api.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@ -25,6 +26,9 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@ -65,11 +69,13 @@ public class ServiceInfoTest {
+ "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"valid\":true,\"groupName\":\"\"}"; + "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"valid\":true,\"groupName\":\"\"}";
ServiceInfo actual = mapper.readValue(example, ServiceInfo.class); ServiceInfo actual = mapper.readValue(example, ServiceInfo.class);
assertEquals("G@@testName", actual.getName()); assertEquals("G@@testName", actual.getName());
assertEquals(0, actual.ipCount());
assertEquals("testClusters", actual.getClusters()); assertEquals("testClusters", actual.getClusters());
assertEquals("", actual.getChecksum()); assertEquals("", actual.getChecksum());
assertEquals("", actual.getGroupName()); assertEquals("", actual.getGroupName());
assertEquals(1000, actual.getCacheMillis()); assertEquals(1000, actual.getCacheMillis());
assertEquals(0, actual.getLastRefTime()); assertEquals(0, actual.getLastRefTime());
assertTrue(actual.expired());
assertTrue(actual.getHosts().isEmpty()); assertTrue(actual.getHosts().isEmpty());
assertTrue(actual.isValid()); assertTrue(actual.isValid());
assertFalse(actual.isAllIPs()); assertFalse(actual.isAllIPs());
@ -79,6 +85,7 @@ public class ServiceInfoTest {
public void testGetKey() { public void testGetKey() {
String key = serviceInfo.getKey(); String key = serviceInfo.getKey();
assertEquals("G@@testName@@testClusters", key); assertEquals("G@@testName@@testClusters", key);
assertEquals("G@@testName@@testClusters", serviceInfo.toString());
} }
@Test @Test
@ -102,4 +109,67 @@ public class ServiceInfoTest {
assertEquals(key1, s1.getKey()); assertEquals(key1, s1.getKey());
assertEquals(key2, s2.getKey()); assertEquals(key2, s2.getKey());
} }
@Test(expected = IllegalArgumentException.class)
public void testServiceInfoConstructorWithError() {
String key1 = "name";
ServiceInfo s1 = new ServiceInfo(key1);
}
@Test
public void testValidateForAllIps() {
serviceInfo.setAllIPs(true);
assertTrue(serviceInfo.validate());
}
@Test
public void testValidateForNullHosts() {
serviceInfo.setHosts(null);
assertFalse(serviceInfo.validate());
}
@Test
public void testValidateForEmptyHosts() {
serviceInfo.setHosts(Collections.EMPTY_LIST);
assertFalse(serviceInfo.validate());
}
@Test
public void testValidateForUnhealthyHosts() {
Instance instance = new Instance();
instance.setHealthy(false);
serviceInfo.addHost(instance);
assertFalse(serviceInfo.validate());
}
@Test
public void testValidateForBothUnhealthyAndHealthyHosts() {
List<Instance> instanceList = new LinkedList<>();
Instance instance = new Instance();
instanceList.add(instance);
instance = new Instance();
instance.setHealthy(false);
instanceList.add(instance);
serviceInfo.addAllHosts(instanceList);
assertTrue(serviceInfo.validate());
}
@Test
public void testFromKey() {
String key1 = "group@@name";
String key2 = "group@@name@@c2";
ServiceInfo s1 = ServiceInfo.fromKey(key1);
ServiceInfo s2 = ServiceInfo.fromKey(key2);
assertEquals(key1, s1.getKey());
assertEquals(key2, s2.getKey());
}
@Test
public void testSetAndGet() throws JsonProcessingException {
serviceInfo.setReachProtectionThreshold(true);
serviceInfo.setJsonFromServer(mapper.writeValueAsString(serviceInfo));
ServiceInfo actual = mapper.readValue(serviceInfo.getJsonFromServer(), ServiceInfo.class);
assertEquals(StringUtils.EMPTY, actual.getJsonFromServer());
assertTrue(actual.isReachProtectionThreshold());
}
} }

View File

@ -0,0 +1,62 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ServiceTest {
@Test
public void testSetAndGet() {
Service service = new Service();
assertNull(service.getName());
assertNull(service.getAppName());
assertNull(service.getGroupName());
assertEquals(0.0f, service.getProtectThreshold(), 0.1);
assertTrue(service.getMetadata().isEmpty());
service.setName("service");
service.setGroupName("group");
service.setAppName("app");
service.setProtectThreshold(1.0f);
HashMap<String, String> metadata = new HashMap<>();
service.setMetadata(metadata);
service.addMetadata("a", "b");
assertEquals("service", service.getName());
assertEquals("app", service.getAppName());
assertEquals("group", service.getGroupName());
assertEquals(1.0f, service.getProtectThreshold(), 0.1);
assertEquals(1, service.getMetadata().size());
assertEquals("b", service.getMetadata().get("a"));
}
@Test
public void testToString() {
Service service = new Service("service");
service.setGroupName("group");
service.setAppName("app");
service.setProtectThreshold(1.0f);
service.setMetadata(Collections.singletonMap("a", "b"));
assertEquals("Service{name='service', protectThreshold=1.0, appName='app', groupName='group', metadata={a=b}}", service.toString());
}
}

View File

@ -19,7 +19,11 @@ package com.alibaba.nacos.api.naming.pojo.builder;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.Test; import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -67,6 +71,24 @@ public class InstanceBuilderTest {
assertThat(actual.getMetadata().get(META_KEY), is(META_VALUE)); assertThat(actual.getMetadata().get(META_KEY), is(META_VALUE));
} }
@Test
public void testBuildInstanceWithoutNewMetadata() {
InstanceBuilder builder = InstanceBuilder.newBuilder();
Map<String, String> metadata = new HashMap<>();
metadata.put("test", "test");
Instance actual = builder.setMetadata(metadata).build();
assertNull(actual.getServiceName());
assertNull(actual.getClusterName());
assertNull(actual.getInstanceId());
assertNull(actual.getIp());
assertThat(actual.getPort(), is(0));
assertThat(actual.getWeight(), is(1.0));
assertTrue(actual.isHealthy());
assertTrue(actual.isEnabled());
assertTrue(actual.isEphemeral());
assertEquals(1, actual.getMetadata().size());
}
@Test @Test
public void testBuildEmptyInstance() { public void testBuildEmptyInstance() {
InstanceBuilder builder = InstanceBuilder.newBuilder(); InstanceBuilder builder = InstanceBuilder.newBuilder();

View File

@ -54,4 +54,10 @@ public class AbstractHealthCheckerTest {
assertEquals("", actual.getTestValue()); assertEquals("", actual.getTestValue());
assertEquals(TestChecker.TYPE, actual.getType()); assertEquals(TestChecker.TYPE, actual.getType());
} }
@Test
public void testClone() throws CloneNotSupportedException {
AbstractHealthChecker none = new AbstractHealthChecker.None().clone();
assertEquals(AbstractHealthChecker.None.class, none.getClass());
}
} }

View File

@ -0,0 +1,56 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo.healthcheck;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Mysql;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class HealthCheckTypeTest {
@Test
public void testOfHealthCheckerClassForBuildInType() {
assertEquals(Tcp.class, HealthCheckType.ofHealthCheckerClass("TCP"));
assertEquals(Http.class, HealthCheckType.ofHealthCheckerClass("HTTP"));
assertEquals(Mysql.class, HealthCheckType.ofHealthCheckerClass("MYSQL"));
assertEquals(AbstractHealthChecker.None.class, HealthCheckType.ofHealthCheckerClass("NONE"));
}
@Test
public void testOfHealthCheckerClassForExtendType() {
HealthCheckType.registerHealthChecker(TestChecker.TYPE, TestChecker.class);
assertEquals(TestChecker.class, HealthCheckType.ofHealthCheckerClass(TestChecker.TYPE));
}
@Test
public void testOfHealthCheckerClassForNonExistType() {
assertNull(HealthCheckType.ofHealthCheckerClass("non-exist"));
}
@Test
public void testGetLoadedHealthCheckerClasses() {
HealthCheckType.registerHealthChecker(TestChecker.TYPE, TestChecker.class);
List<Class<? extends AbstractHealthChecker>> actual = HealthCheckType.getLoadedHealthCheckerClasses();
assertEquals(5, actual.size());
}
}

View File

@ -16,18 +16,21 @@
package com.alibaba.nacos.api.naming.pojo.healthcheck; package com.alibaba.nacos.api.naming.pojo.healthcheck;
import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException;
import com.alibaba.nacos.api.exception.runtime.NacosSerializationException;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp; import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class HealthCheckerFactoryTest { public class HealthCheckerFactoryTest {
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() {
HealthCheckerFactory.registerSubType(TestChecker.class, TestChecker.TYPE); HealthCheckerFactory.registerSubType(new TestChecker());
} }
@Test @Test
@ -57,4 +60,74 @@ public class HealthCheckerFactoryTest {
AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString); AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString);
assertEquals(TestChecker.class, actual.getClass()); assertEquals(TestChecker.class, actual.getClass());
} }
@Test
public void testSerializeNoRegister() {
NoRegisterHealthChecker noRegister = new NoRegisterHealthChecker();
assertFalse(HealthCheckerFactory.serialize(noRegister).contains("no register"));
}
@Test
public void testDeserializeNoRegister() {
String tcpString = "{\"type\":\"no register\",\"testValue\":null}";
AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString);
assertEquals(AbstractHealthChecker.None.class, actual.getClass());
}
@Test(expected = NacosSerializationException.class)
public void testSerializeFailure() {
SelfDependHealthChecker selfDependHealthChecker = new SelfDependHealthChecker();
System.out.println(HealthCheckerFactory.serialize(selfDependHealthChecker));
}
@Test(expected = NacosDeserializationException.class)
public void testDeserializeFailure() {
String errorString = "{\"type\"=\"TCP\"}";
System.out.println(HealthCheckerFactory.deserialize(errorString));
}
@Test
public void testCreateNoneHealthChecker() {
assertEquals(AbstractHealthChecker.None.class, HealthCheckerFactory.createNoneHealthChecker().getClass());
}
private static class NoRegisterHealthChecker extends AbstractHealthChecker {
private static final long serialVersionUID = 9020783491111797559L;
private String testValue;
protected NoRegisterHealthChecker() {
super("no register");
}
public String getTestValue() {
return testValue;
}
public void setTestValue(String testValue) {
this.testValue = testValue;
}
@Override
public AbstractHealthChecker clone() throws CloneNotSupportedException {
return null;
}
}
private static class SelfDependHealthChecker extends AbstractHealthChecker {
private static final long serialVersionUID = 876677992848225965L;
public SelfDependHealthChecker self = this;
protected SelfDependHealthChecker() {
super("self depend");
}
@Override
public AbstractHealthChecker clone() throws CloneNotSupportedException {
return null;
}
}
} }

View File

@ -76,4 +76,25 @@ public class HttpTest {
assertEquals("x:a|y:", actual.getHeaders()); assertEquals("x:a|y:", actual.getHeaders());
assertEquals(Http.TYPE, actual.getType()); assertEquals(Http.TYPE, actual.getType());
} }
@Test
public void testClone() throws CloneNotSupportedException {
Http cloned = http.clone();
assertEquals(http.hashCode(), cloned.hashCode());
assertTrue(http.equals(cloned));
}
@Test
public void testNotEquals() throws CloneNotSupportedException {
assertFalse(http.equals(new Tcp()));
Http cloned = http.clone();
cloned.setPath("aaa");
assertFalse(http.equals(cloned));
cloned = http.clone();
cloned.setHeaders("aaa");
assertFalse(http.equals(cloned));
cloned = http.clone();
cloned.setExpectedResponseCode(500);
assertFalse(http.equals(cloned));
}
} }

View File

@ -24,6 +24,7 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class MysqlTest { public class MysqlTest {
@ -59,4 +60,25 @@ public class MysqlTest {
assertEquals("user", actual.getUser()); assertEquals("user", actual.getUser());
assertEquals(Mysql.TYPE, actual.getType()); assertEquals(Mysql.TYPE, actual.getType());
} }
@Test
public void testClone() throws CloneNotSupportedException {
Mysql cloned = mysql.clone();
assertEquals(mysql.hashCode(), cloned.hashCode());
assertTrue(mysql.equals(cloned));
}
@Test
public void testNotEquals() throws CloneNotSupportedException {
assertFalse(mysql.equals(new Tcp()));
Mysql cloned = mysql.clone();
cloned.setUser("aaa");
assertFalse(mysql.equals(cloned));
cloned = mysql.clone();
cloned.setPwd("aaa");
assertFalse(mysql.equals(cloned));
cloned = mysql.clone();
cloned.setCmd("aaa");
assertFalse(mysql.equals(cloned));
}
} }

View File

@ -14,26 +14,20 @@
* limitations under the License. * limitations under the License.
*/ */
package com.alibaba.nacos.naming.core.v2.upgrade; package com.alibaba.nacos.api.naming.pojo.healthcheck.impl;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
/** import static org.junit.Assert.assertEquals;
* {@link UpgradeStates} unit tests. import static org.junit.Assert.assertTrue;
*
* @author chenglu
* @date 2021-09-01 22:04
*/
public class UpgradeStatesTest {
private UpgradeStates upgradeStates = new UpgradeStates(); public class TcpTest {
@Test @Test
public void testOnEvent() { public void testClone() throws CloneNotSupportedException {
UpgradeStates.UpgradeStateChangedEvent changedEvent = new UpgradeStates.UpgradeStateChangedEvent(true); Tcp original = new Tcp();
upgradeStates.onEvent(changedEvent); Tcp cloned = original.clone();
assertEquals(original.hashCode(), cloned.hashCode());
Assert.assertTrue(upgradeStates.isUpgraded()); assertTrue(original.equals(cloned));
} }
} }

View File

@ -0,0 +1,64 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public abstract class BasedNamingRequestTest {
protected static final String SERVICE = "service";
protected static final String GROUP = "group";
protected static final String NAMESPACE = "namespace";
protected static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
protected void injectNamingRequestBasedInfo(AbstractNamingRequest request) {
request.setServiceName(SERVICE);
request.setGroupName(GROUP);
request.setNamespace(NAMESPACE);
}
protected void checkNamingRequestBasedInfo(AbstractNamingRequest request) {
assertEquals(SERVICE, request.getServiceName());
assertEquals(GROUP, request.getGroupName());
assertEquals(NAMESPACE, request.getNamespace());
assertEquals(NAMING_MODULE, request.getModule());
}
protected void checkSerializeBasedInfo(String json) {
assertTrue(json.contains("\"serviceName\":\"" + SERVICE + "\""));
assertTrue(json.contains("\"groupName\":\"" + GROUP + "\""));
assertTrue(json.contains("\"namespace\":\"" + NAMESPACE + "\""));
assertTrue(json.contains("\"module\":\"" + NAMING_MODULE + "\""));
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BatchInstanceRequestTest extends BasedNamingRequestTest {
@Test
public void testSerialize() throws JsonProcessingException {
BatchInstanceRequest request = new BatchInstanceRequest(NAMESPACE, SERVICE, GROUP,
NamingRemoteConstants.BATCH_REGISTER_INSTANCE, Collections.singletonList(new Instance()));
String json = mapper.writeValueAsString(request);
checkSerializeBasedInfo(json);
assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.BATCH_REGISTER_INSTANCE + "\""));
assertTrue(json.contains("\"instances\":[{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"type\":\"batchRegisterInstance\",\"instances\":[{\"port\":0,\"weight\":1.0,\"healthy\":true,"
+ "\"enabled\":true,\"ephemeral\":true,\"metadata\":{},\"instanceIdGenerator\":\"simple\","
+ "\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000}],"
+ "\"module\":\"naming\"}";
BatchInstanceRequest actual = mapper.readValue(json, BatchInstanceRequest.class);
checkNamingRequestBasedInfo(actual);
assertEquals(NamingRemoteConstants.BATCH_REGISTER_INSTANCE, actual.getType());
assertEquals(1, actual.getInstances().size());
assertEquals(new Instance(), actual.getInstances().get(0));
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class InstanceRequestTest extends BasedNamingRequestTest {
@Test
public void testSerialize() throws JsonProcessingException {
InstanceRequest request = new InstanceRequest(NAMESPACE, SERVICE, GROUP,
NamingRemoteConstants.REGISTER_INSTANCE, new Instance());
String json = mapper.writeValueAsString(request);
checkSerializeBasedInfo(json);
assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.REGISTER_INSTANCE + "\""));
assertTrue(json.contains("\"instance\":{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"type\":\"deregisterInstance\",\"instance\":{\"port\":0,\"weight\":1.0,\"healthy\":true,"
+ "\"enabled\":true,\"ephemeral\":true,\"metadata\":{},\"instanceIdGenerator\":\"simple\","
+ "\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000},"
+ "\"module\":\"naming\"}";
InstanceRequest actual = mapper.readValue(json, InstanceRequest.class);
checkNamingRequestBasedInfo(actual);
assertEquals(NamingRemoteConstants.DE_REGISTER_INSTANCE, actual.getType());
assertEquals(new Instance(), actual.getInstance());
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class NotifySubscriberRequestTest {
private static final String SERVICE = "service";
private static final String GROUP = "group";
private static final String NAMESPACE = "namespace";
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
ServiceInfo serviceInfo = new ServiceInfo(GROUP + "@@" + SERVICE);
NotifySubscriberRequest request = NotifySubscriberRequest.buildNotifySubscriberRequest(serviceInfo);
request.setServiceName(SERVICE);
request.setGroupName(GROUP);
request.setNamespace(NAMESPACE);
String json = mapper.writeValueAsString(request);
checkSerializeBasedInfo(json);
assertTrue(json.contains("\"serviceInfo\":{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"serviceInfo\":{\"name\":\"service\",\"groupName\":\"group\",\"cacheMillis\":1000,\"hosts\":[],"
+ "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false,"
+ "\"valid\":true},\"module\":\"naming\"}";
NotifySubscriberRequest actual = mapper.readValue(json, NotifySubscriberRequest.class);
checkRequestBasedInfo(actual);
assertEquals(GROUP + "@@" + SERVICE, actual.getServiceInfo().getKey());
}
private void checkRequestBasedInfo(NotifySubscriberRequest request) {
assertEquals(SERVICE, request.getServiceName());
assertEquals(GROUP, request.getGroupName());
assertEquals(NAMESPACE, request.getNamespace());
assertEquals(NAMING_MODULE, request.getModule());
}
private void checkSerializeBasedInfo(String json) {
assertTrue(json.contains("\"serviceName\":\"" + SERVICE + "\""));
assertTrue(json.contains("\"groupName\":\"" + GROUP + "\""));
assertTrue(json.contains("\"namespace\":\"" + NAMESPACE + "\""));
assertTrue(json.contains("\"module\":\"" + NAMING_MODULE + "\""));
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ServiceListRequestTest extends BasedNamingRequestTest {
@Test
public void testSerialize() throws JsonProcessingException {
ServiceListRequest request = new ServiceListRequest(NAMESPACE, GROUP, 1, 10);
request.setSelector("label");
String json = mapper.writeValueAsString(request);
assertTrue(json.contains("\"groupName\":\"" + GROUP + "\""));
assertTrue(json.contains("\"namespace\":\"" + NAMESPACE + "\""));
assertTrue(json.contains("\"module\":\"" + NAMING_MODULE + "\""));
assertTrue(json.contains("\"selector\":\"label\""));
assertTrue(json.contains("\"pageNo\":1"));
assertTrue(json.contains("\"pageSize\":10"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"\",\"groupName\":\"group\","
+ "\"pageNo\":1,\"pageSize\":10,\"selector\":\"label\",\"module\":\"naming\"}";
ServiceListRequest actual = mapper.readValue(json, ServiceListRequest.class);
assertEquals(GROUP, actual.getGroupName());
assertEquals(NAMESPACE, actual.getNamespace());
assertEquals(NAMING_MODULE, actual.getModule());
assertEquals(1, actual.getPageNo());
assertEquals(10, actual.getPageSize());
assertEquals("label", actual.getSelector());
}
}

Some files were not shown because too many files have changed in this diff Show More