diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 193c8b69c4f4..b2005c647e31 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -396,10 +396,10 @@ # ServiceOwners: @raedJarrar @jifems # PRLabel: %DevCenter -/sdk/devcenter/ @sebrenna @mharlan +/sdk/devcenter/ @sebrenna # ServiceLabel: %DevCenter -# ServiceOwners: @sebrenna @mharlan +# ServiceOwners: @sebrenna # ServiceLabel: %Device Provisioning Service # ServiceOwners: @nberdy @@ -430,7 +430,7 @@ # ServiceLabel: %Event Grid # AzureSdkOwners: @billwert -# ServiceOwners: @jfggdl +# ServiceOwners: @Kishp01 @ahamad-MS # PRLabel: %Event Hubs /sdk/eventhubs/ @conniey @anuchandy @lmolkova @@ -558,7 +558,7 @@ # ServiceOwners: @ambhatna @savjani # PRLabel: %OpenTelemetry -/sdk/monitor/azure-monitor-opentelemetry-exporter/ @trask @ramthi @heyams @jeanbisutti +/sdk/monitor/azure-monitor-opentelemetry-exporter/ @trask @ramthi @heyams @jeanbisutti @harsimar # ServiceLabel: %Network # ServiceOwners: @aznetsuppgithub @@ -647,9 +647,6 @@ # ServiceLabel: %Redis Cache # ServiceOwners: @yegu-ms -# ServiceLabel: %Relay -# ServiceOwners: @jfggdl - # PRLabel: %Remote Rendering /sdk/remoterendering/ @MichaelZp0 @ChristopherManthei @@ -796,13 +793,13 @@ /sdk/spring-experimental/ @chenrujun @netyyyy @saragluna @moarychan # PRLabel: %Monitor - Spring -/sdk/spring/spring-cloud-azure-starter-monitor @jeanbisutti @trask @ramthi @heyams +/sdk/spring/spring-cloud-azure-starter-monitor @jeanbisutti @trask @ramthi @heyams @harsimar # PRLabel: %Monitor - Spring -/sdk/spring/spring-cloud-azure-starter-monitor-test @jeanbisutti @trask @ramthi @heyams +/sdk/spring/spring-cloud-azure-starter-monitor-test @jeanbisutti @trask @ramthi @heyams @harsimar # ServiceLabel: %Monitor - Spring -# AzureSdkOwners: @jeanbisutti @trask @ramthi @heyams +# AzureSdkOwners: @jeanbisutti @trask @ramthi @heyams @harsimar # PRLabel: %azure-spring /sdk/spring/spring-cloud-azure-appconfiguration-config*/ @mrm9084 @chenrujun @netyyyy @saragluna @moarychan @@ -853,3 +850,4 @@ # Add owners for notifications for specific pipelines /eng/pipelines/aggregate-reports.yml @joshfree @jonathangiles +/eng/common/pipelines/codeowners-linter.yml @alzimmermsft @srnagar @lmolkova diff --git a/.github/CODEOWNERS_baseline_errors.txt b/.github/CODEOWNERS_baseline_errors.txt index e0dbd7daa065..faf15e0ee168 100644 --- a/.github/CODEOWNERS_baseline_errors.txt +++ b/.github/CODEOWNERS_baseline_errors.txt @@ -267,3 +267,8 @@ ccmixpdevs is an invalid user. Ensure the user exists, is public member of Azure ccmbpxpcrew is an invalid user. Ensure the user exists, is public member of Azure and has write permissions. TiagoCrewGitHubIssues is an invalid user. Ensure the user exists, is public member of Azure and has write permissions. ccmshowbackdevs is an invalid user. Ensure the user exists, is public member of Azure and has write permissions. +sagivf is not a public member of Azure. +Aviv-Yaniv is not a public member of Azure. +tmahmood-microsoft is not a public member of Azure. +Kishp01 is not a public member of Azure. +ahamad-MS is an invalid user. Ensure the user exists, is public member of Azure and has write permissions. \ No newline at end of file diff --git a/eng/emitter-package-lock.json b/eng/emitter-package-lock.json index d74bddeb2891..7d1f72e79429 100644 --- a/eng/emitter-package-lock.json +++ b/eng/emitter-package-lock.json @@ -5,13 +5,13 @@ "packages": { "": { "dependencies": { - "@azure-tools/typespec-java": "0.15.14" + "@azure-tools/typespec-java": "0.15.15" }, "devDependencies": { "@azure-tools/typespec-autorest": "0.41.1", "@azure-tools/typespec-azure-core": "0.41.0", "@azure-tools/typespec-azure-resource-manager": "0.41.0", - "@azure-tools/typespec-client-generator-core": "0.41.6", + "@azure-tools/typespec-client-generator-core": "0.41.8", "@typespec/compiler": "0.55.0", "@typespec/http": "0.55.0", "@typespec/openapi": "0.55.0", @@ -114,9 +114,9 @@ } }, "node_modules/@azure-tools/typespec-client-generator-core": { - "version": "0.41.6", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.41.6.tgz", - "integrity": "sha512-pEv0LQb415QioO6hsYYXWwmsG6Ka3J7SRUgf5zlA6/m6inc8OR1MwFGHdTTjzbp3jG0GDr1C/T7jF1Jy+edyfw==", + "version": "0.41.8", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.41.8.tgz", + "integrity": "sha512-d72LPwkEio/swqyAAgcuOaw+K4ghSbZcRjpjsvddxHWHh25ZukjD2hU/BfCtidnKptgKjs79fV++w2MYE6sTyw==", "dependencies": { "change-case": "~5.4.4", "pluralize": "^8.0.0" @@ -133,9 +133,9 @@ } }, "node_modules/@azure-tools/typespec-java": { - "version": "0.15.14", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-java/-/typespec-java-0.15.14.tgz", - "integrity": "sha512-Cpa92KG09UMAq76oM21x/PswYSjuE3LMLtqYv21JEz30TcjaL0/KVtVum2hKzK9s2/eZzY70acaMNkuDQyQVBw==", + "version": "0.15.15", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-java/-/typespec-java-0.15.15.tgz", + "integrity": "sha512-46zyPBkDF5NEbL4DEwDt/WiiQgTvsLI1CtiYD5Cfjt+stbmSNVb77urcxlzqgEbQiFPCV6UJWGnuu09ilYT/Dw==", "dependencies": { "@autorest/codemodel": "~4.20.0", "js-yaml": "~4.1.0", @@ -167,19 +167,19 @@ } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", - "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "version": "7.24.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.5.tgz", + "integrity": "sha512-3q93SSKX2TWCG30M2G2kwaKeTYgEUp5Snjuj8qm729SObL6nbtUldAi37qbxkD5gg3xnBio+f9nqpSepGZMvxA==", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/highlight": { - "version": "7.24.2", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.2.tgz", - "integrity": "sha512-Yac1ao4flkTxTteCDZLEvdxg2fZfz1v8M4QpaGypq/WPDqg3ijHYbDfs+LG5hvzSoqaSZ9/Z9lKSP3CjZjv+pA==", + "version": "7.24.5", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.5.tgz", + "integrity": "sha512-8lLmua6AVh/8SLJRRVD6V8p73Hir9w5mJrhE+IPpILG31KKlI9iz5zmBYKcWPS59qSfgP9RaSBQSHHE81WKuEw==", "dependencies": { - "@babel/helper-validator-identifier": "^7.22.20", + "@babel/helper-validator-identifier": "^7.24.5", "chalk": "^2.4.2", "js-tokens": "^4.0.0", "picocolors": "^1.0.0" @@ -973,9 +973,9 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/yaml": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.4.1.tgz", - "integrity": "sha512-pIXzoImaqmfOrL7teGUBt/T7ZDnyeGBWyXQBvOVhLkWLN37GXv8NMLK406UY6dS51JfcQHsmcW5cJ441bHg6Lg==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.4.2.tgz", + "integrity": "sha512-B3VqDZ+JAg1nZpaEmWtTXUlBneoGx6CPM9b0TENK6aoSu5t73dItudwdgmi6tHlIZZId4dZ9skcAQ2UbcyAeVA==", "bin": { "yaml": "bin.mjs" }, diff --git a/eng/emitter-package.json b/eng/emitter-package.json index 15fe2aad5a8e..d566172a15d6 100644 --- a/eng/emitter-package.json +++ b/eng/emitter-package.json @@ -1,16 +1,16 @@ { "main": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-java": "0.15.14" + "@azure-tools/typespec-java": "0.15.15" }, "devDependencies": { - "@typespec/versioning": "0.55.0", - "@azure-tools/typespec-client-generator-core": "0.41.6", - "@typespec/http": "0.55.0", - "@typespec/openapi": "0.55.0", + "@azure-tools/typespec-client-generator-core": "0.41.8", "@typespec/rest": "0.55.0", "@typespec/compiler": "0.55.0", + "@typespec/openapi": "0.55.0", "@azure-tools/typespec-azure-core": "0.41.0", + "@typespec/versioning": "0.55.0", + "@typespec/http": "0.55.0", "@azure-tools/typespec-azure-resource-manager": "0.41.0", "@azure-tools/typespec-autorest": "0.41.1" } diff --git a/eng/mgmt/automation/changelog.py b/eng/mgmt/automation/changelog.py index fd62451eae7e..72f7a5767305 100755 --- a/eng/mgmt/automation/changelog.py +++ b/eng/mgmt/automation/changelog.py @@ -9,7 +9,7 @@ from parameters import * from generate import update_parameters from generate_utils import get_version -from generate import compile_package +from generate_utils import compile_arm_package from generate import compare_with_maven_package os.chdir(pwd) @@ -31,7 +31,7 @@ def main(): update_parameters(args.get('suffix')) if args.get('compile'): - compile_package(sdk_root, service) + compile_arm_package(sdk_root, service) versions = get_version(sdk_root, service).split(';') stable_version = versions[1] diff --git a/eng/mgmt/automation/generate.py b/eng/mgmt/automation/generate.py index da692c27e539..1c56b9e154b7 100755 --- a/eng/mgmt/automation/generate.py +++ b/eng/mgmt/automation/generate.py @@ -24,7 +24,7 @@ ) from generate_utils import ( compare_with_maven_package, - compile_package, + compile_arm_package, generate, get_and_update_service_from_api_specs, get_suffix_from_api_specs, @@ -187,7 +187,7 @@ def sdk_automation_autorest(config: dict) -> List[dict]: tag=tag, ) if succeeded: - compile_package(sdk_root, module) + compile_arm_package(sdk_root, module) packages.append({ 'packageName': @@ -256,7 +256,7 @@ def sdk_automation_typespec_project(tsp_project: str, config: dict) -> dict: update_root_pom(sdk_root, service) # compile - succeeded = compile_package(sdk_root, module) + succeeded = compile_arm_package(sdk_root, module) # output if sdk_folder and module and service: @@ -359,7 +359,7 @@ def main(): ) if succeeded: - succeeded = compile_package(sdk_root, module) + succeeded = compile_arm_package(sdk_root, module) if succeeded: compare_with_maven_package(sdk_root, service, stable_version, current_version, module) diff --git a/eng/mgmt/automation/generate_data.py b/eng/mgmt/automation/generate_data.py index aee8301e8d57..fa885c58a0e9 100755 --- a/eng/mgmt/automation/generate_data.py +++ b/eng/mgmt/automation/generate_data.py @@ -335,7 +335,11 @@ def compile_package(sdk_root: str, group_id: str, module: str) -> bool: sdk_root, group_id, module) logging.info(command) if os.system(command) != 0: - logging.error('[COMPILE] Maven build fail') + error_message = ('[COMPILE] Maven build fail.\n' + 'One reason of the compilation failure is that the existing code customization in SDK repository being incompatible with the class generated from updated TypeSpec source. In such case, you can ignore the failure, and fix the customization in SDK repository.\n' + 'You can inquire in "Language - Java" Teams channel. Please include the link of this Pull Request in the query.') + logging.error(error_message) + print(error_message, file=sys.stderr) return False return True diff --git a/eng/mgmt/automation/generate_utils.py b/eng/mgmt/automation/generate_utils.py index 8194eae9be2b..422db00d3471 100644 --- a/eng/mgmt/automation/generate_utils.py +++ b/eng/mgmt/automation/generate_utils.py @@ -95,7 +95,7 @@ def generate( return True -def compile_package(sdk_root, module) -> bool: +def compile_arm_package(sdk_root: str, module: str) -> bool: if os.system( 'mvn --no-transfer-progress clean verify -f {0}/pom.xml -Dmaven.javadoc.skip -Dgpg.skip -DskipTestCompile -Djacoco.skip -Drevapi.skip -pl {1}:{2} -am'.format( sdk_root, GROUP_ID, module)) != 0: diff --git a/eng/mgmt/automation/generation.yml b/eng/mgmt/automation/generation.yml index d1423af5d341..ef7306beaa24 100644 --- a/eng/mgmt/automation/generation.yml +++ b/eng/mgmt/automation/generation.yml @@ -12,7 +12,9 @@ variables: - name: MAVEN_OPTS value: '-Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' - name: NodeVersion - value: '16.x' + value: '18.x' +- name: fromTypeSpec + value: $[ne(variables['TSP_CONFIG'], '')] steps: - bash: | @@ -29,6 +31,12 @@ steps: - bash: | npm install -g autorest displayName: 'Install autorest' + condition: eq(variables.fromTypeSpec, false) + +- bash: | + npm install -g @azure-tools/typespec-client-generator-cli + displayName: 'Install tsp-client' + condition: eq(variables.fromTypeSpec, true) # - template: /eng/common/testproxy/test-proxy-tool.yml # parameters: @@ -38,13 +46,27 @@ steps: - bash: | export PATH=$JAVA_HOME_11_X64/bin:$PATH java -version + set -x + ./eng/mgmt/automation/generate.py --tsp-config "$(TSP_CONFIG)" --version "$(VERSION)" --auto-commit-external-change --user-name "azure-sdk" --user-email "azuresdk@microsoft.com" + displayName: Generation from TypeSpec + condition: eq(variables.fromTypeSpec, true) + +- bash: | + export PATH=$JAVA_HOME_11_X64/bin:$PATH + java -version + set -x ./eng/mgmt/automation/generate.py --readme "$(README)" --tag "$(TAG)" --autorest-options="$(AUTOREST_OPTIONS)" --service "$(SERVICE)" --version "$(VERSION)" --suffix "$(SUFFIX)" --auto-commit-external-change --user-name "azure-sdk" --user-email "azuresdk@microsoft.com" - displayName: Generation + displayName: Generation from Swagger + condition: eq(variables.fromTypeSpec, false) - template: /eng/common/pipelines/templates/steps/create-pull-request.yml parameters: PRBranchName: fluent-lite-generation-$(Build.BuildId) - CommitMsg: '[Automation] Generate Fluent Lite from $(README)#$(TAG)' - PRTitle: '[Automation] Generate Fluent Lite from $(README)#$(TAG)' + ${{ if variables.fromTypeSpec }}: + CommitMsg: '[Automation] Generate Fluent Lite from TypeSpec $(README)' + PRTitle: '[Automation] Generate Fluent Lite from TypeSpec $(README)' + ${{ else }}: + CommitMsg: '[Automation] Generate Fluent Lite from Swagger $(README)#$(TAG)' + PRTitle: '[Automation] Generate Fluent Lite from Swagger $(README)#$(TAG)' PRLabels: 'Mgmt - Track 2' OpenAsDraft: '$(DRAFT_PULL_REQUEST)' diff --git a/eng/mgmt/automation/generation_data.yml b/eng/mgmt/automation/generation_data.yml index 55378d235324..7cacdc1877c9 100644 --- a/eng/mgmt/automation/generation_data.yml +++ b/eng/mgmt/automation/generation_data.yml @@ -12,7 +12,7 @@ variables: - name: MAVEN_OPTS value: '-Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' - name: NodeVersion - value: '16.x' + value: '18.x' steps: - bash: | diff --git a/eng/mgmt/automation/parameters.py b/eng/mgmt/automation/parameters.py index 158efbd6c896..85fe90bc5d0a 100644 --- a/eng/mgmt/automation/parameters.py +++ b/eng/mgmt/automation/parameters.py @@ -16,7 +16,7 @@ SDK_ROOT = '../../../' # related to file dir AUTOREST_CORE_VERSION = '3.9.7' -AUTOREST_JAVA = '@autorest/java@4.1.28' +AUTOREST_JAVA = '@autorest/java@4.1.29' DEFAULT_VERSION = '1.0.0-beta.1' GROUP_ID = 'com.azure.resourcemanager' API_SPECS_FILE = 'api-specs.yaml' diff --git a/eng/mgmt/automation/sdk_generate.py b/eng/mgmt/automation/sdk_generate.py index e6ffeaceeccc..d1d1e9a0a51e 100755 --- a/eng/mgmt/automation/sdk_generate.py +++ b/eng/mgmt/automation/sdk_generate.py @@ -20,7 +20,7 @@ ) from generate_utils import ( compare_with_maven_package, - compile_package, + compile_arm_package, generate, get_and_update_service_from_api_specs, get_suffix_from_api_specs, @@ -215,7 +215,7 @@ def sdk_automation_autorest(config: dict) -> List[dict]: tag = tag, ) if succeeded: - compile_package(sdk_root, module) + compile_arm_package(sdk_root, module) packages.append({ 'packageName': @@ -294,7 +294,7 @@ def main(): ) if succeeded: - succeeded = compile_package(sdk_root, module) + succeeded = compile_arm_package(sdk_root, module) if succeeded: compare_with_maven_package(sdk_root, service, stable_version, current_version, module) diff --git a/eng/pipelines/docindex.yml b/eng/pipelines/docindex.yml index 0cb3f6205908..c128f858955d 100644 --- a/eng/pipelines/docindex.yml +++ b/eng/pipelines/docindex.yml @@ -13,7 +13,6 @@ jobs: DailyDocRepoLocation: $(Pipeline.Workspace)/daily DocRepoOwner: Azure DocRepoName: azure-docs-sdk-java - DocValidationImageId: azuresdkimages.azurecr.io/javarefautocr:latest steps: # Sync docs repo onboarding files/folders - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml @@ -29,10 +28,6 @@ jobs: WorkingDirectory: $(DocRepoLocation) - Name: azure-sdk/$(DocRepoName) WorkingDirectory: $(DailyDocRepoLocation) - # Pull and build the docker image. - - template: /eng/common/pipelines/templates/steps/docker-pull-image.yml - parameters: - ImageId: "$(DocValidationImageId)" - task: Powershell@2 inputs: @@ -46,7 +41,7 @@ jobs: inputs: pwsh: true filePath: eng/common/scripts/Update-DocsMsPackages.ps1 - arguments: -DocRepoLocation $(DocRepoLocation) -ImageId '$(DocValidationImageId)' + arguments: -DocRepoLocation $(DocRepoLocation) displayName: Update Docs Onboarding for main branch condition: and(succeeded(), or(eq(variables['Build.Reason'], 'Schedule'), eq(variables['Force.MainUpdate'], 'true'))) @@ -85,7 +80,7 @@ jobs: parameters: BaseRepoBranch: $(DefaultBranch) BaseRepoOwner: $(DocRepoOwner) - CommitMsg: "Update docs CI configuration" + CommitMsg: "Update docs CI configuration Build: $(System.CollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)" TargetRepoName: $(DocRepoName) TargetRepoOwner: $(DocRepoOwner) WorkingDirectory: $(DocRepoLocation) @@ -95,20 +90,7 @@ jobs: parameters: DailyBranchVariableName: DailyDocsBranchName - # Docs daily updates is supposed to download packages from public feed repository, so we have to specify additional repositories in a POM or the profile. - # Here is maven documentation: https://maven.apache.org/guides/mini/guide-multiple-repositories.html - - powershell: | - # Linux mvn `setting.xml` is sitting under path `~/.m2/setting.xml` - Get-Command mvn - if (!(Test-Path '~/.m2/')) { - mkdir ~/.m2/ - } - if (Test-Path '~/.m2/setting.xml') { - Write-Host "'setting.xml' exists. Overwriting the file to support multiple repositories." - } - Copy-Item "./eng/repo-docs/docms/daily.update.setting.xml" -Destination "~/.m2/settings.xml" - displayName: 'Configure mvn' - workingDirectory: $(Build.SourcesDirectory) + - template: /eng/pipelines/templates/steps/mvn-linux-settings-for-docs.yml - task: Powershell@2 inputs: diff --git a/eng/pipelines/templates/stages/1es-redirect.yml b/eng/pipelines/templates/stages/1es-redirect.yml index d97a6c8e6fec..0cad046eea7a 100644 --- a/eng/pipelines/templates/stages/1es-redirect.yml +++ b/eng/pipelines/templates/stages/1es-redirect.yml @@ -11,7 +11,7 @@ resources: - repository: azure-sdk-build-tools type: git name: internal/azure-sdk-build-tools - ref: refs/tags/azure-sdk-build-tools_20240320.1 + ref: refs/tags/azure-sdk-build-tools_20240507.1 parameters: - name: stages diff --git a/eng/pipelines/templates/stages/archetype-java-release-batch.yml b/eng/pipelines/templates/stages/archetype-java-release-batch.yml index 24a2d7c7e723..7b0cf0945427 100644 --- a/eng/pipelines/templates/stages/archetype-java-release-batch.yml +++ b/eng/pipelines/templates/stages/archetype-java-release-batch.yml @@ -319,10 +319,6 @@ stages: image: azsdk-pool-mms-ubuntu-2004-1espt os: linux - variables: - - name: DocValidationImageId - value: azuresdkimages.azurecr.io/javarefautocr:latest - strategy: runOnce: deploy: @@ -341,6 +337,8 @@ stages: - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml + - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml + - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml parameters: PackageInfoLocations: @@ -354,7 +352,6 @@ stages: SparseCheckoutPaths: - docs-ref-services/ - metadata/ - DocValidationImageId: "$(DocValidationImageId)" - deployment: PublishDocs displayName: Publish Docs to GitHubIO Blob Storage @@ -464,9 +461,6 @@ stages: name: azsdk-pool-mms-ubuntu-2004-general image: azsdk-pool-mms-ubuntu-2004-1espt os: linux - variables: - - name: DocValidationImageId - value: azuresdkimages.azurecr.io/javarefautocr:latest steps: - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml parameters: @@ -485,6 +479,8 @@ stages: - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml + - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml + - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml parameters: PackageInfoLocations: @@ -499,6 +495,5 @@ stages: SparseCheckoutPaths: - docs-ref-services/ - metadata/ - DocValidationImageId: "$(DocValidationImageId)" - template: /eng/common/pipelines/templates/steps/docsms-ensure-validation.yml diff --git a/eng/pipelines/templates/stages/archetype-java-release-patch.yml b/eng/pipelines/templates/stages/archetype-java-release-patch.yml index 50e817b937fd..c22cff36f32c 100644 --- a/eng/pipelines/templates/stages/archetype-java-release-patch.yml +++ b/eng/pipelines/templates/stages/archetype-java-release-patch.yml @@ -239,8 +239,6 @@ stages: variables: - template: /eng/pipelines/templates/variables/globals.yml - - name: DocValidationImageId - value: azuresdkimages.azurecr.io/javarefautocr:latest strategy: runOnce: @@ -261,6 +259,8 @@ stages: - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml + - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml + - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml parameters: PackageInfoLocations: @@ -274,7 +274,6 @@ stages: SparseCheckoutPaths: - docs-ref-services/ - metadata/ - DocValidationImageId: "$(DocValidationImageId)" - deployment: PublishDocs displayName: Publish Docs to GitHubIO Blob Storage diff --git a/eng/pipelines/templates/stages/archetype-java-release.yml b/eng/pipelines/templates/stages/archetype-java-release.yml index bcb7e5c37892..6d689be35605 100644 --- a/eng/pipelines/templates/stages/archetype-java-release.yml +++ b/eng/pipelines/templates/stages/archetype-java-release.yml @@ -257,8 +257,6 @@ stages: variables: - template: /eng/pipelines/templates/variables/globals.yml - - name: DocValidationImageId - value: azuresdkimages.azurecr.io/javarefautocr:latest strategy: runOnce: @@ -275,10 +273,11 @@ stages: - download: current displayName: 'Download Artifact: ${{parameters.ArtifactName}}' artifact: ${{parameters.ArtifactName}} - # Pull and build the docker image. - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml + - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml + - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml parameters: PackageInfoLocations: @@ -290,7 +289,6 @@ stages: SparseCheckoutPaths: - docs-ref-services/ - metadata/ - DocValidationImageId: "$(DocValidationImageId)" - ${{if ne(artifact.skipPublishDocGithubIo, 'true')}}: - deployment: PublishDocs @@ -446,8 +444,6 @@ stages: os: linux variables: - template: /eng/pipelines/templates/variables/globals.yml - - name: DocValidationImageId - value: azuresdkimages.azurecr.io/javarefautocr:latest steps: - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml parameters: @@ -466,6 +462,8 @@ stages: - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml + - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml + - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml parameters: PackageInfoLocations: @@ -480,6 +478,5 @@ stages: SparseCheckoutPaths: - docs-ref-services/ - metadata/ - DocValidationImageId: "$(DocValidationImageId)" - template: /eng/common/pipelines/templates/steps/docsms-ensure-validation.yml diff --git a/eng/pipelines/templates/steps/install-rex-validation-tool.yml b/eng/pipelines/templates/steps/install-rex-validation-tool.yml new file mode 100644 index 000000000000..904e04402123 --- /dev/null +++ b/eng/pipelines/templates/steps/install-rex-validation-tool.yml @@ -0,0 +1,22 @@ +steps: + # Create a java2docfx subdirectory in the $(Build.BinariesDirectory) and install the java2docfx there + # This way, the jar file is in its own subdirectory and isolated. + - pwsh: | + $java2docfxVer = Get-Content eng/scripts/docs/java2docfx.version.txt + $java2docfxDir = Join-Path $(Build.BinariesDirectory) "java2docfx" + New-Item $java2docfxDir -ItemType Directory | Out-Null + $originLocation = Get-Location + try { + # Set the location into the created java2docfx directory . Running mvn from the repository root + # picks up the root POM and processes that while doing the dependency:copy in spite of + # the fact it has nothing to do with this download. + Set-Location $java2docfxDir + Write-Host "mvn dependency:copy -Dartifact=""com.microsoft:java2docfx:$java2docfxVer"" -DoutputDirectory=""$java2docfxDir""" + mvn dependency:copy -Dartifact="com.microsoft:java2docfx:$java2docfxVer" -DoutputDirectory="$java2docfxDir" + $java2docfxJarLoc = Join-Path $java2docfxDir -ChildPath "java2docfx-$java2docfxVer.jar" + Write-Host "Testing the install, running java -jar $java2docfxJarLoc -h" + java -jar $java2docfxJarLoc -h + } finally { + Set-Location $originLocation + } + displayName: Install java2docfx for package validation \ No newline at end of file diff --git a/eng/pipelines/templates/steps/java-publishing.yml b/eng/pipelines/templates/steps/java-publishing.yml index 6f8aeecf8156..016495e8e130 100644 --- a/eng/pipelines/templates/steps/java-publishing.yml +++ b/eng/pipelines/templates/steps/java-publishing.yml @@ -107,10 +107,14 @@ steps: -Path ${{ parameters.OutputDirectory }} -InformationAction Continue - ${{if and(eq(parameters.ShouldPublish, 'true'), ne(parameters.StageOnly, 'true'))}}: - - task: EsrpRelease@4 + - task: EsrpRelease@7 displayName: 'Publish to ESRP' inputs: - ConnectedServiceName: 'ESRP Release Service' + ConnectedServiceName: 'Azure SDK Engineering System' + ClientId: '5f81938c-2544-4f1f-9251-dd9de5b8a81b' + KeyVaultName: 'AzureSDKEngKeyVault' + AuthCertName: 'azure-sdk-esrp-release-auth-certificate' + SignCertName: 'azure-sdk-esrp-release-sign-certificate' Intent: 'PackageDistribution' ContentType: 'Maven' FolderLocation: ${{ parameters.OutputDirectory }} diff --git a/eng/repo-docs/docms/daily.update.setting.xml b/eng/repo-docs/docms/daily.update.setting.xml index fc1b359a3a62..f30128b6d146 100644 --- a/eng/repo-docs/docms/daily.update.setting.xml +++ b/eng/repo-docs/docms/daily.update.setting.xml @@ -18,6 +18,16 @@ true + + docs-public-packages + https://docfx.pkgs.visualstudio.com/docfx/_packaging/docs-public-packages/maven/v1 + + true + + + true + + diff --git a/eng/scripts/Language-Settings.ps1 b/eng/scripts/Language-Settings.ps1 index 27cfa73218be..dfbd0f1ba16c 100644 --- a/eng/scripts/Language-Settings.ps1 +++ b/eng/scripts/Language-Settings.ps1 @@ -163,7 +163,11 @@ function Get-java-DocsMsDevLanguageSpecificPackageInfo($packageInfo, $packageSou # through the javadoc, like track 1 libraries whose javadoc.jar files don't contain anything, in # the metadata json files. if ($namespaces.Count -gt 0) { + Write-Host "Get-java-DocsMsDevLanguageSpecificPackageInfo:adding namespaces property with the following namespaces:" + $namespaces | Write-Host $packageInfo | Add-Member -Type NoteProperty -Name "Namespaces" -Value $namespaces + } else { + Write-Host "Get-java-DocsMsDevLanguageSpecificPackageInfo: no namespaces to add" } } return $packageInfo @@ -262,412 +266,6 @@ function Get-java-GithubIoDocIndex() GenerateDocfxTocContent -tocContent $tocContent -lang "Java" -campaignId "UA-62780441-42" } -# a "package.json configures target packages for all the monikers in a Repository, it also has a slightly different -# schema than the moniker-specific json config that is seen in python and js -function Update-java-CIConfig($pkgs, $ciRepo, $locationInDocRepo, $monikerId=$null) -{ - $pkgJsonLoc = (Join-Path -Path $ciRepo -ChildPath $locationInDocRepo) - - if (-not (Test-Path $pkgJsonLoc)) { - Write-Error "Unable to locate package json at location $pkgJsonLoc, exiting." - exit(1) - } - - $allJsonData = Get-Content $pkgJsonLoc | ConvertFrom-Json - - $visibleInCI = @{} - - for ($i=0; $i -lt $allJsonData[$monikerId].packages.Length; $i++) { - $pkgDef = $allJsonData[$monikerId].packages[$i] - $visibleInCI[$pkgDef.packageArtifactId] = $i - } - - foreach ($releasingPkg in $pkgs) { - if ($visibleInCI.ContainsKey($releasingPkg.PackageId)) { - $packagesIndex = $visibleInCI[$releasingPkg.PackageId] - $existingPackageDef = $allJsonData[$monikerId].packages[$packagesIndex] - $existingPackageDef.packageVersion = $releasingPkg.PackageVersion - } - else { - $newItem = New-Object PSObject -Property @{ - packageDownloadUrl = $PackageRepositoryUri - packageGroupId = $releasingPkg.GroupId - packageArtifactId = $releasingPkg.PackageId - packageVersion = $releasingPkg.PackageVersion - inputPath = @() - excludePath = @() - } - - $allJsonData[$monikerId].packages += $newItem - } - } - - $jsonContent = $allJsonData | ConvertTo-Json -Depth 10 | % {$_ -replace "(?m) (?<=^(?: )*)", " " } - - Set-Content -Path $pkgJsonLoc -Value $jsonContent -} - -$PackageExclusions = @{ - "azure-core-experimental" = "Don't want to include an experimental package."; - "azure-core-test" = "Don't want to include the test framework package."; - "azure-sdk-bom" = "Don't want to include the sdk bom."; - "azure-storage-internal-avro" = "No external APIs."; - "azure-cosmos-spark_3-1_2-12" = "Javadoc dependency issue."; - "azure-cosmos-spark_3-2_2-12" = "Javadoc dependency issue."; - "azure-cosmos-spark_3-3_2-12" = "Javadoc dependency issue."; - "azure-cosmos-spark_3-4_2-12" = "Javadoc dependency issue."; - "azure-cosmos-spark_3-5_2-12" = "Javadoc dependency issue."; - "azure-cosmos-test" = "Don't want to include the test framework package."; - "azure-aot-graalvm-support-netty" = "No Javadocs for the package."; - "azure-aot-graalvm-support" = "No Javadocs for the package."; - "azure-sdk-template" = "Depends on unreleased core."; - "azure-sdk-template-two" = "Depends on unreleased core."; - "azure-sdk-template-three" = "Depends on unreleased core."; - "azure-ai-personalizer" = "No java docs in this package."; - "azure-sdk-build-tool" = "Do not release docs for this package."; - "azure-resourcemanager-voiceservices" = "Doc build attempts to download a package that does not have published sources."; - "azure-resourcemanager-storagemover" = "Attempts to azure-sdk-build-tool and fails"; - "azure-security-keyvault-jca" = "Consistently hangs docs build, might be a spring package https://github.com/Azure/azure-sdk-for-java/issues/35389"; -} - -# Validates if the package will succeed in the CI build by validating the -# existence of a com folder in the unzipped source package -function SourcePackageHasComFolder($artifactNamePrefix, $packageDirectory) { - try - { - $packageArtifact = "${artifactNamePrefix}:jar:sources" - $mvnResults = mvn ` - dependency:copy ` - -Dartifact="$packageArtifact" ` - -DoutputDirectory="$packageDirectory" - - if ($LASTEXITCODE) { - LogWarning "Could not download source artifact: $packageArtifact" - $mvnResults | Write-Host - return $false - } - - $sourcesJarPath = (Get-ChildItem -File -Path $packageDirectory -Filter "*-sources.jar")[0] - $sourcesExtractPath = Join-Path $packageDirectory "sources" - - # Ensure that the sources folder is empty before extracting the jar - # otherwise there could be file collisions from a previous extraction run on - # the same system. - Remove-Item $sourcesExtractPath/* -Force -Recurse -ErrorAction Ignore - - Add-Type -AssemblyName System.IO.Compression.FileSystem - [System.IO.Compression.ZipFile]::ExtractToDirectory($sourcesJarPath, $sourcesExtractPath) - - if (!(Test-Path "$sourcesExtractPath\com")) { - LogWarning "Could not locate 'com' folder extracting $packageArtifact" - return $false - } - } - catch - { - LogError "Exception while updating checking if package can be documented: $($package.packageGroupId):$($package.packageArtifactId)" - LogError $_ - LogError $_.ScriptStackTrace - return $false - } - - return $true -} - -function PackageDependenciesResolve($artifactNamePrefix, $packageDirectory) { - - $pomArtifactName = "${artifactNamePrefix}:pom" - $artifactDownloadOutput = mvn ` - dependency:copy ` - -Dartifact="$pomArtifactName" ` - -DoutputDirectory="$packageDirectory" - - if ($LASTEXITCODE) { - LogWarning "Could not download pom artifact: $pomArtifactName" - $artifactDownloadOutput | Write-Host - return $false - } - - $downloadedPomPath = (Get-ChildItem -File -Path $packageDirectory -Filter '*.pom')[0] - - # -P '!azure-mgmt-sdk-test-jar' excludes the unpublished test jar from - # dependencies - $copyDependencyOutput = mvn ` - -f $downloadedPomPath ` - dependency:copy-dependencies ` - -P '!azure-mgmt-sdk-test-jar' ` - -DoutputDirectory="$packageDirectory" - - if ($LASTEXITCODE) { - LogWarning "Could not resolve dependencies for: $pomArtifactName" - $copyDependencyOutput | Write-Host - return $false - } - - return $true -} - -function ValidatePackage($groupId, $artifactId, $version, $DocValidationImageId) { - return ValidatePackages @{ Group = $groupId; Name = $artifactId; Version = $version; } $DocValidationImageId -} - -function ValidatePackages([array]$packageInfos, $DocValidationImageId) { - $workingDirectory = Join-Path ([System.IO.Path]::GetTempPath()) "validation" - if (!(Test-Path $workingDirectory)) { - New-Item -ItemType Directory -Force -Path $workingDirectory | Out-Null - } - - # Add more validation by replicating as much of the docs CI process as - # possible - # https://github.com/Azure/azure-sdk-for-python/issues/20109 - if (!$DocValidationImageId) - { - return FallbackValidation -packageInfos $packageInfos -workingDirectory $workingDirectory - } - else - { - return DockerValidation -packageInfos $packageInfos -DocValidationImageId $DocValidationImageId -workingDirectory $workingDirectory - } -} - -function FallbackValidation ($packageInfos, $workingDirectory) { - $results = @() - - foreach ($packageInfo in $packageInfos) { - $groupId = $packageInfo.Group - $artifactId = $packageInfo.Name - $version = $packageInfo.Version - - Write-Host "Validating using mvn command directly on $artifactId." - - $artifactNamePrefix = "${groupId}:${artifactId}:${version}" - - $packageDirectory = Join-Path $workingDirectory "${groupId}__${artifactId}__${version}" - New-Item -ItemType Directory -Path $packageDirectory -Force | Out-Null - - $isValid = (SourcePackageHasComFolder $artifactNamePrefix $packageDirectory) ` - -and (PackageDependenciesResolve $artifactNamePrefix $packageDirectory) - - if (!$isValid) { - LogWarning "Package $artifactNamePrefix ref docs validation failed." - } - - $results += $isValid - } - - $allValid = $results.Where({ $_ -eq $false }).Count -eq 0 - - return $allValid -} - -function DockerValidation ($packageInfos, $DocValidationImageId, $workingDirectory) { - Write-Host "Validating $($packageInfos.Length) package(s) using $DocValidationImageId." - - $containerWorkingDirectory = '/workdir/out' - $configurationFileName = 'configuration.json' - - $hostConfigurationPath = Join-Path $workingDirectory $configurationFileName - - # Cannot use Join-Path because the container and host path separators may differ - $containerConfigurationPath = "$containerWorkingDirectory/$configurationFileName" - - $configuration = [ordered]@{ - "output_path" = "docs-ref-autogen"; - "packages" = @($packageInfos | ForEach-Object { [ordered]@{ - packageGroupId = $_.Group; - packageArtifactId = $_.Name; - packageVersion = $_.Version; - packageDownloadUrl = $PackageRepositoryUri; - } }); - } - - Set-Content -Path $hostConfigurationPath -Value ($configuration | ConvertTo-Json) | Out-Null - - docker run -v "${workingDirectory}:${containerWorkingDirectory}" ` - -e TARGET_CONFIGURATION_PATH=$containerConfigurationPath $DocValidationImageId 2>&1 ` - | Where-Object { -not ($_ -match '^Progress .*B\s*$') } ` # Remove progress messages - | Out-Host - - if ($LASTEXITCODE -ne 0) { - LogWarning "The `docker` command failed with exit code $LASTEXITCODE." - - # The docker exit codes: https://docs.docker.com/engine/reference/run/#exit-status - # If the docker validation failed because of docker itself instead of the application, or if we don't know which - # package failed, fall back to mvn validation - if ($LASTEXITCODE -in 125..127 -Or $packageInfos.Length -gt 1) { - return FallbackValidation -packageInfos $packageInfos -workingDirectory $workingDirectory - } - - return $false - } - - return $true -} - -function Update-java-DocsMsPackages($DocsRepoLocation, $DocsMetadata, $DocValidationImageId) { - Write-Host "Excluded packages:" - foreach ($excludedPackage in $PackageExclusions.Keys) { - Write-Host " $excludedPackage - $($PackageExclusions[$excludedPackage])" - } - - # Also exclude 'spring' packages - # https://github.com/Azure/azure-sdk-for-java/issues/23087 - $FilteredMetadata = $DocsMetadata.Where({ !($PackageExclusions.ContainsKey($_.Package) -or $_.Type -eq 'spring') }) - - UpdateDocsMsPackages ` - (Join-Path $DocsRepoLocation 'package.json') ` - 'preview' ` - $FilteredMetadata ` - $DocValidationImageId - - UpdateDocsMsPackages ` - (Join-Path $DocsRepoLocation 'package.json') ` - 'latest' ` - $FilteredMetadata ` - $DocValidationImageId -} - -function UpdateDocsMsPackages($DocConfigFile, $Mode, $DocsMetadata, $DocValidationImageId) { - $packageConfig = Get-Content $DocConfigFile -Raw | ConvertFrom-Json - - $packageOutputPath = 'docs-ref-autogen' - if ($Mode -eq 'preview') { - $packageOutputPath = 'preview/docs-ref-autogen' - } - $targetPackageList = $packageConfig.Where({ $_.output_path -eq $packageOutputPath}) - if ($targetPackageList.Length -eq 0) { - LogError "Unable to find package config for $packageOutputPath in $DocConfigFile" - exit 1 - } elseif ($targetPackageList.Length -gt 1) { - LogError "Found multiple package configs for $packageOutputPath in $DocConfigFile" - exit 1 - } - - $targetPackageList = $targetPackageList[0] - - $outputPackages = @() - foreach ($package in $targetPackageList.packages) { - $packageGroupId = $package.packageGroupId - $packageName = $package.packageArtifactId - - $matchingPublishedPackageArray = $DocsMetadata.Where({ - $_.Package -eq $packageName -and $_.GroupId -eq $packageGroupId - }) - - # If this package does not match any published packages keep it in the list. - # This handles packages which are not tracked in metadata but still need to - # be built in Docs CI. - if ($matchingPublishedPackageArray.Count -eq 0) { - Write-Host "Keep non-tracked package: $packageName" - $outputPackages += $package - continue - } - - if ($matchingPublishedPackageArray.Count -gt 1) { - LogWarning "Found more than one matching published package in metadata for $packageName; only updating first entry" - } - $matchingPublishedPackage = $matchingPublishedPackageArray[0] - - if ($Mode -eq 'preview' -and !$matchingPublishedPackage.VersionPreview.Trim()) { - # If we are in preview mode and the package does not have a superseding - # preview version, remove the package from the list. - Write-Host "Remove superseded preview package: $packageName" - continue - } - - if ($Mode -eq 'latest' -and !$matchingPublishedPackage.VersionGA.Trim()) { - LogWarning "Metadata is missing GA version for GA package $packageName. Keeping existing package." - $outputPackages += $package - continue - } - - $packageVersion = $($matchingPublishedPackage.VersionGA) - if ($Mode -eq 'preview') { - if (!$matchingPublishedPackage.VersionPreview.Trim()) { - LogWarning "Metadata is missing preview version for preview package $packageName. Keeping existing package." - $outputPackages += $package - continue - } - $packageVersion = $matchingPublishedPackage.VersionPreview - } - - # If upgrading the package, run basic sanity checks against the package - if ($package.packageVersion -ne $packageVersion) { - Write-Host "Validating new version detected for $packageName ($packageVersion)" - $validatePackageResult = ValidatePackage $package.packageGroupId $package.packageArtifactId $packageVersion $DocValidationImageId - - if (!$validatePackageResult) { - LogWarning "Package is not valid: $packageName. Keeping old version." - $outputPackages += $package - continue - } - - $package.packageVersion = $packageVersion - } - - Write-Host "Keeping tracked package: $packageName." - $outputPackages += $package - } - - $outputPackagesHash = @{} - foreach ($package in $outputPackages) { - $outputPackagesHash["$($package.packageGroupId):$($package.packageArtifactId)"] = $true - } - - $remainingPackages = @() - if ($Mode -eq 'preview') { - $remainingPackages = $DocsMetadata.Where({ - ![string]::IsNullOrWhiteSpace($_.VersionPreview) -and !$outputPackagesHash.ContainsKey("$($_.GroupId):$($_.Package)") - }) - } else { - $remainingPackages = $DocsMetadata.Where({ - ![string]::IsNullOrWhiteSpace($_.VersionGA) -and !$outputPackagesHash.ContainsKey("$($_.GroupId):$($_.Package)") - }) - } - - # Add packages that exist in the metadata but are not onboarded in docs config - foreach ($package in $remainingPackages) { - $packageName = $package.Package - $packageGroupId = $package.GroupId - $packageVersion = $package.VersionGA - if ($Mode -eq 'preview') { - $packageVersion = $package.VersionPreview - } - - Write-Host "Validating new package $($packageGroupId):$($packageName):$($packageVersion)" - $validatePackageResult = ValidatePackage $packageGroupId $packageName $packageVersion $DocValidationImageId - if (!$validatePackageResult) { - LogWarning "Package is not valid: ${packageGroupId}:$packageName. Cannot onboard." - continue - } - - Write-Host "Add new package from metadata: ${packageGroupId}:$packageName" - $package = [ordered]@{ - packageArtifactId = $packageName - packageGroupId = $packageGroupId - packageVersion = $packageVersion - packageDownloadUrl = $PackageRepositoryUri - } - - $outputPackages += $package - } - - $targetPackageList.packages = $outputPackages - - # It is assumed that there is a matching config from above when the number of - # matching $targetPackageList is 1 - foreach ($config in $packageConfig) { - if ($config.output_path -eq $packageOutputPath) { - $config = $targetPackageList - break - } - } - - $outputJson = ConvertTo-Json $packageConfig -Depth 100 - Set-Content -Path $DocConfigFile -Value $outputJson - Write-Host "Onboarding configuration $Mode written to: $DocConfigFile" -} - # function is used to filter packages to submit to API view tool function Find-java-Artifacts-For-Apireview($artifactDir, $pkgName) { @@ -754,6 +352,8 @@ function GetExistingPackageVersions ($PackageName, $GroupId=$null) } } +# Defined in common.ps1 +# $GetDocsMsMetadataForPackageFn = "Get-${Language}-DocsMsMetadataForPackage" function Get-java-DocsMsMetadataForPackage($PackageInfo) { $readmeName = $PackageInfo.Name.ToLower() Write-Host "Docs.ms Readme name: $($readmeName)" @@ -787,12 +387,81 @@ function Validate-java-DocMsPackages ($PackageInfo, $PackageInfos, $DocValidatio $PackageInfos = @($PackageInfo) } - if (!(ValidatePackages $PackageInfos $DocValidationImageId)) { - Write-Error "Package validation failed" -ErrorAction Continue + # The install-rex-validation-tool.yml will install the java2docfx jar file into the Build.BinariesDirectory + # which is a DevOps variable for the directory. In PS that variable is BUILD_BINARIESDIRECTORY. + # The reason why this is necessary is that the command for java2docfx is in the following format: + # java –jar java2docfx-1.0.0.jar.jar --packagesJsonFile "C\temp\package.json" + # or + # java –jar java2docfx-1.0.0.jar --package "::" + # which means we need to know where, exactly, because the java command requires the full path + # to the jar file as an argument + $java2docfxJar = $null + if (!$Env:BUILD_BINARIESDIRECTORY) { + LogError "Env:BUILD_BINARIESDIRECTORY is not set and this is where the java2docfx jar file should be installed." + return $false + } + $java2docfxDir = Join-Path $Env:BUILD_BINARIESDIRECTORY "java2docfx" + if (!(Test-Path $java2docfxDir)) { + LogError "There should be a java2docfx directory under Env:BUILD_BINARIESDIRECTORY. Ensure that the /eng/pipelines/templates/steps/install-rex-validation-tool.yml template was run prior to whatever step is running this." + return $false + } + $java2docfxJarLoc = @(Get-ChildItem -Path $java2docfxDir -File -Filter "java2docfx*.jar") + if (!$java2docfxJarLoc) { + LogError "The java2docfx jar file should be installed in $java2docfxDir and is not there." return $false + } else { + # In theory, this shouldn't happen as the install-rex-validation-tool.yml is the only thing + # that'll ever install the jar + if ($java2docfxJarLoc.Count -gt 1) { + Write-Host "There were $($java2docfxJarLoc.Count) java2docfx jar files found in $Build_BinariesDirectory, using the first one" + } + $java2docfxJar = $java2docfxJarLoc[0] + Write-Host "java2docfx jar location=$java2docfxJar" + } + + $allSuccess = $true + $originLocation = Get-Location + foreach ($packageInfo in $PackageInfos) { + $artifact = "$($packageInfo.Group):$($packageInfo.Name):$($packageInfo.Version)" + $tempDirectory = Join-Path ([System.IO.Path]::GetTempPath()) "$($packageInfo.Group)-$($packageInfo.Name)-$($packageInfo.Version)" + New-Item $tempDirectory -ItemType Directory | Out-Null + # Set the location to the temp directory. The reason being is that it'll effectively be empty, no + # other jars, no POM files aka nothing Java related to pick up. + Set-Location $tempDirectory + try { + Write-Host "Calling java2docfx for $artifact" + Write-Host "java -jar ""$java2docfxJar"" -p ""$artifact""" + $java2docfxResults = java ` + -jar "$java2docfxJar"` + -p "$artifact" + # JRS-TODO: The -o option is something I'm currently questioning the behavior of but + # I can do some initial testing without that option being set + # -p "$artifact" ` + # -o "$tempDirectory" + + if ($LASTEXITCODE -ne 0) { + LogWarning "java2docfx failed for $artifact" + $java2docfxResults | Write-Host + $allSuccess = $false + } + } + catch { + LogError "Exception while trying to download: $artifact" + LogError $_ + LogError $_.ScriptStackTrace + $allSuccess = $false + } + finally { + # Ensure that the origianl location is restored + Set-Location $originLocation + # everything is contained within the temp directory, clean it up every time + if (Test-Path $tempDirectory) { + Remove-Item $tempDirectory -Recurse -Force + } + } } - return $true + return $allSuccess } function Get-java-EmitterName() { diff --git a/eng/scripts/docs/java2docfx.version.txt b/eng/scripts/docs/java2docfx.version.txt new file mode 100644 index 000000000000..a6a3a43c3a04 --- /dev/null +++ b/eng/scripts/docs/java2docfx.version.txt @@ -0,0 +1 @@ +1.0.4 \ No newline at end of file diff --git a/eng/versioning/external_dependencies.txt b/eng/versioning/external_dependencies.txt index d5644c733269..4300df19b15d 100644 --- a/eng/versioning/external_dependencies.txt +++ b/eng/versioning/external_dependencies.txt @@ -54,7 +54,7 @@ commons-codec:commons-codec;1.15 commons-net:commons-net;3.9.0 io.cloudevents:cloudevents-api;2.2.0 io.cloudevents:cloudevents-core;2.2.0 -io.fabric8:kubernetes-client;5.12.3 +io.fabric8:kubernetes-client;6.12.1 io.micrometer:micrometer-core;1.9.17 io.micrometer:micrometer-registry-azure-monitor;1.9.17 io.micrometer:micrometer-registry-graphite;1.9.17 diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index bc256bc3f118..0566ad82773d 100644 --- a/eng/versioning/version_client.txt +++ b/eng/versioning/version_client.txt @@ -110,7 +110,7 @@ com.azure.cosmos.spark:azure-cosmos-spark_3-2_2-12;4.30.0;4.31.0-beta.1 com.azure.cosmos.spark:azure-cosmos-spark_3-3_2-12;4.30.0;4.31.0-beta.1 com.azure.cosmos.spark:azure-cosmos-spark_3-4_2-12;4.30.0;4.31.0-beta.1 com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12;4.30.0;4.31.0-beta.1 -com.azure:azure-cosmos-test;1.0.0-beta.6;1.0.0-beta.7 +com.azure:azure-cosmos-test;1.0.0-beta.7;1.0.0-beta.8 com.azure:azure-cosmos-tests;1.0.0-beta.1;1.0.0-beta.1 com.azure.cosmos.kafka:azure-cosmos-kafka-connect;1.0.0-beta.2;1.0.0-beta.3 com.azure:azure-data-appconfiguration;1.6.0;1.7.0-beta.1 @@ -155,7 +155,7 @@ com.azure:azure-messaging-eventhubs-checkpointstore-jedis;1.0.0-beta.2;1.0.0-bet com.azure:azure-messaging-eventhubs-stress;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-messaging-eventhubs-track1-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-messaging-eventhubs-track2-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-messaging-servicebus;7.16.0;7.17.0-beta.1 +com.azure:azure-messaging-servicebus;7.17.0;7.18.0-beta.1 com.azure:azure-messaging-servicebus-stress;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-messaging-servicebus-track1-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-messaging-servicebus-track2-perf;1.0.0-beta.1;1.0.0-beta.1 @@ -170,7 +170,7 @@ com.azure:azure-monitor-query;1.3.1;1.4.0-beta.1 com.azure:azure-monitor-query-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-perf-test-parent;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-quantum-jobs;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-search-documents;11.6.4;11.7.0-beta.3 +com.azure:azure-search-documents;11.6.4;11.7.0-beta.4 com.azure:azure-search-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-security-attestation;1.1.23;1.2.0-beta.1 com.azure:azure-security-confidentialledger;1.0.19;1.1.0-beta.1 @@ -184,7 +184,7 @@ com.azure:azure-security-keyvault-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-sdk-template;1.1.1234;1.2.2-beta.1 com.azure:azure-sdk-template-two;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-sdk-template-three;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-spring-data-cosmos;3.44.0;3.45.0-beta.1 +com.azure:azure-spring-data-cosmos;3.45.0;3.46.0-beta.1 com.azure:azure-storage-blob;12.25.4;12.26.0-beta.2 com.azure:azure-storage-blob-batch;12.21.4;12.22.0-beta.2 com.azure:azure-storage-blob-changefeed;12.0.0-beta.20;12.0.0-beta.21 @@ -208,58 +208,58 @@ com.azure:identity-test-vm;1.0-SNAPSHOT;1.0-SNAPSHOT com.azure:identity-test-webapp;0.0.1-SNAPSHOT;0.0.1-SNAPSHOT com.azure.spring:azure-monitor-spring-native;1.0.0-beta.1;1.0.0-beta.1 com.azure.spring:azure-monitor-spring-native-test;1.0.0-beta.1;1.0.0-beta.1 -com.azure.spring:spring-cloud-azure-appconfiguration-config-web;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-appconfiguration-config;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-feature-management-web;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-feature-management;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-appconfiguration-config;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-dependencies;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-messaging-azure;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-messaging-azure-eventhubs;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-messaging-azure-servicebus;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-messaging-azure-storage-queue;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-integration-azure-core;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-integration-azure-eventhubs;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-integration-azure-servicebus;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-integration-azure-storage-queue;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-core;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-actuator-autoconfigure;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-actuator;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-autoconfigure;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-resourcemanager;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-service;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-active-directory;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-active-directory-b2c;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-actuator;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-appconfiguration;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-cosmos;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-data-cosmos;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-eventhubs;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-eventgrid;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-jdbc-mysql;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-jdbc-postgresql;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-redis;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-keyvault;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-keyvault-certificates;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-keyvault-secrets;4.17.0;4.18.0-beta.1 +com.azure.spring:spring-cloud-azure-appconfiguration-config-web;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-appconfiguration-config;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-feature-management-web;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-feature-management;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-appconfiguration-config;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-dependencies;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-messaging-azure;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-messaging-azure-eventhubs;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-messaging-azure-servicebus;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-messaging-azure-storage-queue;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-integration-azure-core;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-integration-azure-eventhubs;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-integration-azure-servicebus;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-integration-azure-storage-queue;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-core;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-actuator-autoconfigure;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-actuator;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-autoconfigure;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-resourcemanager;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-service;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-active-directory;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-active-directory-b2c;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-actuator;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-appconfiguration;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-cosmos;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-data-cosmos;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-eventhubs;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-eventgrid;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-jdbc-mysql;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-jdbc-postgresql;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-redis;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-keyvault;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-keyvault-certificates;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-keyvault-secrets;4.18.0;4.19.0-beta.1 com.azure.spring:spring-cloud-azure-starter-monitor;1.0.0-beta.5;1.0.0-beta.6 -com.azure.spring:spring-cloud-azure-starter-servicebus-jms;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-servicebus;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-storage;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-storage-blob;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-storage-file-share;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-storage-queue;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-integration-eventhubs;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-integration-servicebus;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-integration-storage-queue;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-stream-eventhubs;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-stream-servicebus;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-starter;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-stream-binder-eventhubs-core;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-stream-binder-eventhubs;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-stream-binder-servicebus-core;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-stream-binder-servicebus;4.17.0;4.18.0-beta.1 -com.azure.spring:spring-cloud-azure-trace-sleuth;4.17.0;4.18.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-servicebus-jms;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-servicebus;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-storage;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-storage-blob;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-storage-file-share;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-storage-queue;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-integration-eventhubs;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-integration-servicebus;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-integration-storage-queue;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-stream-eventhubs;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-stream-servicebus;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-starter;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-stream-binder-eventhubs-core;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-stream-binder-eventhubs;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-stream-binder-servicebus-core;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-stream-binder-servicebus;4.18.0;4.19.0-beta.1 +com.azure.spring:spring-cloud-azure-trace-sleuth;4.18.0;4.19.0-beta.1 com.azure.resourcemanager:azure-resourcemanager;2.38.0;2.39.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-appplatform;2.38.0;2.39.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-appservice;2.38.0;2.39.0-beta.1 diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java index ef014fb4d65e..e044d4ca5cc4 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java @@ -21,8 +21,10 @@ import com.azure.core.util.polling.PollOperationDetails; import com.azure.core.util.polling.PollerFlux; import com.azure.data.appconfiguration.implementation.AzureAppConfigurationImpl; +import com.azure.data.appconfiguration.implementation.ConfigurationSettingDeserializationHelper; import com.azure.data.appconfiguration.implementation.CreateSnapshotUtilClient; import com.azure.data.appconfiguration.implementation.SyncTokenPolicy; +import com.azure.data.appconfiguration.implementation.Utility; import com.azure.data.appconfiguration.implementation.models.GetKeyValueHeaders; import com.azure.data.appconfiguration.implementation.models.KeyValue; import com.azure.data.appconfiguration.models.ConfigurationSetting; @@ -44,13 +46,9 @@ import static com.azure.core.util.FluxUtil.monoError; import static com.azure.core.util.FluxUtil.withContext; -import static com.azure.data.appconfiguration.implementation.ConfigurationSettingDeserializationHelper.toConfigurationSettingWithPagedResponse; -import static com.azure.data.appconfiguration.implementation.ConfigurationSettingDeserializationHelper.toConfigurationSettingWithResponse; import static com.azure.data.appconfiguration.implementation.Utility.ETAG_ANY; -import static com.azure.data.appconfiguration.implementation.Utility.addTracingNamespace; import static com.azure.data.appconfiguration.implementation.Utility.getETag; import static com.azure.data.appconfiguration.implementation.Utility.getPageETag; -import static com.azure.data.appconfiguration.implementation.Utility.handleNotModifiedErrorToValidResponse; import static com.azure.data.appconfiguration.implementation.Utility.toKeyValue; import static com.azure.data.appconfiguration.implementation.Utility.toSettingFieldsList; import static com.azure.data.appconfiguration.implementation.Utility.updateSnapshotAsync; @@ -354,7 +352,7 @@ public Mono addConfigurationSetting(String key, String lab /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -391,7 +389,7 @@ public Mono addConfigurationSetting(ConfigurationSetting s /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -429,9 +427,8 @@ public Mono> addConfigurationSettingWithResponse( return withContext( context -> validateSettingAsync(setting).flatMap( settingInternal -> serviceClient.putKeyValueWithResponseAsync(settingInternal.getKey(), - settingInternal.getLabel(), null, ETAG_ANY, toKeyValue(settingInternal), - addTracingNamespace(context)) - .map(response -> toConfigurationSettingWithResponse(response)))); + settingInternal.getLabel(), null, ETAG_ANY, toKeyValue(settingInternal), context) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithResponse))); } /** @@ -471,7 +468,7 @@ public Mono setConfigurationSetting(String key, String lab /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -515,10 +512,10 @@ public Mono setConfigurationSetting(ConfigurationSetting s /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. - * + *

* If {@link ConfigurationSetting#getETag() ETag} is specified, the configuration value is updated if the current * setting's ETag matches. If the ETag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. @@ -574,8 +571,8 @@ public Mono> setConfigurationSettingWithResponse( context -> validateSettingAsync(setting).flatMap( settingInternal -> serviceClient.putKeyValueWithResponseAsync(settingInternal.getKey(), settingInternal.getLabel(), getETag(ifUnchanged, settingInternal), null, - toKeyValue(settingInternal), addTracingNamespace(context)) - .map(response -> toConfigurationSettingWithResponse(response)))); + toKeyValue(settingInternal), context) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithResponse))); } /** @@ -716,25 +713,20 @@ public Mono getConfigurationSetting(ConfigurationSetting s @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getConfigurationSettingWithResponse(ConfigurationSetting setting, OffsetDateTime acceptDateTime, boolean ifChanged) { - return withContext( - context -> validateSettingAsync(setting).flatMap( - settingInternal -> - serviceClient.getKeyValueWithResponseAsync(settingInternal.getKey(), settingInternal.getLabel(), - acceptDateTime == null ? null : acceptDateTime.toString(), null, - getETag(ifChanged, settingInternal), null, addTracingNamespace(context)) - .onErrorResume( - HttpResponseException.class, - (Function>>) throwable -> { - HttpResponseException e = (HttpResponseException) throwable; - HttpResponse httpResponse = e.getResponse(); - if (httpResponse.getStatusCode() == 304) { - return Mono.just(new ResponseBase( - httpResponse.getRequest(), httpResponse.getStatusCode(), - httpResponse.getHeaders(), null, null)); - } - return Mono.error(throwable); - }) - .map(response -> toConfigurationSettingWithResponse(response)))); + return withContext(context -> validateSettingAsync(setting).flatMap(settingInternal -> + serviceClient.getKeyValueWithResponseAsync(settingInternal.getKey(), settingInternal.getLabel(), + acceptDateTime == null ? null : acceptDateTime.toString(), null, + getETag(ifChanged, settingInternal), null, context) + .onErrorResume(HttpResponseException.class, + (Function>>) throwable -> { + HttpResponseException e = (HttpResponseException) throwable; + HttpResponse httpResponse = e.getResponse(); + if (httpResponse.getStatusCode() == 304) { + return Mono.just(new ResponseBase(httpResponse.getRequest(), + httpResponse.getStatusCode(), httpResponse.getHeaders(), null, null)); + } + return Mono.error(throwable); + }).map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithResponse))); } /** @@ -770,7 +762,7 @@ public Mono deleteConfigurationSetting(String key, String * {@link ConfigurationSetting#getLabel() label} and optional ETag combination from the service. * For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. - * + *

* If {@link ConfigurationSetting#getETag() ETag} is specified and is not the wildcard character ({@code "*"}), then * the setting is only deleted if the ETag matches the current ETag; this means that no one has updated the * ConfigurationSetting yet. @@ -809,10 +801,10 @@ public Mono deleteConfigurationSetting(ConfigurationSettin /** * Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting#getKey() key}, and optional * {@link ConfigurationSetting#getLabel() label} and optional ETag combination from the service. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. - * + *

* If {@link ConfigurationSetting#getETag() ETag} is specified and is not the wildcard character ({@code "*"}), then * the setting is only deleted if the ETag matches the current ETag; this means that no one has updated the * ConfigurationSetting yet. @@ -855,8 +847,8 @@ public Mono> deleteConfigurationSettingWithRespon boolean ifUnchanged) { return withContext(context -> validateSettingAsync(setting).flatMap( settingInternal -> serviceClient.deleteKeyValueWithResponseAsync(settingInternal.getKey(), - settingInternal.getLabel(), getETag(ifUnchanged, settingInternal), addTracingNamespace(context)) - .map(response -> toConfigurationSettingWithResponse(response)))); + settingInternal.getLabel(), getETag(ifUnchanged, settingInternal), context) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithResponse))); } /** @@ -901,7 +893,7 @@ public Mono setReadOnly(String key, String label, boolean /** * Sets the read-only status for the {@link ConfigurationSetting}. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -949,7 +941,7 @@ public Mono setReadOnly(ConfigurationSetting setting, bool /** * Sets the read-only status for the {@link ConfigurationSetting}. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -1000,16 +992,14 @@ public Mono setReadOnly(ConfigurationSetting setting, bool @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setReadOnlyWithResponse(ConfigurationSetting setting, boolean isReadOnly) { - return withContext(context -> validateSettingAsync(setting).flatMap( - settingInternal -> { - final String key = settingInternal.getKey(); - final String label = settingInternal.getLabel(); - final Context contextInternal = addTracingNamespace(context); - return (isReadOnly - ? serviceClient.putLockWithResponseAsync(key, label, null, null, contextInternal) - : serviceClient.deleteLockWithResponseAsync(key, label, null, null, contextInternal)) - .map(response -> toConfigurationSettingWithResponse(response)); - })); + return withContext(context -> validateSettingAsync(setting).flatMap(settingInternal -> { + final String key = settingInternal.getKey(); + final String label = settingInternal.getLabel(); + return (isReadOnly + ? serviceClient.putLockWithResponseAsync(key, label, null, null, context) + : serviceClient.deleteLockWithResponseAsync(key, label, null, null, context)) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithResponse); + })); } /** @@ -1042,31 +1032,19 @@ public PagedFlux listConfigurationSettings(SettingSelector final List settingFields = selector == null ? null : toSettingFieldsList(selector.getFields()); final List matchConditionsList = selector == null ? null : selector.getMatchConditions(); AtomicInteger pageETagIndex = new AtomicInteger(0); - return new PagedFlux<>( - () -> withContext(context -> serviceClient.getKeyValuesSinglePageAsync( - keyFilter, - labelFilter, - null, - acceptDateTime, - settingFields, - null, - null, - getPageETag(matchConditionsList, pageETagIndex), - addTracingNamespace(context)) - .onErrorResume(HttpResponseException.class, - (Function>>) throwable -> - handleNotModifiedErrorToValidResponse(throwable)) - .map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))), - nextLink -> withContext(context -> serviceClient.getKeyValuesNextSinglePageAsync( - nextLink, - acceptDateTime, - null, - getPageETag(matchConditionsList, pageETagIndex), - addTracingNamespace(context)) - .onErrorResume(HttpResponseException.class, - (Function>>) throwable -> - handleNotModifiedErrorToValidResponse(throwable)) - .map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))) + return new PagedFlux<>(() -> withContext(context -> serviceClient.getKeyValuesSinglePageAsync(keyFilter, + labelFilter, null, acceptDateTime, settingFields, null, null, + getPageETag(matchConditionsList, pageETagIndex), context) + .onErrorResume(HttpResponseException.class, + (Function>>) + Utility::handleNotModifiedErrorToValidResponse) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithPagedResponse)), + nextLink -> withContext(context -> serviceClient.getKeyValuesNextSinglePageAsync(nextLink, + acceptDateTime, null, getPageETag(matchConditionsList, pageETagIndex), context) + .onErrorResume(HttpResponseException.class, + (Function>>) + Utility::handleNotModifiedErrorToValidResponse) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithPagedResponse)) ); } @@ -1124,29 +1102,13 @@ public PagedFlux listConfigurationSettingsForSnapshot(Stri */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listConfigurationSettingsForSnapshot(String snapshotName, - List fields) { - return new PagedFlux<>( - () -> withContext( - context -> serviceClient.getKeyValuesSinglePageAsync( - null, - null, - null, - null, - fields, - snapshotName, - null, - null, - addTracingNamespace(context)) - .map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))), - nextLink -> withContext( - context -> serviceClient.getKeyValuesNextSinglePageAsync( - nextLink, - null, - null, - null, - addTracingNamespace(context)) - .map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))) - ); + List fields) { + return new PagedFlux<>(() -> withContext(context -> serviceClient.getKeyValuesSinglePageAsync(null, null, null, + null, fields, snapshotName, null, null, context) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithPagedResponse)), + nextLink -> withContext(context -> serviceClient.getKeyValuesNextSinglePageAsync(nextLink, null, null, null, + context) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithPagedResponse))); } /** @@ -1154,7 +1116,7 @@ public PagedFlux listConfigurationSettingsForSnapshot(Stri * in descending order from their {@link ConfigurationSetting#getLastModified() lastModified} date. * Revisions expire after a period of time, see Pricing * for more information. - * + *

* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code selector}. * @@ -1181,21 +1143,12 @@ public PagedFlux listRevisions(SettingSelector selector) { final String labelFilter = selector == null ? null : selector.getLabelFilter(); final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime(); final List settingFields = selector == null ? null : toSettingFieldsList(selector.getFields()); - return new PagedFlux<>( - () -> withContext( - context -> serviceClient.getRevisionsSinglePageAsync( - keyFilter, - labelFilter, - null, - acceptDateTime, - settingFields, - addTracingNamespace(context)) - .map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))), - nextLink -> withContext( - context -> - serviceClient.getRevisionsNextSinglePageAsync(nextLink, acceptDateTime, - addTracingNamespace(context)) - .map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse)))); + return new PagedFlux<>(() -> withContext(context -> serviceClient.getRevisionsSinglePageAsync(keyFilter, + labelFilter, null, acceptDateTime, settingFields, context) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithPagedResponse)), + nextLink -> withContext(context -> serviceClient.getRevisionsNextSinglePageAsync(nextLink, acceptDateTime, + context) + .map(ConfigurationSettingDeserializationHelper::toConfigurationSettingWithPagedResponse))); } /** @@ -1440,17 +1393,11 @@ public Mono> recoverSnapshotWithResponse( @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listSnapshots(SnapshotSelector selector) { try { - return new PagedFlux<>( - () -> withContext( - context -> serviceClient.getSnapshotsSinglePageAsync( - selector == null ? null : selector.getNameFilter(), - null, - selector == null ? null : selector.getFields(), - selector == null ? null : selector.getStatus(), - addTracingNamespace(context))), - nextLink -> withContext( - context -> serviceClient.getSnapshotsNextSinglePageAsync(nextLink, addTracingNamespace(context))) - ); + return new PagedFlux<>(() -> withContext(context -> serviceClient.getSnapshotsSinglePageAsync( + selector == null ? null : selector.getNameFilter(), null, + selector == null ? null : selector.getFields(), selector == null ? null : selector.getStatus(), + context)), nextLink -> withContext(context -> + serviceClient.getSnapshotsNextSinglePageAsync(nextLink, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(LOGGER, ex)); } diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClient.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClient.java index 94d07ff34f5c..30e97c8af057 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClient.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClient.java @@ -46,8 +46,6 @@ import static com.azure.data.appconfiguration.implementation.ConfigurationSettingDeserializationHelper.toConfigurationSettingWithPagedResponse; import static com.azure.data.appconfiguration.implementation.ConfigurationSettingDeserializationHelper.toConfigurationSettingWithResponse; import static com.azure.data.appconfiguration.implementation.Utility.ETAG_ANY; -import static com.azure.data.appconfiguration.implementation.Utility.addTracingNamespace; -import static com.azure.data.appconfiguration.implementation.Utility.enableSyncRestProxy; import static com.azure.data.appconfiguration.implementation.Utility.getETag; import static com.azure.data.appconfiguration.implementation.Utility.getPageETag; import static com.azure.data.appconfiguration.implementation.Utility.handleNotModifiedErrorToValidResponse; @@ -356,7 +354,7 @@ public ConfigurationSetting addConfigurationSetting(String key, String label, St /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -392,7 +390,7 @@ public ConfigurationSetting addConfigurationSetting(ConfigurationSetting setting /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -433,7 +431,7 @@ public Response addConfigurationSettingWithResponse(Config // return an error. final ResponseBase response = serviceClient.putKeyValueWithResponse(setting.getKey(), setting.getLabel(), null, ETAG_ANY, - toKeyValue(setting), enableSyncRestProxy(addTracingNamespace(context))); + toKeyValue(setting), context); return toConfigurationSettingWithResponse(response); } @@ -475,7 +473,7 @@ public ConfigurationSetting setConfigurationSetting(String key, String label, St /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -521,10 +519,10 @@ public ConfigurationSetting setConfigurationSetting(ConfigurationSetting setting /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. - * + *

* If {@link ConfigurationSetting#getETag() ETag} is specified, the configuration value is updated if the current * setting's ETag matches. If the ETag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. @@ -578,9 +576,8 @@ public Response setConfigurationSettingWithResponse(Config boolean ifUnchanged, Context context) { validateSetting(setting); final ResponseBase response = - serviceClient.putKeyValueWithResponse(setting.getKey(), setting.getLabel(), - getETag(ifUnchanged, setting), null, toKeyValue(setting), - enableSyncRestProxy(addTracingNamespace(context))); + serviceClient.putKeyValueWithResponse(setting.getKey(), setting.getLabel(), getETag(ifUnchanged, setting), + null, toKeyValue(setting), context); return toConfigurationSettingWithResponse(response); } @@ -646,7 +643,7 @@ public ConfigurationSetting getConfigurationSetting(String key, String label, Of /** * Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting#getKey() key}, and optional * {@link ConfigurationSetting#getLabel() label}, optional {@code acceptDateTime} and optional ETag combination. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -681,7 +678,7 @@ public ConfigurationSetting getConfigurationSetting(ConfigurationSetting setting /** * Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting#getKey() key}, and optional * {@link ConfigurationSetting#getLabel() label}, optional {@code acceptDateTime} and optional ETag combination. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -725,8 +722,8 @@ public Response getConfigurationSettingWithResponse(Config try { final ResponseBase response = serviceClient.getKeyValueWithResponse(setting.getKey(), setting.getLabel(), - acceptDateTime == null ? null : acceptDateTime.toString(), null, - getETag(ifChanged, setting), null, enableSyncRestProxy(addTracingNamespace(context))); + acceptDateTime == null ? null : acceptDateTime.toString(), null, getETag(ifChanged, setting), null, + context); return toConfigurationSettingWithResponse(response); } catch (HttpResponseException ex) { final HttpResponse httpResponse = ex.getResponse(); @@ -769,7 +766,7 @@ public ConfigurationSetting deleteConfigurationSetting(String key, String label) /** * Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting#getKey() key}, and optional * {@link ConfigurationSetting#getLabel() label} and optional ETag combination. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -806,10 +803,10 @@ public ConfigurationSetting deleteConfigurationSetting(ConfigurationSetting sett /** * Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting#getKey() key}, and optional * {@link ConfigurationSetting#getLabel() label} and optional ETag combination. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. - * + *

* If {@link ConfigurationSetting#getETag() ETag} is specified and is not the wildcard character ({@code "*"}), then * the setting is only deleted if the ETag matches the current ETag; this means that no one has updated the * ConfigurationSetting yet. @@ -852,7 +849,7 @@ public Response deleteConfigurationSettingWithResponse(Con validateSetting(setting); final ResponseBase response = serviceClient.deleteKeyValueWithResponse(setting.getKey(), setting.getLabel(), - getETag(ifUnchanged, setting), enableSyncRestProxy(addTracingNamespace(context))); + getETag(ifUnchanged, setting), context); return toConfigurationSettingWithResponse(response); } @@ -898,7 +895,7 @@ public ConfigurationSetting setReadOnly(String key, String label, boolean isRead /** * Sets the read-only status for the {@link ConfigurationSetting}. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -945,7 +942,7 @@ public ConfigurationSetting setReadOnly(ConfigurationSetting setting, boolean is /** * Sets the read-only status for the {@link ConfigurationSetting}. - * + *

* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and * {@link SecretReferenceConfigurationSetting}. * @@ -995,7 +992,6 @@ public Response setReadOnlyWithResponse(ConfigurationSetti validateSetting(setting); final String key = setting.getKey(); final String label = setting.getLabel(); - context = enableSyncRestProxy(addTracingNamespace(context)); return isReadOnly ? toConfigurationSettingWithResponse(serviceClient.putLockWithResponse(key, label, null, null, context)) @@ -1061,34 +1057,21 @@ public PagedIterable listConfigurationSettings(SettingSele final List settingFields = selector == null ? null : toSettingFieldsList(selector.getFields()); final List matchConditionsList = selector == null ? null : selector.getMatchConditions(); AtomicInteger pageETagIndex = new AtomicInteger(0); - return new PagedIterable<>( - () -> { - PagedResponse pagedResponse; - try { - pagedResponse = serviceClient.getKeyValuesSinglePage( - keyFilter, - labelFilter, - null, - acceptDateTime, - settingFields, - null, - null, - getPageETag(matchConditionsList, pageETagIndex), - enableSyncRestProxy(addTracingNamespace(context))); - } catch (HttpResponseException ex) { - return handleNotModifiedErrorToValidResponse(ex, LOGGER); - } - return toConfigurationSettingWithPagedResponse(pagedResponse); - }, + return new PagedIterable<>(() -> { + PagedResponse pagedResponse; + try { + pagedResponse = serviceClient.getKeyValuesSinglePage(keyFilter, labelFilter, null, acceptDateTime, + settingFields, null, null, getPageETag(matchConditionsList, pageETagIndex), context); + } catch (HttpResponseException ex) { + return handleNotModifiedErrorToValidResponse(ex, LOGGER); + } + return toConfigurationSettingWithPagedResponse(pagedResponse); + }, nextLink -> { PagedResponse pagedResponse; try { - pagedResponse = serviceClient.getKeyValuesNextSinglePage( - nextLink, - acceptDateTime, - null, - getPageETag(matchConditionsList, pageETagIndex), - enableSyncRestProxy(addTracingNamespace(context))); + pagedResponse = serviceClient.getKeyValuesNextSinglePage(nextLink, acceptDateTime, null, + getPageETag(matchConditionsList, pageETagIndex), context); } catch (HttpResponseException ex) { return handleNotModifiedErrorToValidResponse(ex, LOGGER); } @@ -1152,28 +1135,16 @@ public PagedIterable listConfigurationSettingsForSnapshot( */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listConfigurationSettingsForSnapshot(String snapshotName, - List fields, - Context context) { - return new PagedIterable<>( - () -> { - final PagedResponse pagedResponse = serviceClient.getKeyValuesSinglePage( - null, - null, - null, - null, - fields, - snapshotName, - null, - null, - enableSyncRestProxy(addTracingNamespace(context))); - return toConfigurationSettingWithPagedResponse(pagedResponse); - }, - nextLink -> { - final PagedResponse pagedResponse = serviceClient.getKeyValuesNextSinglePage(nextLink, - null, null, null, enableSyncRestProxy(addTracingNamespace(context))); - return toConfigurationSettingWithPagedResponse(pagedResponse); - } - ); + List fields, Context context) { + return new PagedIterable<>(() -> { + final PagedResponse pagedResponse = serviceClient.getKeyValuesSinglePage(null, null, null, null, + fields, snapshotName, null, null, context); + return toConfigurationSettingWithPagedResponse(pagedResponse); + }, nextLink -> { + final PagedResponse pagedResponse = serviceClient.getKeyValuesNextSinglePage(nextLink, null, null, + null, context); + return toConfigurationSettingWithPagedResponse(pagedResponse); + }); } /** @@ -1181,8 +1152,7 @@ public PagedIterable listConfigurationSettingsForSnapshot( * in descending order from their {@link ConfigurationSetting#getLastModified() lastModified} date. * Revisions expire after a period of time, see Pricing * for more information. - * - * + *

* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code selector}. * @@ -1217,7 +1187,7 @@ public PagedIterable listRevisions(SettingSelector selecto * in descending order from their {@link ConfigurationSetting#getLastModified() lastModified} date. * Revisions expire after a period of time, see Pricing * for more information. - * + *

* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code selector}. * @@ -1243,23 +1213,16 @@ public PagedIterable listRevisions(SettingSelector selecto @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listRevisions(SettingSelector selector, Context context) { final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime(); - return new PagedIterable<>( - () -> { - final PagedResponse pagedResponse = serviceClient.getRevisionsSinglePage( - selector == null ? null : selector.getKeyFilter(), - selector == null ? null : selector.getLabelFilter(), - null, - acceptDateTime, - selector == null ? null : toSettingFieldsList(selector.getFields()), - enableSyncRestProxy(addTracingNamespace(context))); - return toConfigurationSettingWithPagedResponse(pagedResponse); - }, - nextLink -> { - final PagedResponse pagedResponse = serviceClient.getRevisionsNextSinglePage(nextLink, - acceptDateTime, enableSyncRestProxy(addTracingNamespace(context))); - return toConfigurationSettingWithPagedResponse(pagedResponse); - } - ); + return new PagedIterable<>(() -> { + final PagedResponse pagedResponse = serviceClient.getRevisionsSinglePage( + selector == null ? null : selector.getKeyFilter(), selector == null ? null : selector.getLabelFilter(), + null, acceptDateTime, selector == null ? null : toSettingFieldsList(selector.getFields()), context); + return toConfigurationSettingWithPagedResponse(pagedResponse); + }, nextLink -> { + final PagedResponse pagedResponse = serviceClient.getRevisionsNextSinglePage(nextLink, + acceptDateTime, context); + return toConfigurationSettingWithPagedResponse(pagedResponse); + }); } /** @@ -1525,15 +1488,10 @@ public PagedIterable listSnapshots(SnapshotSelector selec */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listSnapshots(SnapshotSelector selector, Context context) { - return new PagedIterable<>( - () -> serviceClient.getSnapshotsSinglePage( - selector == null ? null : selector.getNameFilter(), - null, - selector == null ? null : selector.getFields(), - selector == null ? null : selector.getStatus(), - enableSyncRestProxy(addTracingNamespace(context))), - nextLink -> serviceClient.getSnapshotsNextSinglePage(nextLink, - enableSyncRestProxy(addTracingNamespace(context)))); + return new PagedIterable<>(() -> serviceClient.getSnapshotsSinglePage( + selector == null ? null : selector.getNameFilter(), null, selector == null ? null : selector.getFields(), + selector == null ? null : selector.getStatus(), context), + nextLink -> serviceClient.getSnapshotsNextSinglePage(nextLink, context)); } /** diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java index a743a01d56bc..489a1b35b7d3 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java @@ -12,6 +12,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpClient; import com.azure.core.http.HttpHeader; +import com.azure.core.http.HttpHeaderName; import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; @@ -126,8 +127,8 @@ public final class ConfigurationClientBuilder implements CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .set("x-ms-return-client-request-id", "true") - .set("Content-Type", "application/json") - .set("Accept", "application/vnd.microsoft.azconfig.kv+json")); + .set(HttpHeaderName.CONTENT_TYPE, "application/json") + .set(HttpHeaderName.ACCEPT, "application/vnd.microsoft.azconfig.kv+json")); } private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class); diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/implementation/Utility.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/implementation/Utility.java index 5bc1cca355d7..f40318800e33 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/implementation/Utility.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/implementation/Utility.java @@ -13,6 +13,7 @@ import com.azure.core.http.rest.ResponseBase; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.data.appconfiguration.implementation.models.KeyValue; import com.azure.data.appconfiguration.implementation.models.SnapshotUpdateParameters; @@ -24,19 +25,15 @@ import reactor.core.publisher.Mono; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; -import static com.azure.core.util.tracing.Tracer.AZ_TRACING_NAMESPACE_KEY; - /** * App Configuration Utility methods, use internally. */ public class Utility { - private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; - public static final String APP_CONFIG_TRACING_NAMESPACE_VALUE = "Microsoft.AppConfiguration"; - public static final String ID = "id"; public static final String DESCRIPTION = "description"; public static final String DISPLAY_NAME = "display_name"; @@ -67,36 +64,9 @@ public static KeyValue toKeyValue(ConfigurationSetting setting) { .setTags(setting.getTags()); } - // List to SettingFields[] - public static SettingFields[] toSettingFieldsArray(List settingFieldsList) { - int size = settingFieldsList.size(); - SettingFields[] fields = new SettingFields[size]; - for (int i = 0; i < size; i++) { - fields[i] = settingFieldsList.get(i); - } - return fields; - } - // SettingFields[] to List public static List toSettingFieldsList(SettingFields[] settingFieldsArray) { - int size = settingFieldsArray.length; - List settingFieldsList = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - settingFieldsList.add(settingFieldsArray[i]); - } - return settingFieldsList; - } - - // Iterable to List - public static List iterableToList(Iterable iterable) { - if (iterable == null) { - return null; - } - List outputList = new ArrayList<>(); - for (E item : iterable) { - outputList.add(item); - } - return outputList; + return new ArrayList<>(Arrays.asList(settingFieldsArray)); } /* @@ -117,14 +87,6 @@ public static String getETag(boolean isETagRequired, ConfigurationSetting settin return isETagRequired ? getETagValue(setting.getETag()) : null; } - public static String getETagSnapshot(boolean isETagRequired, ConfigurationSnapshot snapshot) { - if (!isETagRequired) { - return null; - } - Objects.requireNonNull(snapshot); - return getETagValue(snapshot.getETag()); - } - /* * Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL. */ @@ -149,24 +111,6 @@ public static Mono validateSettingAsync(ConfigurationSetti return Mono.just(setting); } - /** - * Enable the sync stack rest proxy. - * - * @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies. - * Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null. - * - * @return The Context. - */ - public static Context enableSyncRestProxy(Context context) { - context = context == null ? Context.NONE : context; - return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true); - } - - public static Context addTracingNamespace(Context context) { - context = context == null ? Context.NONE : context; - return context.addData(AZ_TRACING_NAMESPACE_KEY, APP_CONFIG_TRACING_NAMESPACE_VALUE); - } - public static Response updateSnapshotSync(String snapshotName, MatchConditions matchConditions, ConfigurationSnapshotStatus status, AzureAppConfigurationImpl serviceClient, Context context) { @@ -203,44 +147,44 @@ public static String parseNextLink(String nextLink) { // Async handler public static Mono> handleNotModifiedErrorToValidResponse(HttpResponseException error) { HttpResponse httpResponse = error.getResponse(); + if (httpResponse == null) { + return Mono.error(error); + } + String continuationToken = parseNextLink(httpResponse.getHeaderValue(HttpHeaderName.LINK)); if (httpResponse.getStatusCode() == 304) { - return Mono.just( - new PagedResponseBase<>( - httpResponse.getRequest(), - httpResponse.getStatusCode(), - httpResponse.getHeaders(), - null, - continuationToken, - null)); + return Mono.just(new PagedResponseBase<>(httpResponse.getRequest(), httpResponse.getStatusCode(), + httpResponse.getHeaders(), null, continuationToken, null)); } + return Mono.error(error); } // Sync Handler public static PagedResponse handleNotModifiedErrorToValidResponse(HttpResponseException error, ClientLogger logger) { HttpResponse httpResponse = error.getResponse(); + if (httpResponse == null) { + throw logger.logExceptionAsError(error); + } + String continuationToken = parseNextLink(httpResponse.getHeaderValue(HttpHeaderName.LINK)); if (httpResponse.getStatusCode() == 304) { - return new PagedResponseBase<>( - httpResponse.getRequest(), - httpResponse.getStatusCode(), - httpResponse.getHeaders(), - null, - continuationToken, - null); + return new PagedResponseBase<>(httpResponse.getRequest(), httpResponse.getStatusCode(), + httpResponse.getHeaders(), null, continuationToken, null); } + throw logger.logExceptionAsError(error); } // Get the ETag from a list public static String getPageETag(List matchConditionsList, AtomicInteger pageETagIndex) { - int pageETagListSize = (matchConditionsList == null || matchConditionsList.isEmpty()) - ? 0 - : matchConditionsList.size(); + if (CoreUtils.isNullOrEmpty(matchConditionsList)) { + return null; + } + String nextPageETag = null; int pageETagIndexValue = pageETagIndex.get(); - if (pageETagIndexValue < pageETagListSize) { + if (pageETagIndexValue < matchConditionsList.size()) { nextPageETag = matchConditionsList.get(pageETagIndexValue).getIfNoneMatch(); pageETagIndex.set(pageETagIndexValue + 1); } diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientTest.java b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientTest.java index 3d0c3e5a491e..744dddcf1bee 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientTest.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientTest.java @@ -777,15 +777,11 @@ public void listConfigurationSettingsAcceptDateTime(HttpClient httpClient, Confi final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); // Create 3 revisions of the same key. - try { - assertConfigurationEquals(original, client.setConfigurationSettingWithResponse(original, false, Context.NONE).getValue()); - Thread.sleep(2000); - assertConfigurationEquals(updated, client.setConfigurationSettingWithResponse(updated, false, Context.NONE).getValue()); - Thread.sleep(2000); - assertConfigurationEquals(updated2, client.setConfigurationSettingWithResponse(updated2, false, Context.NONE).getValue()); - } catch (InterruptedException ex) { - // Do nothing. - } + assertConfigurationEquals(original, client.setConfigurationSettingWithResponse(original, false, Context.NONE).getValue()); + sleepIfRunningAgainstService(2000); + assertConfigurationEquals(updated, client.setConfigurationSettingWithResponse(updated, false, Context.NONE).getValue()); + sleepIfRunningAgainstService(2000); + assertConfigurationEquals(updated2, client.setConfigurationSettingWithResponse(updated2, false, Context.NONE).getValue()); // Gets all versions of this value so we can get the one we want at that particular date. List revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).stream().collect(Collectors.toList()); @@ -886,15 +882,11 @@ public void listRevisionsAcceptDateTime(HttpClient httpClient, ConfigurationServ final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); // Create 3 revisions of the same key. - try { - assertConfigurationEquals(original, client.setConfigurationSettingWithResponse(original, false, Context.NONE).getValue()); - Thread.sleep(2000); - assertConfigurationEquals(updated, client.setConfigurationSettingWithResponse(updated, false, Context.NONE).getValue()); - Thread.sleep(2000); - assertConfigurationEquals(updated2, client.setConfigurationSettingWithResponse(updated2, false, Context.NONE).getValue()); - } catch (InterruptedException ex) { - // Do nothing. - } + assertConfigurationEquals(original, client.setConfigurationSettingWithResponse(original, false, Context.NONE).getValue()); + sleepIfRunningAgainstService(2000); + assertConfigurationEquals(updated, client.setConfigurationSettingWithResponse(updated, false, Context.NONE).getValue()); + sleepIfRunningAgainstService(2000); + assertConfigurationEquals(updated2, client.setConfigurationSettingWithResponse(updated2, false, Context.NONE).getValue()); // Gets all versions of this value. List revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).stream().collect(Collectors.toList()); diff --git a/sdk/attestation/azure-security-attestation/src/test/java/com/azure/security/attestation/AttestationTest.java b/sdk/attestation/azure-security-attestation/src/test/java/com/azure/security/attestation/AttestationTest.java index 21c89af0fc57..0dada17dbdf1 100644 --- a/sdk/attestation/azure-security-attestation/src/test/java/com/azure/security/attestation/AttestationTest.java +++ b/sdk/attestation/azure-security-attestation/src/test/java/com/azure/security/attestation/AttestationTest.java @@ -9,6 +9,7 @@ import com.azure.core.test.utils.TestUtils; import com.azure.core.util.BinaryData; import com.azure.core.util.Context; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.serializer.SerializerEncoding; import com.azure.security.attestation.models.AttestationData; import com.azure.security.attestation.models.AttestationDataInterpretation; @@ -354,7 +355,8 @@ void testTpmAttestation(HttpClient httpClient, String clientUri) { .setAttestationSigner(new AttestationSigningKey(getIsolatedSigningCertificate(), getIsolatedSigningKey()))); if (result.getPolicyResolution() != PolicyModification.UPDATED) { - System.out.printf("Unexpected resolution setting TPM policy: %s", result.getPolicyResolution().toString()); + LOGGER.log(LogLevel.VERBOSE, + () -> "Unexpected resolution setting TPM policy: " + result.getPolicyResolution()); return; } @@ -373,11 +375,11 @@ void testTpmAttestation(HttpClient httpClient, String clientUri) { Object deserializedResponse = assertDoesNotThrow(() -> ADAPTER.deserialize(tpmResponse.getTpmResult().toBytes(), Object.class, SerializerEncoding.JSON)); - assertTrue(deserializedResponse instanceof LinkedHashMap); + assertInstanceOf(LinkedHashMap.class, deserializedResponse); @SuppressWarnings("unchecked") LinkedHashMap initialResponse = (LinkedHashMap) deserializedResponse; assertTrue(initialResponse.containsKey("payload")); - assertTrue(initialResponse.get("payload") instanceof LinkedHashMap); + assertInstanceOf(LinkedHashMap.class, initialResponse.get("payload")); @SuppressWarnings("unchecked") LinkedHashMap payload = (LinkedHashMap) initialResponse.get("payload"); assertTrue(payload.containsKey("challenge")); @@ -402,7 +404,8 @@ void testTpmAttestationWithResult(HttpClient httpClient, String clientUri) { .setAttestationSigner(new AttestationSigningKey(getIsolatedSigningCertificate(), getIsolatedSigningKey()))); if (result.getPolicyResolution() != PolicyModification.UPDATED) { - System.out.printf("Unexpected resolution setting TPM policy: %s", result.getPolicyResolution().toString()); + LOGGER.log(LogLevel.VERBOSE, + () -> "Unexpected resolution setting TPM policy: " + result.getPolicyResolution()); return; } @@ -423,11 +426,11 @@ void testTpmAttestationWithResult(HttpClient httpClient, String clientUri) { Object deserializedResponse = assertDoesNotThrow(() -> ADAPTER.deserialize( tpmResponse.getValue().getTpmResult().toBytes(), Object.class, SerializerEncoding.JSON)); - assertTrue(deserializedResponse instanceof LinkedHashMap); + assertInstanceOf(LinkedHashMap.class, deserializedResponse); @SuppressWarnings("unchecked") LinkedHashMap initialResponse = (LinkedHashMap) deserializedResponse; assertTrue(initialResponse.containsKey("payload")); - assertTrue(initialResponse.get("payload") instanceof LinkedHashMap); + assertInstanceOf(LinkedHashMap.class, initialResponse.get("payload")); @SuppressWarnings("unchecked") LinkedHashMap payload = (LinkedHashMap) initialResponse.get("payload"); assertTrue(payload.containsKey("challenge")); @@ -450,7 +453,8 @@ void testTpmAttestationAsync(HttpClient httpClient, String clientUri) { .setAttestationSigner(new AttestationSigningKey(getIsolatedSigningCertificate(), getIsolatedSigningKey()))); if (result.getPolicyResolution() != PolicyModification.UPDATED) { - System.out.printf("Unexpected resolution setting TPM policy: %s", result.getPolicyResolution().toString()); + LOGGER.log(LogLevel.VERBOSE, + () -> "Unexpected resolution setting TPM policy: " + result.getPolicyResolution()); return; } @@ -469,11 +473,11 @@ void testTpmAttestationAsync(HttpClient httpClient, String clientUri) { .assertNext(tpmResponse -> { Object deserializedResponse = assertDoesNotThrow(() -> ADAPTER.deserialize( tpmResponse.getTpmResult().toBytes(), Object.class, SerializerEncoding.JSON)); - assertTrue(deserializedResponse instanceof LinkedHashMap); + assertInstanceOf(LinkedHashMap.class, deserializedResponse); @SuppressWarnings("unchecked") LinkedHashMap initialResponse = (LinkedHashMap) deserializedResponse; assertTrue(initialResponse.containsKey("payload")); - assertTrue(initialResponse.get("payload") instanceof LinkedHashMap); + assertInstanceOf(LinkedHashMap.class, initialResponse.get("payload")); @SuppressWarnings("unchecked") LinkedHashMap payload = (LinkedHashMap) initialResponse.get("payload"); assertTrue(payload.containsKey("challenge")); @@ -669,7 +673,7 @@ private static void verifyAttestationResult(TestMode testMode, String clientUri, assertNull(result.getNonce()); if (expectJson) { - assertTrue(result.getRuntimeClaims() instanceof Map); + assertInstanceOf(Map.class, result.getRuntimeClaims()); @SuppressWarnings("unchecked") Map runtimeClaims = (Map) result.getRuntimeClaims(); Map expectedClaims = assertDoesNotThrow(() -> @@ -685,7 +689,7 @@ static void assertObjectEqual(Map expected, Map LOGGER.verbose("Key: " + key); assertTrue(actual.containsKey(key)); if (expected.get(key) instanceof Map) { - assertTrue(actual.get(key) instanceof Map); + assertInstanceOf(Map.class, actual.get(key)); @SuppressWarnings("unchecked") Map expectedInner = (Map) expected.get(key); @SuppressWarnings("unchecked") diff --git a/sdk/boms/spring-cloud-azure-dependencies/pom.xml b/sdk/boms/spring-cloud-azure-dependencies/pom.xml index 01737e7633d1..cbb7b2fd5ae8 100644 --- a/sdk/boms/spring-cloud-azure-dependencies/pom.xml +++ b/sdk/boms/spring-cloud-azure-dependencies/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-dependencies - 4.18.0-beta.1 + 4.19.0-beta.1 pom Spring Cloud Azure Dependencies @@ -51,14 +51,14 @@ com.azure azure-sdk-bom - 1.2.22 + 1.2.23 pom import com.azure azure-spring-data-cosmos - 3.45.0-beta.1 + 3.46.0-beta.1 com.azure.resourcemanager diff --git a/sdk/communication/azure-communication-callautomation/pom.xml b/sdk/communication/azure-communication-callautomation/pom.xml index 32b5e27eb7b8..722ac6b09f44 100644 --- a/sdk/communication/azure-communication-callautomation/pom.xml +++ b/sdk/communication/azure-communication-callautomation/pom.xml @@ -71,7 +71,7 @@ com.azure azure-messaging-servicebus - 7.16.0 + 7.17.0 test diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationAsyncClientAutomatedLiveTests.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationAsyncClientAutomatedLiveTests.java index 31efad130aa1..27e11915f67f 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationAsyncClientAutomatedLiveTests.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationAsyncClientAutomatedLiveTests.java @@ -17,6 +17,7 @@ import com.azure.communication.identity.CommunicationIdentityAsyncClient; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.Response; +import com.azure.core.test.annotation.DoNotRecord; import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -32,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.fail; public class CallAutomationAsyncClientAutomatedLiveTests extends CallAutomationAutomatedLiveTestBase { + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( @@ -132,6 +134,7 @@ public void createVOIPCallAndAnswerThenHangupAutomatedTest(HttpClient httpClient } } + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationAutomatedLiveTestBase.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationAutomatedLiveTestBase.java index 500d2108a25c..a7a831b0b173 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationAutomatedLiveTestBase.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationAutomatedLiveTestBase.java @@ -8,28 +8,27 @@ import com.azure.communication.callautomation.models.events.CallAutomationEventBase; import com.azure.communication.common.CommunicationIdentifier; import com.azure.core.amqp.AmqpTransportType; +import com.azure.core.http.HttpClient; import com.azure.core.http.HttpMethod; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; import com.azure.core.test.TestMode; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.servicebus.ServiceBusClientBuilder; import com.azure.messaging.servicebus.ServiceBusErrorContext; import com.azure.messaging.servicebus.ServiceBusException; import com.azure.messaging.servicebus.ServiceBusFailureReason; import com.azure.messaging.servicebus.ServiceBusProcessorClient; -import com.azure.core.http.HttpClient; import com.azure.messaging.servicebus.ServiceBusReceivedMessage; import com.azure.messaging.servicebus.ServiceBusReceivedMessageContext; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.azure.core.util.CoreUtils; -import java.util.StringJoiner; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; @@ -39,11 +38,15 @@ import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import java.util.StringJoiner; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class CallAutomationAutomatedLiveTestBase extends CallAutomationLiveTestBase { + private static final ClientLogger LOGGER = new ClientLogger(CallAutomationAutomatedLiveTestBase.class); + protected ConcurrentHashMap processorStore; // Key: callerId + receiverId, Value: incomingCallContext protected ConcurrentHashMap incomingCallContextStore; @@ -60,7 +63,7 @@ public class CallAutomationAutomatedLiveTestBase extends CallAutomationLiveTestB protected static final String BOT_APP_ID = Configuration.getGlobalConfiguration() .get("BOT_APP_ID", "REDACTED-bedb-REDACTED-b8c6-REDACTED"); - private static final StringJoiner JSON_PROPERTIES_TO_REDACT + private static final StringJoiner JSON_PROPERTIES_TO_REDACT = new StringJoiner("\":\"|\"", "\"", "\":\"") .add("value") .add("rawId") @@ -70,11 +73,11 @@ public class CallAutomationAutomatedLiveTestBase extends CallAutomationLiveTestB .add("ivrContext") .add("incomingCallContext") .add("serverCallId"); - + protected static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN = Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"})", JSON_PROPERTIES_TO_REDACT), Pattern.CASE_INSENSITIVE); - + protected static final String URL_REGEX = "(?<=http:\\/\\/|https:\\/\\/)([^\\/?]+)"; @Override @@ -206,11 +209,12 @@ private void messageBodyHandler(String body) { } protected void errorHandler(ServiceBusErrorContext context, CountDownLatch countdownLatch) { - System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'%n", - context.getFullyQualifiedNamespace(), context.getEntityPath()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error when receiving messages from namespace: '%s'. Entity: '%s'%n", + context.getFullyQualifiedNamespace(), context.getEntityPath())); if (!(context.getException() instanceof ServiceBusException)) { - System.out.printf("Non-ServiceBusException occurred: %s%n", context.getException()); + LOGGER.log(LogLevel.VERBOSE, () -> "Non-ServiceBusException occurred: " + context.getException()); return; } @@ -220,22 +224,20 @@ protected void errorHandler(ServiceBusErrorContext context, CountDownLatch count if (reason == ServiceBusFailureReason.MESSAGING_ENTITY_DISABLED || reason == ServiceBusFailureReason.MESSAGING_ENTITY_NOT_FOUND || reason == ServiceBusFailureReason.UNAUTHORIZED) { - System.out.printf("An unrecoverable error occurred. Stopping processing with reason %s: %s%n", - reason, exception.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "An unrecoverable error occurred. Stopping processing with reason %s: %s%n", + reason, exception.getMessage())); countdownLatch.countDown(); } else if (reason == ServiceBusFailureReason.MESSAGE_LOCK_LOST) { - System.out.printf("Message lock lost for message: %s%n", context.getException()); + LOGGER.log(LogLevel.VERBOSE, + () -> String.format("Message lock lost for message: %s%n", context.getException())); } else if (reason == ServiceBusFailureReason.SERVICE_BUSY) { - try { - // Choosing an arbitrary amount of time to wait until trying again. - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - System.err.println("Unable to sleep for period of time"); - } + // Choosing an arbitrary amount of time to wait until trying again. + sleepIfRunningAgainstService(1000); } else { - System.out.printf("Error source %s, reason %s, message: %s%n", context.getErrorSource(), - reason, context.getException()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format("Error source %s, reason %s, message: %s%n", + context.getErrorSource(), reason, context.getException())); } } @@ -260,7 +262,7 @@ protected String waitForIncomingCallContext(String uniqueId, Duration timeOut) t if (incomingCallContext != null) { return incomingCallContext; } - Thread.sleep(1000); + sleepIfRunningAgainstService(1000); } return null; } @@ -275,11 +277,11 @@ protected T waitForEvent(Class eventType, return event; } } - Thread.sleep(1000); + sleepIfRunningAgainstService(1000); } return null; } - + protected String redact(String content, Matcher matcher) { while (matcher.find()) { String captureGroup = matcher.group(1); diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationLiveTestBase.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationLiveTestBase.java index fbd9a81bd697..ca45f40b8eba 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationLiveTestBase.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationLiveTestBase.java @@ -62,17 +62,17 @@ public class CallAutomationLiveTestBase extends TestProxyTestBase { protected static final String MEDIA_SOURCE = Configuration.getGlobalConfiguration() .get("ACS_MEDIA_SOURCE", "https://contoso.com/music.wav"); protected static final String URL_REGEX = "(?<=http:\\/\\/|https:\\/\\/)([^\\/?]+)"; - + protected CommunicationIdentityClientBuilder getCommunicationIdentityClientUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder() .connectionString(CONNECTION_STRING) .httpClient(getHttpClientOrUsePlayback(httpClient)); - + if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); - + return builder; } @@ -88,12 +88,12 @@ protected CallAutomationClientBuilder getCallAutomationClientUsingConnectionStri .connectionString(CONNECTION_STRING) .httpClient(getHttpClientOrUsePlayback(httpClient)); } - + if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); - + return builder; } @@ -137,12 +137,6 @@ protected Mono logHeaders(String testName, HttpPipelineNextPolicy }); } - protected void waitForOperationCompletion(int milliSeconds) throws InterruptedException { - if (getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(milliSeconds); - } - } - static class FakeCredentials implements TokenCredential { @Override public Mono getToken(TokenRequestContext tokenRequestContext) { @@ -159,15 +153,15 @@ protected String redact(String content, Matcher matcher) { } return content; } - + protected void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { - + if (interceptorManager.isLiveMode()) { return; } List customSanitizers = new ArrayList<>(); - + customSanitizers.add(new TestProxySanitizer("Authorization", null, "REDACTED", TestProxySanitizerType.HEADER)); customSanitizers.add(new TestProxySanitizer("x-ms-client-request-id", null, "REDACTED", TestProxySanitizerType.HEADER)); customSanitizers.add(new TestProxySanitizer("x-ms-content-sha256", null, "REDACTED", TestProxySanitizerType.HEADER)); @@ -187,7 +181,7 @@ protected void addTestProxyTestSanitizersAndMatchers(InterceptorManager intercep customSanitizers.add(new TestProxySanitizer("$..mediaSubscriptionId", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..dataSubscriptionId", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URL_REGEX, "REDACTED", TestProxySanitizerType.BODY_REGEX)); - + interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallConnectionAsyncAutomatedLiveTests.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallConnectionAsyncAutomatedLiveTests.java index c807992bf2a3..69662ce92337 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallConnectionAsyncAutomatedLiveTests.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallConnectionAsyncAutomatedLiveTests.java @@ -15,14 +15,14 @@ import com.azure.communication.callautomation.models.RemoveParticipantResult; import com.azure.communication.callautomation.models.events.AddParticipantSucceeded; import com.azure.communication.callautomation.models.events.CallConnected; -import com.azure.communication.callautomation.models.events.RemoveParticipantSucceeded; import com.azure.communication.callautomation.models.events.CancelAddParticipantSucceeded; +import com.azure.communication.callautomation.models.events.RemoveParticipantSucceeded; import com.azure.communication.common.CommunicationIdentifier; import com.azure.communication.common.CommunicationUserIdentifier; import com.azure.communication.identity.CommunicationIdentityAsyncClient; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.Response; - +import com.azure.core.test.annotation.DoNotRecord; import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -39,6 +39,7 @@ public class CallConnectionAsyncAutomatedLiveTests extends CallAutomationAutomatedLiveTestBase { + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( @@ -157,6 +158,7 @@ public void createVOIPCallAndAnswerThenAddParticipantFinallyRemoveParticipantAut } } + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( @@ -232,7 +234,7 @@ public void createVOIPCallAndAnswerThenAddParticipantFinallyCancelAddParticipant assertNotNull(addParticipantsResultResponse); // ensure invitation is sent - Thread.sleep(3000); + sleepIfRunningAgainstService(3000); // cancel add participant CancelAddParticipantOperationResult cancelAddParticipantResponse = createCallResult diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallDialogAsyncAutomatedLiveTests.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallDialogAsyncAutomatedLiveTests.java index c12f8a6f6e83..4dac2c5d8b31 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallDialogAsyncAutomatedLiveTests.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallDialogAsyncAutomatedLiveTests.java @@ -12,6 +12,7 @@ import com.azure.communication.identity.CommunicationIdentityAsyncClient; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.Response; +import com.azure.core.test.annotation.DoNotRecord; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable; @@ -25,6 +26,7 @@ public class CallDialogAsyncAutomatedLiveTests extends CallAutomationAutomatedLiveTestBase { + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallMediaAsyncAutomatedLiveTests.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallMediaAsyncAutomatedLiveTests.java index 60e5034b3d1d..a7d6c8f17887 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallMediaAsyncAutomatedLiveTests.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallMediaAsyncAutomatedLiveTests.java @@ -24,6 +24,7 @@ import com.azure.core.http.HttpClient; import com.azure.core.http.rest.Response; import com.azure.core.test.TestMode; +import com.azure.core.test.annotation.DoNotRecord; import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable; import org.junit.jupiter.params.ParameterizedTest; @@ -42,6 +43,7 @@ public class CallMediaAsyncAutomatedLiveTests extends CallAutomationAutomatedLiveTestBase { + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( @@ -128,6 +130,7 @@ public void playMediaInACallAutomatedTest(HttpClient httpClient) { } } + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingAutomatedLiveTests.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingAutomatedLiveTests.java index 98e6ee049631..8187e92aaef8 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingAutomatedLiveTests.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingAutomatedLiveTests.java @@ -21,6 +21,7 @@ import com.azure.communication.common.CommunicationUserIdentifier; import com.azure.communication.identity.CommunicationIdentityClient; import com.azure.core.http.HttpClient; +import com.azure.core.test.annotation.DoNotRecord; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -34,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.fail; public class CallRecordingAutomatedLiveTests extends CallAutomationAutomatedLiveTestBase { + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") public void createACSCallAndUnmixedAudioTest(HttpClient httpClient) { @@ -118,6 +120,7 @@ public void createACSCallAndUnmixedAudioTest(HttpClient httpClient) { } } + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") public void createACSCallUnmixedAudioAffinityTest(HttpClient httpClient) { diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createACSCallAndUnmixedAudioTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createACSCallAndUnmixedAudioTest.json deleted file mode 100644 index 41689d777012..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createACSCallAndUnmixedAudioTest.json +++ /dev/null @@ -1 +0,0 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"802fc64d-4d4e-4280-be90-228202784cd6\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-d9b1-40b6-805b-56cef20d7f13\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"802fc64d-4d4e-4280-be90-228202784cd6\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:17:14.5301986\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-d9b1-40b6-805b-56cef20d7f13\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"802fc64d-4d4e-4280-be90-228202784cd6\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:17:14.5301986\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-d9b1-40b6-805b-56cef20d7f13\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"802fc64d-4d4e-4280-be90-228202784cd6\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:17:19.8119571\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-d9b1-40b6-805b-56cef20d7f13\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"802fc64d-4d4e-4280-be90-228202784cd6\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-04-24T19:17:20.2182933\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-d9b1-40b6-805b-56cef20d7f13\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createACSCallUnmixedAudioAffinityTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createACSCallUnmixedAudioAffinityTest.json deleted file mode 100644 index 3b6fc1e33a39..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createACSCallUnmixedAudioAffinityTest.json +++ /dev/null @@ -1 +0,0 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"54f85e11-3105-433f-aac8-19cf1df95d36\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-78fd-4327-bf24-44ec170f86cd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54f85e11-3105-433f-aac8-19cf1df95d36\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:17:26.4688368\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-78fd-4327-bf24-44ec170f86cd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54f85e11-3105-433f-aac8-19cf1df95d36\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:17:26.4688368\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-78fd-4327-bf24-44ec170f86cd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54f85e11-3105-433f-aac8-19cf1df95d36\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:17:30.9536716\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-78fd-4327-bf24-44ec170f86cd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54f85e11-3105-433f-aac8-19cf1df95d36\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-04-24T19:17:31.3599728\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-78fd-4327-bf24-44ec170f86cd\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenAddParticipantFinallyCancelAddParticipant.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenAddParticipantFinallyCancelAddParticipant.json deleted file mode 100644 index 8bc5f1f63488..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenAddParticipantFinallyCancelAddParticipant.json +++ /dev/null @@ -1 +0,0 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"7d16dfce-c0c5-490d-8105-7debd7893a32\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-cbad-484c-bcde-27c5edc765db\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d16dfce-c0c5-490d-8105-7debd7893a32\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:37.484509\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-8ff1-4fe6-a575-d0e702b71497\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d16dfce-c0c5-490d-8105-7debd7893a32\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:37.5001327\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-8ff1-4fe6-a575-d0e702b71497\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d16dfce-c0c5-490d-8105-7debd7893a32\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:37.5157768\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-cbad-484c-bcde-27c5edc765db\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d16dfce-c0c5-490d-8105-7debd7893a32\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:37.5157768\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-8ff1-4fe6-a575-d0e702b71497\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d16dfce-c0c5-490d-8105-7debd7893a32\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:39.5471963\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-cbad-484c-bcde-27c5edc765db\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d16dfce-c0c5-490d-8105-7debd7893a32\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:39.5471963\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-cbad-484c-bcde-27c5edc765db\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\",\"type\":\"Microsoft.Communication.CancelAddParticipantSucceeded\",\"data\":{\"invitationId\":\"03b7d0e2-1d59-4f37-9fd1-f827d275eb59\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-8ff1-4fe6-a575-d0e702b71497\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d16dfce-c0c5-490d-8105-7debd7893a32\",\"publicEventType\":\"Microsoft.Communication.CancelAddParticipantSucceeded\"},\"time\":\"2024-04-24T19:16:41.2504076\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-8ff1-4fe6-a575-d0e702b71497\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenAddParticipantFinallyRemoveParticipantAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenAddParticipantFinallyRemoveParticipantAutomatedTest.json deleted file mode 100644 index cb7d3ec5caf6..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenAddParticipantFinallyRemoveParticipantAutomatedTest.json +++ /dev/null @@ -1 +0,0 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:23.5615833\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:23.6240133\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:23.6083905\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:23.6240133\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:26.4836617\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:26.5148471\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:28.2649797\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.AddParticipantSucceeded\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participant\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.AddParticipantSucceeded\"},\"time\":\"2024-04-24T19:16:28.358734\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:28.358734\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:28.358734\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:28.6244317\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:28.8431467\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:28.8431467\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":7,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:29.0931748\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:29.3119818\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:29.3119818\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":9,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:29.5775742\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-c9dd-4c59-b2b3-d50aaa67159f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-04-24T19:16:29.6557095\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-c9dd-4c59-b2b3-d50aaa67159f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":9,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:30.0464126\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.RemoveParticipantSucceeded\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participant\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.RemoveParticipantSucceeded\"},\"time\":\"2024-04-24T19:16:29.6557095\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":7,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:29.7807154\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":9,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:30.5151508\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:30.6089007\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":11,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-9ebd-43a1-95f7-92e9994edb3f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:30.9996063\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-9ebd-43a1-95f7-92e9994edb3f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":9,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-7b70-4bfd-b026-739e6c663e81\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"448c7527-7911-4149-b835-e49afb83a6bf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:31.1246381\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-7b70-4bfd-b026-739e6c663e81\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenHangupAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenHangupAutomatedTest.json deleted file mode 100644 index ecc6d9ed6c24..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndAnswerThenHangupAutomatedTest.json +++ /dev/null @@ -1 +0,0 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"b94e5319-f526-4538-aaef-6d59b28d3aa2\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-4f90-4199-9a2c-e07e3af80407\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b94e5319-f526-4538-aaef-6d59b28d3aa2\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:12.9357522\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b94e5319-f526-4538-aaef-6d59b28d3aa2\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:12.9670517\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b94e5319-f526-4538-aaef-6d59b28d3aa2\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:12.9984379\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-4f90-4199-9a2c-e07e3af80407\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b94e5319-f526-4538-aaef-6d59b28d3aa2\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:13.0451895\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-4f90-4199-9a2c-e07e3af80407\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b94e5319-f526-4538-aaef-6d59b28d3aa2\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-04-24T19:16:14.4514859\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-4f90-4199-9a2c-e07e3af80407\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-2077-4ee0-b8ac-017ad075c7bb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b94e5319-f526-4538-aaef-6d59b28d3aa2\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-04-24T19:16:14.529611\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-2077-4ee0-b8ac-017ad075c7bb\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndRejectAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndRejectAutomatedTest.json deleted file mode 100644 index b2a384ab4c74..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/createVOIPCallAndRejectAutomatedTest.json +++ /dev/null @@ -1 +0,0 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"5556ad81-73a7-4fa7-a5c7-b4b7d08a2001\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-c0ef-474b-8b58-ad685a4b1ce9\",\"type\":\"Microsoft.Communication.CreateCallFailed\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-c0ef-474b-8b58-ad685a4b1ce9\",\"resultInformation\":{\"code\":603,\"subCode\":0,\"message\":\"Decline. DiagCode: 603#0.@\"},\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-c0ef-474b-8b58-ad685a4b1ce9\",\"correlationId\":\"5556ad81-73a7-4fa7-a5c7-b4b7d08a2001\",\"publicEventType\":\"Microsoft.Communication.CreateCallFailed\"},\"time\":\"2024-04-24T19:16:06.0905745\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-c0ef-474b-8b58-ad685a4b1ce9\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/dialogActionInACallAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/dialogActionInACallAutomatedTest.json deleted file mode 100644 index 4647cc0dd9a7..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/dialogActionInACallAutomatedTest.json +++ /dev/null @@ -1 +0,0 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"41820b15-8dca-430f-b226-b3d26a3f80b5\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-688b-44d7-8081-1282028cdd97\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"41820b15-8dca-430f-b226-b3d26a3f80b5\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T18:28:31.0979781\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-688b-44d7-8081-1282028cdd97\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"41820b15-8dca-430f-b226-b3d26a3f80b5\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T18:28:31.1448558\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-3a6a-431c-8c4a-7c1f8b27f9f5\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-3a6a-431c-8c4a-7c1f8b27f9f5\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-3a6a-431c-8c4a-7c1f8b27f9f5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"41820b15-8dca-430f-b226-b3d26a3f80b5\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T18:28:31.1762164\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-3a6a-431c-8c4a-7c1f8b27f9f5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-3a6a-431c-8c4a-7c1f8b27f9f5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-3a6a-431c-8c4a-7c1f8b27f9f5\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-3a6a-431c-8c4a-7c1f8b27f9f5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"41820b15-8dca-430f-b226-b3d26a3f80b5\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T18:28:31.1762164\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-3a6a-431c-8c4a-7c1f8b27f9f5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\",\"type\":\"Microsoft.Communication.DialogFailed\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\",\"resultInformation\":{\"code\":500,\"subCode\":8595,\"message\":\"Action failed, missing bot config or app id.\"},\"dialogInputType\":\"powerVirtualAgents\",\"dialogId\":\"92e08834-b6ee-4ede-8956-9fefa27a691c\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-688b-44d7-8081-1282028cdd97\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"41820b15-8dca-430f-b226-b3d26a3f80b5\",\"publicEventType\":\"Microsoft.Communication.DialogFailed\"},\"time\":\"2024-04-24T18:28:33.2388006\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-688b-44d7-8081-1282028cdd97\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/dtmfActionsInACallAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/dtmfActionsInACallAutomatedTest.json deleted file mode 100644 index 63208076fd7d..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/dtmfActionsInACallAutomatedTest.json +++ /dev/null @@ -1 +0,0 @@ -["[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-09a1-4ad4-9320-4f2d89459535\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-09a1-4ad4-9320-4f2d89459535\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-09a1-4ad4-9320-4f2d89459535\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"892264d7-e380-44f1-88fd-7764e019664b\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-04-24T18:29:05.7916051\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-09a1-4ad4-9320-4f2d89459535\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-567b-47c2-93a4-546fa6997899\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-567b-47c2-93a4-546fa6997899\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-567b-47c2-93a4-546fa6997899\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"63ad2792-7c3d-497d-bbae-aa384c7a8f03\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-04-24T18:29:06.0572971\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-567b-47c2-93a4-546fa6997899\"}]","{\"to\":{\"kind\":\"phoneNumber\",\"rawId\":\"REDACTED\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"from\":{\"kind\":\"phoneNumber\",\"rawId\":\"REDACTED\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"1a14f457-e406-4aed-95b3-7e6259d23851\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-476a-4aed-ae4b-fb8657609c2f\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-476a-4aed-ae4b-fb8657609c2f\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-476a-4aed-ae4b-fb8657609c2f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"1a14f457-e406-4aed-95b3-7e6259d23851\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:50.3802422\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-476a-4aed-ae4b-fb8657609c2f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-476a-4aed-ae4b-fb8657609c2f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-476a-4aed-ae4b-fb8657609c2f\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"phoneNumber\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-476a-4aed-ae4b-fb8657609c2f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"1a14f457-e406-4aed-95b3-7e6259d23851\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:50.5365\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-476a-4aed-ae4b-fb8657609c2f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-e121-46d6-ab08-b468bd18edd5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"d6d82270-ed3c-49b0-aeb9-2a157ca1af60\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:16:50.6345661\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"phoneNumber\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-e121-46d6-ab08-b468bd18edd5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"d6d82270-ed3c-49b0-aeb9-2a157ca1af60\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:16:50.6345661\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\",\"type\":\"Microsoft.Communication.SendDtmfTonesCompleted\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-e121-46d6-ab08-b468bd18edd5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"d6d82270-ed3c-49b0-aeb9-2a157ca1af60\",\"publicEventType\":\"Microsoft.Communication.SendDtmfTonesCompleted\"},\"time\":\"2024-04-24T19:16:55.6194105\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\",\"type\":\"Microsoft.Communication.ContinuousDtmfRecognitionStopped\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-e121-46d6-ab08-b468bd18edd5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"d6d82270-ed3c-49b0-aeb9-2a157ca1af60\",\"publicEventType\":\"Microsoft.Communication.ContinuousDtmfRecognitionStopped\"},\"time\":\"2024-04-24T19:16:56.1352209\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-e121-46d6-ab08-b468bd18edd5\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/playMediaInACallAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/playMediaInACallAutomatedTest.json deleted file mode 100644 index ef82e3d66c80..000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/playMediaInACallAutomatedTest.json +++ /dev/null @@ -1 +0,0 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"ef73aa27-a842-4fb1-bdaa-3a46db20014e\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-b29e-4059-8f3c-f78434c99035\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef73aa27-a842-4fb1-bdaa-3a46db20014e\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:17:02.3387065\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-5e6f-47d8-bc89-5489b351cd37\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-5e6f-47d8-bc89-5489b351cd37\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-5e6f-47d8-bc89-5489b351cd37\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef73aa27-a842-4fb1-bdaa-3a46db20014e\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-04-24T19:17:02.307396\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-5e6f-47d8-bc89-5489b351cd37\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-5e6f-47d8-bc89-5489b351cd37\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-5e6f-47d8-bc89-5489b351cd37\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-5e6f-47d8-bc89-5489b351cd37\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef73aa27-a842-4fb1-bdaa-3a46db20014e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:17:02.3543277\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-5e6f-47d8-bc89-5489b351cd37\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-b29e-4059-8f3c-f78434c99035\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef73aa27-a842-4fb1-bdaa-3a46db20014e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-04-24T19:17:02.3543277\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"eventSource\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"451f3600-b29e-4059-8f3c-f78434c99035\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef73aa27-a842-4fb1-bdaa-3a46db20014e\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-04-24T19:17:08.357708\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/451f3600-b29e-4059-8f3c-f78434c99035\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callingserver/src/test/java/com/azure/communication/callingserver/CallAutomationLiveTestBase.java b/sdk/communication/azure-communication-callingserver/src/test/java/com/azure/communication/callingserver/CallAutomationLiveTestBase.java index e5cf3dc2817e..fbfb3defe424 100644 --- a/sdk/communication/azure-communication-callingserver/src/test/java/com/azure/communication/callingserver/CallAutomationLiveTestBase.java +++ b/sdk/communication/azure-communication-callingserver/src/test/java/com/azure/communication/callingserver/CallAutomationLiveTestBase.java @@ -13,6 +13,8 @@ import com.azure.core.test.TestMode; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.identity.DefaultAzureCredentialBuilder; import reactor.core.publisher.Mono; @@ -25,6 +27,8 @@ import java.util.regex.Pattern; public class CallAutomationLiveTestBase extends TestBase { + private static final ClientLogger LOGGER = new ClientLogger(CallAutomationLiveTestBase.class); + protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https://REDACTED.communication.azure.com/;accesskey=QWNjZXNzS2V5"); @@ -109,7 +113,7 @@ protected Mono logHeaders(String testName, HttpPipelineNextPolicy final HttpResponse bufferedResponse = httpResponse.buffer(); /* Should sanitize printed response url */ - System.out.println("Chain-ID header for " + testName + " request " + LOGGER.log(LogLevel.VERBOSE, () -> "Chain-ID header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("X-Microsoft-Skype-Chain-ID")); return Mono.just(bufferedResponse); diff --git a/sdk/communication/azure-communication-callingserver/src/test/java/com/azure/communication/callingserver/DownloadContentAsyncLiveTests.java b/sdk/communication/azure-communication-callingserver/src/test/java/com/azure/communication/callingserver/DownloadContentAsyncLiveTests.java index 4a397fa5a51f..732a8df93167 100644 --- a/sdk/communication/azure-communication-callingserver/src/test/java/com/azure/communication/callingserver/DownloadContentAsyncLiveTests.java +++ b/sdk/communication/azure-communication-callingserver/src/test/java/com/azure/communication/callingserver/DownloadContentAsyncLiveTests.java @@ -8,6 +8,8 @@ import com.azure.communication.callingserver.models.ParallelDownloadOptions; import com.azure.core.http.HttpClient; import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -31,6 +33,7 @@ import static org.mockito.Mockito.times; public class DownloadContentAsyncLiveTests extends CallAutomationLiveTestBase { + private static final ClientLogger LOGGER = new ClientLogger(DownloadContentAsyncLiveTests.class); @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @@ -61,7 +64,7 @@ private void downloadMetadata(CallAutomationAsyncClient conversationAsyncClient) try { validateMetadata(conversationAsyncClient.getCallRecordingAsync().downloadStream(METADATA_URL)); } catch (Exception e) { - System.out.println("Error: " + e.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> "Error", e); throw e; } } @@ -79,7 +82,7 @@ public void downloadMetadataRetryingAsync(HttpClient httpClient) { try { validateMetadata(conversationAsyncClient.getCallRecordingAsync().downloadStream(METADATA_URL)); } catch (Exception e) { - System.out.println("Error: " + e.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> "Error", e); throw e; } } @@ -104,7 +107,7 @@ public void downloadVideoAsync(HttpClient httpClient) { .verifyComplete()) .verifyComplete(); } catch (Exception e) { - System.out.println("Error: " + e.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> "Error", e); throw e; } } diff --git a/sdk/communication/azure-communication-chat/src/test/java/com/azure/communication/chat/ChatClientTest.java b/sdk/communication/azure-communication-chat/src/test/java/com/azure/communication/chat/ChatClientTest.java index 89cd18a49ba8..4bdb19fff1e7 100644 --- a/sdk/communication/azure-communication-chat/src/test/java/com/azure/communication/chat/ChatClientTest.java +++ b/sdk/communication/azure-communication-chat/src/test/java/com/azure/communication/chat/ChatClientTest.java @@ -3,28 +3,30 @@ package com.azure.communication.chat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - +import com.azure.communication.chat.implementation.ChatOptionsProvider; +import com.azure.communication.chat.models.ChatThreadItem; +import com.azure.communication.chat.models.CreateChatThreadOptions; +import com.azure.communication.chat.models.CreateChatThreadResult; +import com.azure.communication.chat.models.ListChatThreadsOptions; +import com.azure.communication.common.CommunicationUserIdentifier; import com.azure.communication.identity.CommunicationIdentityClient; import com.azure.communication.identity.models.CommunicationTokenScope; -import com.azure.communication.common.CommunicationUserIdentifier; -import com.azure.communication.chat.implementation.ChatOptionsProvider; -import com.azure.communication.chat.models.*; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Set the AZURE_TEST_MODE environment variable to either PLAYBACK or RECORD to determine if tests are playback or * live. By default, tests are run in playback mode. @@ -129,7 +131,7 @@ public void canDeleteChatThreadWithResponse(HttpClient httpClient) { @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void canListChatThreads(HttpClient httpClient) throws InterruptedException { + public void canListChatThreads(HttpClient httpClient) { // Arrange setupTest(httpClient, "canListChatThreadsSync"); CreateChatThreadOptions threadRequest1 = ChatOptionsProvider.createThreadOptions( @@ -139,7 +141,7 @@ public void canListChatThreads(HttpClient httpClient) throws InterruptedExceptio client.createChatThread(threadRequest1); client.createChatThread(threadRequest2); - Thread.sleep(500); + sleepIfRunningAgainstService(500); // Action & Assert PagedIterable threadsResponse = client.listChatThreads(); @@ -156,7 +158,7 @@ public void canListChatThreads(HttpClient httpClient) throws InterruptedExceptio @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void canListChatThreadsWithMaxPageSize(HttpClient httpClient) throws InterruptedException { + public void canListChatThreadsWithMaxPageSize(HttpClient httpClient) { // Arrange setupTest(httpClient, "canListChatThreadsWithMaxPageSizeSync"); CreateChatThreadOptions threadRequest1 = ChatOptionsProvider.createThreadOptions( @@ -166,7 +168,7 @@ public void canListChatThreadsWithMaxPageSize(HttpClient httpClient) throws Inte client.createChatThread(threadRequest1); client.createChatThread(threadRequest2); - Thread.sleep(500); + sleepIfRunningAgainstService(500); ListChatThreadsOptions options = new ListChatThreadsOptions(); options.setMaxPageSize(10); diff --git a/sdk/communication/azure-communication-chat/src/test/java/com/azure/communication/chat/CommunicationLoggerPolicy.java b/sdk/communication/azure-communication-chat/src/test/java/com/azure/communication/chat/CommunicationLoggerPolicy.java index 362f2f720f74..74737342374d 100644 --- a/sdk/communication/azure-communication-chat/src/test/java/com/azure/communication/chat/CommunicationLoggerPolicy.java +++ b/sdk/communication/azure-communication-chat/src/test/java/com/azure/communication/chat/CommunicationLoggerPolicy.java @@ -9,6 +9,7 @@ import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import reactor.core.publisher.Mono; /** @@ -16,7 +17,7 @@ */ public class CommunicationLoggerPolicy implements HttpPipelinePolicy { - private final ClientLogger logger = new ClientLogger(CommunicationLoggerPolicy.class); + private static final ClientLogger LOGGER = new ClientLogger(CommunicationLoggerPolicy.class); private final String testName; /** @@ -34,7 +35,7 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN final HttpResponse bufferedResponse = httpResponse.buffer(); // Should sanitize printed reponse url - System.out.println("MS-CV header for " + testName + " request " + LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); diff --git a/sdk/communication/azure-communication-identity/src/test/java/com/azure/communication/identity/CommunicationIdentityClientTestBase.java b/sdk/communication/azure-communication-identity/src/test/java/com/azure/communication/identity/CommunicationIdentityClientTestBase.java index 4a2be505d72a..0b183b1b4d6a 100644 --- a/sdk/communication/azure-communication-identity/src/test/java/com/azure/communication/identity/CommunicationIdentityClientTestBase.java +++ b/sdk/communication/azure-communication-identity/src/test/java/com/azure/communication/identity/CommunicationIdentityClientTestBase.java @@ -19,6 +19,8 @@ import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.identity.DefaultAzureCredentialBuilder; import reactor.core.publisher.Mono; @@ -33,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; public class CommunicationIdentityClientTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; @@ -159,7 +162,7 @@ private Mono logHeaders(String testName, HttpPipelineNextPolicy ne final HttpResponse bufferedResponse = httpResponse.buffer(); // Should sanitize printed reponse url - System.out.println("MS-CV header for " + testName + " request " + LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); diff --git a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/ClassificationPolicyAsyncLiveTests.java b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/ClassificationPolicyAsyncLiveTests.java index b180abf99367..deac224f7551 100644 --- a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/ClassificationPolicyAsyncLiveTests.java +++ b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/ClassificationPolicyAsyncLiveTests.java @@ -26,7 +26,6 @@ import com.azure.communication.jobrouter.models.WorkerSelectorAttachment; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; import com.azure.core.util.BinaryData; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -139,9 +138,7 @@ public void createClassificationPolicy(HttpClient httpClient) throws Interrupted } })).block(); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(5000); - } + sleepIfRunningAgainstService(5000); // Verify assertEquals(classificationPolicyId, policy.getId()); diff --git a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/ClassificationPolicyLiveTests.java b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/ClassificationPolicyLiveTests.java index 5639631436e9..1da46b2b40da 100644 --- a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/ClassificationPolicyLiveTests.java +++ b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/ClassificationPolicyLiveTests.java @@ -24,7 +24,6 @@ import com.azure.communication.jobrouter.models.WorkerSelectorAttachment; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; import com.azure.core.util.BinaryData; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -107,9 +106,7 @@ public void createClassificationPolicy(HttpClient httpClient) throws Interrupted RouterJob job = routerClient.createJobWithClassificationPolicy( new CreateJobWithClassificationPolicyOptions(jobId, channelId, classificationPolicyId)); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(5000); - } + sleepIfRunningAgainstService(5000); // Verify assertEquals(classificationPolicyId, policy.getId()); diff --git a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterJobAsyncLiveTests.java b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterJobAsyncLiveTests.java index 92e21536b168..ccf6b55c2157 100644 --- a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterJobAsyncLiveTests.java +++ b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterJobAsyncLiveTests.java @@ -25,7 +25,6 @@ import com.azure.core.http.HttpClient; import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; import com.azure.core.util.BinaryData; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -150,9 +149,7 @@ public void unassignJob(HttpClient httpClient) throws InterruptedException { assertEquals(2, jobDeserialized.getRequestedWorkerSelectors().size()); assertEquals(Duration.ofSeconds(100), jobDeserialized.getRequestedWorkerSelectors().get(0).getExpiresAfter()); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(2000); - } + sleepIfRunningAgainstService(2000); jobDeserialized.setPriority(10); RouterJob updatedJob = jobRouterAsyncClient.updateJob(jobId, jobDeserialized).block(); @@ -207,9 +204,7 @@ public void unassignJob(HttpClient httpClient) throws InterruptedException { // Verify assertTrue(unassignJobResult.getUnassignmentCount() > 0); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(5000); - } + sleepIfRunningAgainstService(5000); RouterQueueStatistics queueStatistics = jobRouterAsyncClient.getQueueStatistics(queueId).block(); @@ -236,9 +231,7 @@ public void unassignJob(HttpClient httpClient) throws InterruptedException { jobRouterAsyncClient.cancelJob(jobId, requestOptions).block(); jobRouterAsyncClient.deleteJob(jobId).block(); jobRouterAsyncClient.deleteWorker(workerId).block(); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(5000); - } + sleepIfRunningAgainstService(5000); administrationAsyncClient.deleteQueue(queueId).block(); administrationAsyncClient.deleteDistributionPolicy(distributionPolicyId).block(); } diff --git a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterJobLiveTests.java b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterJobLiveTests.java index 23447f8edab1..2363a4d1228a 100644 --- a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterJobLiveTests.java +++ b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterJobLiveTests.java @@ -25,7 +25,6 @@ import com.azure.core.http.HttpClient; import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; import com.azure.core.util.BinaryData; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -151,9 +150,7 @@ public void unassignJob(HttpClient httpClient) throws InterruptedException { assertEquals(2, jobDeserialized.getRequestedWorkerSelectors().size()); assertEquals(Duration.ofSeconds(100), jobDeserialized.getRequestedWorkerSelectors().get(0).getExpiresAfter()); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(2000); - } + sleepIfRunningAgainstService(2000); jobDeserialized.setPriority(10); RouterJob updatedJob = jobRouterClient.updateJob(jobId, jobDeserialized); @@ -207,9 +204,7 @@ public void unassignJob(HttpClient httpClient) throws InterruptedException { // Verify assertTrue(unassignJobResult.getUnassignmentCount() > 0); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(5000); - } + sleepIfRunningAgainstService(5000); RouterQueueStatistics queueStatistics = jobRouterClient.getQueueStatistics(queueId); @@ -235,9 +230,7 @@ public void unassignJob(HttpClient httpClient) throws InterruptedException { jobRouterClient.cancelJob(jobId, requestOptions); jobRouterClient.deleteJob(jobId); jobRouterClient.deleteWorker(workerId); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(5000); - } + sleepIfRunningAgainstService(5000); routerAdminClient.deleteQueue(queueId); routerAdminClient.deleteDistributionPolicy(distributionPolicyId); } @@ -264,9 +257,7 @@ public void jobScheduling(HttpClient httpClient) throws InterruptedException { OffsetDateTime.of(2040, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC)))); assertEquals(RouterJobStatus.PENDING_SCHEDULE, job.getStatus()); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(2000); - } + sleepIfRunningAgainstService(2000); // Action job.setMatchingMode(new QueueAndMatchMode()); diff --git a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterWorkerAsyncLiveTests.java b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterWorkerAsyncLiveTests.java index 800d9d47d2f1..4cd77b5ce427 100644 --- a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterWorkerAsyncLiveTests.java +++ b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterWorkerAsyncLiveTests.java @@ -14,7 +14,6 @@ import com.azure.communication.jobrouter.models.RouterWorker; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; import com.azure.core.util.BinaryData; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -132,9 +131,7 @@ public void createWorker(HttpClient httpClient) throws InterruptedException { assertEquals(channels.size(), deserialized.getChannels().size()); assertEquals(deserialized.getEtag(), result.getEtag()); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(2000); - } + sleepIfRunningAgainstService(2000); deserialized.setAvailableForOffers(true); deserialized.setChannels(new ArrayList() { diff --git a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterWorkerLiveTests.java b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterWorkerLiveTests.java index 008f0b3a0eea..b4423b1403e9 100644 --- a/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterWorkerLiveTests.java +++ b/sdk/communication/azure-communication-jobrouter/src/test/java/com.azure.communication.jobrouter/RouterWorkerLiveTests.java @@ -11,7 +11,6 @@ import com.azure.communication.jobrouter.models.RouterWorker; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; import com.azure.core.util.BinaryData; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -108,9 +107,7 @@ public void createWorker(HttpClient httpClient) throws InterruptedException { assertEquals(channels.size(), deserialized.getChannels().size()); assertEquals(deserialized.getEtag(), result.getEtag()); - if (this.getTestMode() != TestMode.PLAYBACK) { - Thread.sleep(2000); - } + sleepIfRunningAgainstService(2000); deserialized.setAvailableForOffers(true); deserialized.setChannels(new ArrayList() { diff --git a/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/CommunicationMessagesTestBase.java b/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/CommunicationMessagesTestBase.java index 34bfb174ebde..ebb1ceae3992 100644 --- a/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/CommunicationMessagesTestBase.java +++ b/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/CommunicationMessagesTestBase.java @@ -14,11 +14,14 @@ import com.azure.core.test.models.TestProxySanitizer; import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.util.Configuration; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import reactor.core.publisher.Mono; import java.util.Arrays; public class CommunicationMessagesTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(CommunicationMessagesTestBase.class); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_CONNECTION_STRING_CPM", @@ -101,7 +104,7 @@ public Mono logHeaders(HttpPipelineNextPolicy next) { final HttpResponse bufferedResponse = httpResponse.buffer(); // Should sanitize printed reponse url - System.out.println("MS-CV header for request " + LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); diff --git a/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/PhoneNumbersIntegrationTestBase.java b/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/PhoneNumbersIntegrationTestBase.java index 43789327783c..15d95cadd7c3 100644 --- a/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/PhoneNumbersIntegrationTestBase.java +++ b/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/PhoneNumbersIntegrationTestBase.java @@ -16,12 +16,16 @@ import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.identity.DefaultAzureCredentialBuilder; import reactor.core.publisher.Mono; import java.util.Arrays; public class PhoneNumbersIntegrationTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(PhoneNumbersIntegrationTestBase.class); + private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https://REDACTED.communication.azure.com/;accesskey=QWNjZXNzS2V5"); @@ -141,8 +145,8 @@ private Mono logHeaders(String testName, HttpPipelineNextPolicy ne final HttpResponse bufferedResponse = httpResponse.buffer(); // Should sanitize printed reponse url - System.out.println("MS-CV header for " + testName + " request " - + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); + LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } diff --git a/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/siprouting/SipRoutingIntegrationTestBase.java b/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/siprouting/SipRoutingIntegrationTestBase.java index b74c96e53805..8d0b33036d34 100644 --- a/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/siprouting/SipRoutingIntegrationTestBase.java +++ b/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/siprouting/SipRoutingIntegrationTestBase.java @@ -19,16 +19,20 @@ import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.identity.DefaultAzureCredentialBuilder; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.List; -import java.util.UUID; import static java.util.Arrays.asList; public class SipRoutingIntegrationTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(SipRoutingIntegrationTestBase.class); + private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https://REDACTED.communication.azure.com/;accesskey=QWNjZXNzS2V5"); private static final String AZURE_TEST_DOMAIN = Configuration.getGlobalConfiguration() @@ -192,7 +196,7 @@ private Mono logHeaders(String testName, HttpPipelineNextPolicy ne final HttpResponse bufferedResponse = httpResponse.buffer(); // Should sanitize printed reponse url - System.out.println("MS-CV header for " + testName + " request " + LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); @@ -203,7 +207,7 @@ private static String getUniqueFqdn(String order) { return order + ".redacted" + "." + AZURE_TEST_DOMAIN; } - String unique = UUID.randomUUID().toString().replace("-", ""); + String unique = CoreUtils.randomUuid().toString().replace("-", ""); return order + "-" + unique + "." + AZURE_TEST_DOMAIN; } } diff --git a/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsAsyncClientTests.java b/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsAsyncClientTests.java index dc472774da6f..6fe6e520b73d 100644 --- a/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsAsyncClientTests.java +++ b/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsAsyncClientTests.java @@ -3,33 +3,42 @@ package com.azure.communication.rooms; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - +import com.azure.communication.common.CommunicationIdentifier; +import com.azure.communication.common.CommunicationUserIdentifier; import com.azure.communication.identity.CommunicationIdentityClient; -import com.azure.communication.rooms.models.*; import com.azure.communication.rooms.implementation.models.CommunicationErrorResponseException; +import com.azure.communication.rooms.models.AddOrUpdateParticipantsResult; +import com.azure.communication.rooms.models.CommunicationRoom; +import com.azure.communication.rooms.models.CreateRoomOptions; +import com.azure.communication.rooms.models.ParticipantRole; +import com.azure.communication.rooms.models.RemoveParticipantsResult; +import com.azure.communication.rooms.models.RoomParticipant; +import com.azure.communication.rooms.models.UpdateRoomOptions; import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.Response; import com.azure.core.test.http.AssertingHttpClientBuilder; -import java.util.Arrays; -import java.util.List; - -import com.azure.communication.common.CommunicationIdentifier; -import com.azure.communication.common.CommunicationUserIdentifier; - +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; - import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class RoomsAsyncClientTests extends RoomsTestBase { + private static final ClientLogger LOGGER = new ClientLogger(RoomsAsyncClientTests.class); + private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @@ -78,7 +87,7 @@ public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { Mono> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); - System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); + LOGGER.log(LogLevel.VERBOSE, () -> String.valueOf(VALID_FROM.plusMonths(3).getDayOfYear())); StepVerifier.create(response3) .assertNext(roomResult -> { @@ -121,10 +130,10 @@ public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { StepVerifier.create(response1) .assertNext(roomResult -> { - assertTrue(roomResult.getRoomId() != null); - assertTrue(roomResult.getCreatedAt() != null); - assertTrue(roomResult.getValidFrom() != null); - assertTrue(roomResult.getValidUntil() != null); + assertNotNull(roomResult.getRoomId()); + assertNotNull(roomResult.getCreatedAt()); + assertNotNull(roomResult.getValidFrom()); + assertNotNull(roomResult.getValidUntil()); assertTrue(roomResult.isPstnDialOutEnabled()); }).verifyComplete(); @@ -139,7 +148,7 @@ public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { StepVerifier.create(response3) .assertNext(result3 -> { - assertEquals(true, result3.getValidUntil().toEpochSecond() > result3.getValidFrom().toEpochSecond()); + assertTrue(result3.getValidUntil().toEpochSecond() > result3.getValidFrom().toEpochSecond()); assertTrue(result3.isPstnDialOutEnabled()); }).verifyComplete(); @@ -168,10 +177,10 @@ public void createRoomWithNoAttributes(HttpClient httpClient) { StepVerifier.create(response1) .assertNext(roomResult -> { - assertTrue(roomResult.getRoomId() != null); - assertTrue(roomResult.getCreatedAt() != null); - assertTrue(roomResult.getValidFrom() != null); - assertTrue(roomResult.getValidUntil() != null); + assertNotNull(roomResult.getRoomId()); + assertNotNull(roomResult.getCreatedAt()); + assertNotNull(roomResult.getValidFrom()); + assertNotNull(roomResult.getValidUntil()); assertFalse(roomResult.isPstnDialOutEnabled()); }).verifyComplete(); @@ -210,10 +219,10 @@ public void createRoomWithOnlyParticipantAttributes(HttpClient httpClient) { StepVerifier.create(response1) .assertNext(roomResult -> { - assertTrue(roomResult.getRoomId() != null); - assertTrue(roomResult.getCreatedAt() != null); - assertTrue(roomResult.getValidFrom() != null); - assertTrue(roomResult.getValidUntil() != null); + assertNotNull(roomResult.getRoomId()); + assertNotNull(roomResult.getCreatedAt()); + assertNotNull(roomResult.getValidFrom()); + assertNotNull(roomResult.getValidUntil()); assertTrue(roomResult.isPstnDialOutEnabled()); }).verifyComplete(); @@ -241,10 +250,10 @@ public void createRoomWithOnlyPstnEnabledAttribute(HttpClient httpClient) { StepVerifier.create(response1) .assertNext(roomResult -> { - assertTrue(roomResult.getRoomId() != null); - assertTrue(roomResult.getCreatedAt() != null); - assertTrue(roomResult.getValidFrom() != null); - assertTrue(roomResult.getValidUntil() != null); + assertNotNull(roomResult.getRoomId()); + assertNotNull(roomResult.getCreatedAt()); + assertNotNull(roomResult.getValidFrom()); + assertNotNull(roomResult.getValidUntil()); assertTrue(roomResult.isPstnDialOutEnabled()); }).verifyComplete(); @@ -566,10 +575,10 @@ public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient http StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { - assertTrue(roomResult.getRoomId() != null); - assertTrue(roomResult.getCreatedAt() != null); - assertTrue(roomResult.getValidFrom() != null); - assertTrue(roomResult.getValidUntil() != null); + assertNotNull(roomResult.getRoomId()); + assertNotNull(roomResult.getCreatedAt()); + assertNotNull(roomResult.getValidFrom()); + assertNotNull(roomResult.getValidUntil()); assertTrue(roomResult.isPstnDialOutEnabled()); }).verifyComplete(); @@ -627,7 +636,7 @@ public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient http StepVerifier.create(updateParticipantResponse) .assertNext(result -> { - assertEquals(true, result instanceof AddOrUpdateParticipantsResult); + assertInstanceOf(AddOrUpdateParticipantsResult.class, result); }) .verifyComplete(); @@ -680,7 +689,7 @@ public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient http StepVerifier.create(removeParticipantResponse2) .assertNext(result -> { - assertEquals(true, result instanceof RemoveParticipantsResult); + assertInstanceOf(RemoveParticipantsResult.class, result); }) .verifyComplete(); @@ -716,10 +725,10 @@ public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { - assertTrue(roomResult.getRoomId() != null); - assertTrue(roomResult.getCreatedAt() != null); - assertTrue(roomResult.getValidFrom() != null); - assertTrue(roomResult.getValidUntil() != null); + assertNotNull(roomResult.getRoomId()); + assertNotNull(roomResult.getCreatedAt()); + assertNotNull(roomResult.getValidFrom()); + assertNotNull(roomResult.getValidUntil()); assertTrue(roomResult.isPstnDialOutEnabled()); }).verifyComplete(); @@ -772,10 +781,10 @@ public void addUpdateInvalidParticipants(HttpClient httpClient) { StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { - assertEquals(true, roomResult.getRoomId() != null); - assertEquals(true, roomResult.getCreatedAt() != null); - assertEquals(true, roomResult.getValidFrom() != null); - assertEquals(true, roomResult.getValidUntil() != null); + assertNotNull(roomResult.getRoomId()); + assertNotNull(roomResult.getCreatedAt()); + assertNotNull(roomResult.getValidFrom()); + assertNotNull(roomResult.getValidUntil()); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); @@ -822,10 +831,10 @@ public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClie StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { - assertEquals(true, roomResult.getRoomId() != null); - assertEquals(true, roomResult.getCreatedAt() != null); - assertEquals(true, roomResult.getValidFrom() != null); - assertEquals(true, roomResult.getValidUntil() != null); + assertNotNull(roomResult.getRoomId()); + assertNotNull(roomResult.getCreatedAt()); + assertNotNull(roomResult.getValidFrom()); + assertNotNull(roomResult.getValidUntil()); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); @@ -835,10 +844,10 @@ public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClie StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { - assertEquals(true, room.getRoomId() != null); - assertEquals(true, room.getCreatedAt() != null); - assertEquals(true, room.getValidFrom() != null); - assertEquals(true, room.getValidUntil() != null); + assertNotNull(room.getRoomId()); + assertNotNull(room.getCreatedAt()); + assertNotNull(room.getValidFrom()); + assertNotNull(room.getValidUntil()); }) .expectComplete() .verify(); diff --git a/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsTestBase.java b/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsTestBase.java index c78a43f7207b..d845723cd19b 100644 --- a/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsTestBase.java +++ b/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsTestBase.java @@ -5,10 +5,14 @@ import com.azure.communication.common.implementation.CommunicationConnectionString; import com.azure.communication.identity.CommunicationIdentityClientBuilder; -import com.azure.communication.rooms.models.*; +import com.azure.communication.rooms.models.CommunicationRoom; +import com.azure.communication.rooms.models.RoomParticipant; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.rest.Response; import com.azure.core.test.TestMode; import com.azure.core.test.TestProxyTestBase; import com.azure.core.test.models.BodilessMatcher; @@ -16,18 +20,17 @@ import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; +import reactor.core.publisher.Mono; import java.time.OffsetDateTime; import java.util.Arrays; -import java.util.Locale; -import reactor.core.publisher.Mono; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.rest.Response; -import static org.junit.jupiter.api.Assertions.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class RoomsTestBase extends TestProxyTestBase { - protected static final TestMode TEST_MODE = initializeTestMode(); + private static final ClientLogger LOGGER = new ClientLogger(RoomsTestBase.class); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration().get( "COMMUNICATION_CONNECTION_STRING_ROOMS", @@ -112,23 +115,6 @@ protected void configureTestMode(RoomsClientBuilder builder) { } } - private static TestMode initializeTestMode() { - ClientLogger logger = new ClientLogger(RoomsTestBase.class); - String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); - if (azureTestMode != null) { - System.out.println("azureTestMode: " + azureTestMode); - try { - return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); - } catch (IllegalArgumentException var3) { - logger.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); - return TestMode.PLAYBACK; - } - } else { - logger.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); - return TestMode.PLAYBACK; - } - } - protected RoomsClientBuilder addLoggingPolicy(RoomsClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } @@ -153,8 +139,8 @@ private Mono logHeaders(String testName, HttpPipelineNextPolicy ne final HttpResponse bufferedResponse = httpResponse.buffer(); // Should sanitize printed reponse url - System.out.println("MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() - + ": " + bufferedResponse.getHeaderValue("MS-CV")); + LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } diff --git a/sdk/communication/azure-communication-sms/src/test/java/com/azure/communication/sms/SmsTestBase.java b/sdk/communication/azure-communication-sms/src/test/java/com/azure/communication/sms/SmsTestBase.java index fdffac7a5479..bbfcda8cc29f 100644 --- a/sdk/communication/azure-communication-sms/src/test/java/com/azure/communication/sms/SmsTestBase.java +++ b/sdk/communication/azure-communication-sms/src/test/java/com/azure/communication/sms/SmsTestBase.java @@ -15,11 +15,15 @@ import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import reactor.core.publisher.Mono; import java.util.Arrays; public class SmsTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(SmsTestBase.class); + protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https://REDACTED.communication.azure.com/;accesskey=QWNjZXNzS2V5"); @@ -95,8 +99,8 @@ private Mono logHeaders(String testName, HttpPipelineNextPolicy ne final HttpResponse bufferedResponse = httpResponse.buffer(); // Should sanitize printed reponse url - System.out.println("MS-CV header for " + testName + " request " - + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); + LOGGER.log(LogLevel.VERBOSE, () -> ("MS-CV header for " + testName + " request " + + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV"))); return Mono.just(bufferedResponse); }); } diff --git a/sdk/confidentialledger/azure-security-confidentialledger/src/test/java/com/azure/security/confidentialledger/ConfidentialLedgerClientTestBase.java b/sdk/confidentialledger/azure-security-confidentialledger/src/test/java/com/azure/security/confidentialledger/ConfidentialLedgerClientTestBase.java index c91b8d5c6cf1..d9c220dd946f 100644 --- a/sdk/confidentialledger/azure-security-confidentialledger/src/test/java/com/azure/security/confidentialledger/ConfidentialLedgerClientTestBase.java +++ b/sdk/confidentialledger/azure-security-confidentialledger/src/test/java/com/azure/security/confidentialledger/ConfidentialLedgerClientTestBase.java @@ -18,6 +18,8 @@ import com.azure.core.test.models.TestProxySanitizer; import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.util.BinaryData; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.security.confidentialledger.certificate.ConfidentialLedgerCertificateClient; import com.azure.security.confidentialledger.certificate.ConfidentialLedgerCertificateClientBuilder; @@ -39,6 +41,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class ConfidentialLedgerClientTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(ConfidentialLedgerClientTestBase.class); protected static final String TRANSACTION_ID = "transactionId"; protected static final String COLLECTION_ID = "collectionId"; @@ -82,7 +85,7 @@ protected void beforeTest() { try { jsonNode = mapper.readTree(identityResponse.toBytes()); } catch (IOException ex) { - System.out.println("Caught IO exception " + ex); + LOGGER.log(LogLevel.VERBOSE, () -> "Caught IO exception", ex); Assertions.fail(); } @@ -104,7 +107,7 @@ protected void beforeTest() { reactorClient = reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException ex) { - System.out.println("Caught SSL exception " + ex); + LOGGER.log(LogLevel.VERBOSE, () -> "Caught SSL exception", ex); Assertions.fail(); } diff --git a/sdk/containerregistry/azure-containers-containerregistry/src/test/java/com/azure/containers/containerregistry/TestUtils.java b/sdk/containerregistry/azure-containers-containerregistry/src/test/java/com/azure/containers/containerregistry/TestUtils.java index d844c0558d86..839f886a4b87 100644 --- a/sdk/containerregistry/azure-containers-containerregistry/src/test/java/com/azure/containers/containerregistry/TestUtils.java +++ b/sdk/containerregistry/azure-containers-containerregistry/src/test/java/com/azure/containers/containerregistry/TestUtils.java @@ -125,7 +125,6 @@ static TokenCredential getCredentialByAuthority(TestMode testMode, String author static void importImage(TestMode mode, String repository, List tags) { try { importImage(mode, REGISTRY_NAME, repository, tags, REGISTRY_ENDPOINT); - Thread.sleep(SLEEP_TIME_IN_MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } @@ -190,6 +189,8 @@ static void importImage(TestMode mode, String registryName, String repository, L Thread.sleep(SLEEP_TIME_IN_MILLISECONDS); } } while (++index < 3); + + Thread.sleep(SLEEP_TIME_IN_MILLISECONDS); } private static OciImageManifest createManifest() { diff --git a/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/implementation/JdkHttpUtils.java b/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/implementation/JdkHttpUtils.java index 85ae06b2f5a3..bc9a29d746c2 100644 --- a/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/implementation/JdkHttpUtils.java +++ b/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/implementation/JdkHttpUtils.java @@ -3,6 +3,7 @@ package com.azure.core.http.jdk.httpclient.implementation; import com.azure.core.http.HttpHeaders; +import com.azure.core.implementation.util.HttpHeadersAccessHelper; import com.azure.core.util.CoreUtils; import java.nio.ByteBuffer; @@ -25,13 +26,14 @@ public final class JdkHttpUtils { * @param headers the JDK Http headers * @return the azure-core Http headers */ - @SuppressWarnings("deprecation") public static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) { final HttpHeaders httpHeaders = new HttpHeaders((int) (headers.map().size() / 0.75F)); for (Map.Entry> kvp : headers.map().entrySet()) { if (!CoreUtils.isNullOrEmpty(kvp.getValue())) { - httpHeaders.set(kvp.getKey(), kvp.getValue()); + // JDK HttpClient parses headers to lower case, use the access helper to bypass lowercasing the header + // name (or in this case, just checking that the header name is lowercased). + HttpHeadersAccessHelper.setInternal(httpHeaders, kvp.getKey(), kvp.getKey(), kvp.getValue()); } } diff --git a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/NettyAsyncHttpResponseBase.java b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/NettyAsyncHttpResponseBase.java index 5346aeb2948a..6621a80eea46 100644 --- a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/NettyAsyncHttpResponseBase.java +++ b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/NettyAsyncHttpResponseBase.java @@ -7,10 +7,13 @@ import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; +import com.azure.core.implementation.util.HttpHeadersAccessHelper; +import io.netty.util.AsciiString; import reactor.netty.http.client.HttpClientResponse; import java.util.Iterator; import java.util.Map; +import java.util.Objects; /** * Base response class for Reactor Netty with implementations for response metadata. @@ -40,8 +43,19 @@ public abstract class NettyAsyncHttpResponseBase extends HttpResponse { while (nettyHeadersIterator.hasNext()) { Map.Entry next = nettyHeadersIterator.next(); // Value may be null and that needs to be guarded but key should never be null. - CharSequence value = next.getValue(); - this.headers.add(next.getKey().toString(), (value == null) ? null : value.toString()); + String value = Objects.toString(next.getValue(), null); + CharSequence key = next.getKey(); + + // Check for the header name being a Netty AsciiString as it has optimizations around lowercasing. + if (key instanceof AsciiString) { + // Hook into optimizations exposed through shared implementation to speed up the conversion. + AsciiString asciiString = (AsciiString) key; + HttpHeadersAccessHelper.addInternal(headers, asciiString.toLowerCase().toString(), + asciiString.toString(), value); + } else { + // If it isn't an AsciiString, then fallback to the shared, albeit, slower path. + this.headers.add(key.toString(), value); + } } } else { this.headers = new NettyToAzureCoreHttpHeadersWrapper(nettyHeaders); diff --git a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/Utility.java b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/Utility.java index 33a18a4fe343..670e41710e34 100644 --- a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/Utility.java +++ b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/Utility.java @@ -51,10 +51,9 @@ public final class Utility { * @return A newly allocated {@link ByteBuffer} containing the copied bytes. */ public static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { - ByteBuffer buffer = ByteBuffer.allocate(byteBuf.readableBytes()); - byteBuf.readBytes(buffer); - buffer.rewind(); - return buffer; + byte[] bytes = new byte[byteBuf.readableBytes()]; + byteBuf.getBytes(byteBuf.readerIndex(), bytes); + return ByteBuffer.wrap(bytes); } /** diff --git a/sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/polling/LROPollerTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/polling/LROPollerTests.java index d20086bf9d0c..031ed96e6cd0 100644 --- a/sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/polling/LROPollerTests.java +++ b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/polling/LROPollerTests.java @@ -22,6 +22,8 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.polling.AsyncPollResponse; import com.azure.core.util.polling.LongRunningOperationStatus; import com.azure.core.util.polling.PollerFlux; @@ -61,6 +63,7 @@ @SuppressWarnings("unchecked") public class LROPollerTests { + private static final ClientLogger LOGGER = new ClientLogger(LROPollerTests.class); private static final SerializerAdapter SERIALIZER = SerializerFactory.createDefaultManagementSerializerAdapter(); @@ -678,8 +681,12 @@ public void lroRetryAfter() { long nanoTime = System.nanoTime(); - FooWithProvisioningState result = lroFlux.doOnNext(response -> System.out.printf("[%s] status %s%n", - OffsetDateTime.now(), response.getStatus().toString())).blockLast().getFinalResult().block(); + FooWithProvisioningState result = lroFlux + .doOnNext(response -> LOGGER.log(LogLevel.VERBOSE, + () -> String.format("[%s] status %s%n", OffsetDateTime.now(), response.getStatus()))) + .blockLast() + .getFinalResult() + .block(); Assertions.assertNotNull(result); Duration pollingDuration = Duration.ofNanos(System.nanoTime() - nanoTime); @@ -879,7 +886,8 @@ public com.github.tomakehurst.wiremock.http.Response transform(Request request, .build(); } if (request.getMethod().isOneOf(RequestMethod.PUT)) { - System.out.printf("[%s] PUT status %s%n", OffsetDateTime.now(), "IN_PROGRESS"); + LOGGER.log(LogLevel.VERBOSE, + () -> String.format("[%s] PUT status %s%n", OffsetDateTime.now(), "IN_PROGRESS")); return new com.github.tomakehurst.wiremock.http.Response.Builder() .headers(serverConfigure.additionalHeaders) .body(toJson(new FooWithProvisioningState("IN_PROGRESS"))) @@ -888,13 +896,15 @@ public com.github.tomakehurst.wiremock.http.Response transform(Request request, if (request.getMethod().isOneOf(RequestMethod.GET)) { getCallCount[0]++; if (getCallCount[0] < serverConfigure.pollingCountTillSuccess) { - System.out.printf("[%s] GET status %s%n", OffsetDateTime.now(), "IN_PROGRESS"); + LOGGER.log(LogLevel.VERBOSE, + () -> String.format("[%s] GET status %s%n", OffsetDateTime.now(), "IN_PROGRESS")); return new com.github.tomakehurst.wiremock.http.Response.Builder() .headers(serverConfigure.additionalHeaders) .body(toJson(new FooWithProvisioningState("IN_PROGRESS"))) .build(); } else if (getCallCount[0] == serverConfigure.pollingCountTillSuccess) { - System.out.printf("[%s] GET status %s%n", OffsetDateTime.now(), "SUCCEEDED"); + LOGGER.log(LogLevel.VERBOSE, + () -> String.format("[%s] GET status %s%n", OffsetDateTime.now(), "SUCCEEDED")); return new com.github.tomakehurst.wiremock.http.Response.Builder() .body(toJson(new FooWithProvisioningState("SUCCEEDED", UUID.randomUUID().toString()))) .build(); diff --git a/sdk/core/azure-core/spotbugs-exclude.xml b/sdk/core/azure-core/spotbugs-exclude.xml index 4fd09a2c2551..2ffee6a08a69 100644 --- a/sdk/core/azure-core/spotbugs-exclude.xml +++ b/sdk/core/azure-core/spotbugs-exclude.xml @@ -449,4 +449,10 @@ + + + + + + diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java index b42992287c1a..c52fa19e5cbd 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java @@ -33,7 +33,22 @@ public class HttpHeaders implements Iterable { private final Map headers; static { - HttpHeadersAccessHelper.setAccessor(headers -> headers.headers); + HttpHeadersAccessHelper.setAccessor(new HttpHeadersAccessHelper.HttpHeadersAccessor() { + @Override + public Map getRawHeaderMap(HttpHeaders headers) { + return headers.headers; + } + + @Override + public void addInternal(HttpHeaders headers, String formattedName, String name, String value) { + headers.addInternal(formattedName, name, value); + } + + @Override + public void setInternal(HttpHeaders headers, String formattedName, String name, List values) { + headers.setInternal(formattedName, name, values); + } + }); } /** diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java index 615f231971c3..b37eb2c46b7f 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java @@ -123,16 +123,11 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN return authorizeRequest(context).then(Mono.defer(next::process)).flatMap(httpResponse -> { String authHeader = httpResponse.getHeaderValue(HttpHeaderName.WWW_AUTHENTICATE); if (httpResponse.getStatusCode() == 401 && authHeader != null) { - return authorizeRequestOnChallenge(context, httpResponse).flatMap(retry -> { - if (retry) { - // Both Netty and OkHttp expect the requestBody to be closed after the response has been read. - // Failure to do so results in memory leak. - // In case of StreamResponse (or other scenarios where we do not eagerly read the response) - // the response body may not be consumed. - // This can cause potential leaks in the scenarios like above, where the policy - // may intercept the response and it may never be read. - // Forcing the read here - so that the memory can be released. - return httpResponse.getBody().ignoreElements().then(nextPolicy.process()); + return authorizeRequestOnChallenge(context, httpResponse).flatMap(authorized -> { + if (authorized) { + // body needs to be closed or read to the end to release the connection + httpResponse.close(); + return nextPolicy.process(); } else { return Mono.just(httpResponse); } @@ -155,13 +150,8 @@ public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNex String authHeader = httpResponse.getHeaderValue(HttpHeaderName.WWW_AUTHENTICATE); if (httpResponse.getStatusCode() == 401 && authHeader != null) { if (authorizeRequestOnChallengeSync(context, httpResponse)) { - // Both Netty and OkHttp expect the requestBody to be closed after the response has been read. - // Failure to do so results in memory leak. - // In case of StreamResponse (or other scenarios where we do not eagerly read the response) - // the response body may not be consumed. - // This can cause potential leaks in the scenarios like above, where the policy - // may intercept the response and it may never be read. - // Forcing the read here - so that the memory can be released. + // body needs to be closed or read to the end to release the connection + httpResponse.close(); return nextPolicy.processSync(); } else { return httpResponse; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RedirectPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RedirectPolicy.java index fcc969e5216f..d0758d6b7d5d 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RedirectPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RedirectPolicy.java @@ -89,7 +89,6 @@ private Mono attemptRedirect(final HttpPipelineCallContext context return next.clone().process().flatMap(httpResponse -> { if (redirectStrategy.shouldAttemptRedirect(context, httpResponse, redirectAttempt, attemptedRedirectUrls)) { - HttpRequest redirectRequestCopy = createRedirectRequest(httpResponse); return attemptRedirect(context, next, redirectRequestCopy, redirectAttempt + 1, attemptedRedirectUrls); } else { @@ -111,7 +110,6 @@ private HttpResponse attemptRedirectSync(final HttpPipelineCallContext context, HttpResponse httpResponse = next.clone().processSync(); if (redirectStrategy.shouldAttemptRedirect(context, httpResponse, redirectAttempt, attemptedRedirectUrls)) { - HttpRequest redirectRequestCopy = createRedirectRequest(httpResponse); return attemptRedirectSync(context, next, redirectRequestCopy, redirectAttempt + 1, attemptedRedirectUrls); } else { diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/RestProxy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/RestProxy.java index 6e3c8d9a611e..de36dac2045e 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/RestProxy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/RestProxy.java @@ -82,8 +82,6 @@ public Mono send(HttpRequest request, Context contextData) { @Override public Object invoke(Object proxy, final Method method, Object[] args) { - RestProxyUtils.validateResumeOperationIsNotPresent(method); - // Note: request options need to be evaluated here, as it is a public class with package private methods. // Evaluating here allows the package private methods to be invoked here for downstream use. final SwaggerMethodParser methodParser = getMethodParser(method); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/AsyncRestProxy.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/AsyncRestProxy.java index a09db64f1d79..2548bec2a64f 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/AsyncRestProxy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/AsyncRestProxy.java @@ -75,8 +75,6 @@ Mono send(HttpRequest request, Context contextData) { @SuppressWarnings({ "try", "unused" }) public Object invoke(Object proxy, Method method, RequestOptions options, EnumSet errorOptions, Consumer requestCallback, SwaggerMethodParser methodParser, HttpRequest request, Context context) { - RestProxyUtils.validateResumeOperationIsNotPresent(method); - context = startTracingSpan(methodParser, context); // If there is 'RequestOptions' apply its request callback operations before validating the body. diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/RestProxyBase.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/RestProxyBase.java index af018bfc0d95..67f4ea40662e 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/RestProxyBase.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/RestProxyBase.java @@ -98,8 +98,6 @@ public RestProxyBase(HttpPipeline httpPipeline, SerializerAdapter serializer, */ public final Object invoke(Object proxy, Method method, RequestOptions options, EnumSet errorOptions, Consumer requestCallback, SwaggerMethodParser methodParser, boolean isAsync, Object[] args) { - RestProxyUtils.validateResumeOperationIsNotPresent(method); - try { HttpRequest request = createHttpRequest(methodParser, serializer, isAsync, args); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/SwaggerMethodParser.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/SwaggerMethodParser.java index 7401e138f985..94f1674f3348 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/SwaggerMethodParser.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/rest/SwaggerMethodParser.java @@ -285,6 +285,8 @@ public SwaggerMethodParser(Method swaggerMethod) { this.responseEagerlyRead = isResponseEagerlyRead(unwrappedReturnType); this.ignoreResponseBody = isResponseBodyIgnored(unwrappedReturnType); this.spanName = interfaceParser.getServiceName() + "." + swaggerMethod.getName(); + + RestProxyUtils.validateResumeOperationIsNotPresent(swaggerMethod); } /** diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/HttpHeadersAccessHelper.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/HttpHeadersAccessHelper.java index 304f082277fa..bbf6c87e2250 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/HttpHeadersAccessHelper.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/HttpHeadersAccessHelper.java @@ -5,6 +5,8 @@ import com.azure.core.http.HttpHeader; import com.azure.core.http.HttpHeaders; +import java.util.List; +import java.util.Locale; import java.util.Map; /** @@ -24,6 +26,34 @@ public interface HttpHeadersAccessor { * @return The raw header map. */ Map getRawHeaderMap(HttpHeaders headers); + + /** + * Adds a header value to the backing map in {@link HttpHeaders}. + *

+ * This bypasses using {@link HttpHeaders#add(String, String)} which uses {@link String#toLowerCase(Locale)}, + * which may be slower than options available by implementing HTTP stacks (such as Netty which has an ASCII + * string class which has optimizations around lowercasing due to ASCII constraints). + * + * @param headers The {@link HttpHeaders} to add the header to. + * @param formattedName The lower-cased header name. + * @param name The original header name. + * @param value The header value. + */ + void addInternal(HttpHeaders headers, String formattedName, String name, String value); + + /** + * Sets a header value to the backing map in {@link HttpHeaders}. + *

+ * This bypasses using {@link HttpHeaders#set(String, List)} which uses {@link String#toLowerCase(Locale)}, + * which may be slower than options available by implementing HTTP stacks (such as JDK HttpClient where all + * response header names are already lowercased). + * + * @param headers The {@link HttpHeaders} to set the header to. + * @param formattedName The lower-cased header name. + * @param name The original header name. + * @param values The header values. + */ + void setInternal(HttpHeaders headers, String formattedName, String name, List values); } /** @@ -36,6 +66,38 @@ public static Map getRawHeaderMap(HttpHeaders headers) { return accessor.getRawHeaderMap(headers); } + /** + * Adds a header value to the backing map in {@link HttpHeaders}. + *

+ * This bypasses using {@link HttpHeaders#add(String, String)} which uses {@link String#toLowerCase(Locale)}, + * which may be slower than options available by implementing HTTP stacks (such as Netty which has an ASCII + * string class which has optimizations around lowercasing due to ASCII constraints). + * + * @param headers The {@link HttpHeaders} to add the header to. + * @param formattedName The lower-cased header name. + * @param name The original header name. + * @param value The header value. + */ + public static void addInternal(HttpHeaders headers, String formattedName, String name, String value) { + accessor.addInternal(headers, formattedName, name, value); + } + + /** + * Sets a header value to the backing map in {@link HttpHeaders}. + *

+ * This bypasses using {@link HttpHeaders#set(String, List)} which uses {@link String#toLowerCase(Locale)}, + * which may be slower than options available by implementing HTTP stacks (such as JDK HttpClient where all + * response header names are already lowercased). + * + * @param headers The {@link HttpHeaders} to set the header to. + * @param formattedName The lower-cased header name. + * @param name The original header name. + * @param values The header values. + */ + public static void setInternal(HttpHeaders headers, String formattedName, String name, List values) { + accessor.setInternal(headers, formattedName, name, values); + } + /** * Sets the {@link HttpHeadersAccessor}. * diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/serializer/SerializerEncoding.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/serializer/SerializerEncoding.java index 4d4bf4985d5f..c8207428a790 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/serializer/SerializerEncoding.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/serializer/SerializerEncoding.java @@ -9,9 +9,6 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.logging.LogLevel; -import java.util.Map; -import java.util.TreeMap; - /** * Supported serialization encoding formats. */ @@ -32,20 +29,6 @@ public enum SerializerEncoding { TEXT; private static final ClientLogger LOGGER = new ClientLogger(SerializerEncoding.class); - private static final Map SUPPORTED_MIME_TYPES; - - static { - // Encodings and suffixes from: https://tools.ietf.org/html/rfc6838 - SUPPORTED_MIME_TYPES = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - SUPPORTED_MIME_TYPES.put("text/xml", XML); - SUPPORTED_MIME_TYPES.put("application/xml", XML); - SUPPORTED_MIME_TYPES.put("application/json", JSON); - SUPPORTED_MIME_TYPES.put("text/css", TEXT); - SUPPORTED_MIME_TYPES.put("text/csv", TEXT); - SUPPORTED_MIME_TYPES.put("text/html", TEXT); - SUPPORTED_MIME_TYPES.put("text/javascript", TEXT); - SUPPORTED_MIME_TYPES.put("text/plain", TEXT); - } /** * Determines the serializer encoding to use based on the Content-Type header. @@ -63,7 +46,7 @@ public static SerializerEncoding fromHeaders(HttpHeaders headers) { int contentTypeEnd = mimeContentType.indexOf(';'); String contentType = (contentTypeEnd == -1) ? mimeContentType : mimeContentType.substring(0, contentTypeEnd); - final SerializerEncoding encoding = SUPPORTED_MIME_TYPES.get(contentType); + SerializerEncoding encoding = checkForKnownEncoding(contentType); if (encoding != null) { return encoding; } @@ -97,4 +80,43 @@ public static SerializerEncoding fromHeaders(HttpHeaders headers) { return JSON; } + + /* + * There is a limited set of serialization encodings that are known ahead of time. Instead of using a TreeMap with + * a case-insensitive comparator, use an optimized search specifically for the known encodings. + */ + private static SerializerEncoding checkForKnownEncoding(String contentType) { + int length = contentType.length(); + + // Check the length of the content type first as it is a quick check. + if (length != 8 && length != 9 && length != 10 && length != 15 && length != 16) { + return null; + } + + if ("text/".regionMatches(true, 0, contentType, 0, 5)) { + if (length == 8) { + if ("xml".regionMatches(true, 0, contentType, 5, 3)) { + return XML; + } else if ("csv".regionMatches(true, 0, contentType, 5, 3)) { + return TEXT; + } else if ("css".regionMatches(true, 0, contentType, 5, 3)) { + return TEXT; + } + } else if (length == 9 && "html".regionMatches(true, 0, contentType, 5, 4)) { + return TEXT; + } else if (length == 10 && "plain".regionMatches(true, 0, contentType, 5, 5)) { + return TEXT; + } else if (length == 15 && "javascript".regionMatches(true, 0, contentType, 5, 10)) { + return TEXT; + } + } else if ("application/".regionMatches(true, 0, contentType, 0, 12)) { + if (length == 16 && "json".regionMatches(true, 0, contentType, 12, 4)) { + return JSON; + } else if (length == 15 && "xml".regionMatches(true, 0, contentType, 12, 3)) { + return XML; + } + } + + return null; + } } diff --git a/sdk/core/azure-core/src/test/java/com/azure/core/http/policy/PolicyConsumesResponseBodyTest.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/policy/PolicyConsumesResponseBodyTest.java new file mode 100644 index 000000000000..06573971f1f9 --- /dev/null +++ b/sdk/core/azure-core/src/test/java/com/azure/core/http/policy/PolicyConsumesResponseBodyTest.java @@ -0,0 +1,430 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.http.policy; + +import com.azure.core.SyncAsyncExtension; +import com.azure.core.SyncAsyncTest; +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.*; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousByteChannel; +import java.nio.channels.WritableByteChannel; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; + +import static com.azure.core.http.HttpHeaderName.*; +import static org.junit.jupiter.api.Assertions.*; + +public class PolicyConsumesResponseBodyTest { + + private static final TokenCredential NOOP_CREDENTIAL + = request -> Mono.just(new AccessToken("token", OffsetDateTime.MAX)); + + @ParameterizedTest + @ValueSource(booleans = { true, false }) + public void testResponseClosureOn401Sync(boolean authorizeOnChallenge) { + AtomicInteger tryCount = new AtomicInteger(0); + + AtomicReference response401 = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new BearerPolicyImpl(authorizeOnChallenge, NOOP_CREDENTIAL, "scope")) + .httpClient(new TestHttpClient(r -> { + if (tryCount.getAndIncrement() == 0) { + TestHttpResponse r401 = createWithSyncBody(r, 401, 424242); + r401.headers.set(WWW_AUTHENTICATE, "Bearer"); + response401.set(r401); + return r401; + } + return createWithSyncBody(r, 200, 42); + })) + .build(); + + HttpResponse response = pipeline.sendSync(new HttpRequest(HttpMethod.GET, "https://fake"), Context.NONE); + assertEquals(authorizeOnChallenge ? 200 : 401, response.getStatusCode()); + assertEquals(authorizeOnChallenge ? 2 : 1, tryCount.get()); + + if (authorizeOnChallenge) { + assertTrue(response401.get().isConsumedOrClosed()); + } + assertInstanceOf(TestHttpResponse.class, response); + assertFalse(((TestHttpResponse) response).isConsumedOrClosed()); + } + + @ParameterizedTest + @ValueSource(booleans = { true, false }) + public void testResponseClosureOn401Async(boolean authorizeOnChallenge) { + AtomicInteger tryCount = new AtomicInteger(0); + + AtomicReference response401 = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new BearerPolicyImpl(authorizeOnChallenge, NOOP_CREDENTIAL, "scope")) + .httpClient(new TestHttpClient(r -> { + if (tryCount.getAndIncrement() == 0) { + TestHttpResponse r401 = createWithAsyncBody(r, 401, 424242); + r401.headers.set(WWW_AUTHENTICATE, "Bearer"); + response401.set(r401); + return r401; + } + return createWithAsyncBody(r, 200, 42); + })) + .build(); + + HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, "https://fake")).block(); + assertEquals(authorizeOnChallenge ? 200 : 401, response.getStatusCode()); + assertEquals(authorizeOnChallenge ? 2 : 1, tryCount.get()); + + if (authorizeOnChallenge) { + assertTrue(response401.get().isConsumedOrClosed()); + } + + assertInstanceOf(TestHttpResponse.class, response); + assertFalse(((TestHttpResponse) response).isConsumedOrClosed()); + } + + @SyncAsyncTest + public void testResponseClosureOn401AndException() throws Exception { + AtomicInteger tryCount = new AtomicInteger(0); + + AtomicReference responseException = new AtomicReference<>(); + HttpPipeline pipeline = new HttpPipelineBuilder().policies(new BearerPolicyImpl(true, NOOP_CREDENTIAL, "scope")) + .httpClient(new TestHttpClient(r -> { + if (tryCount.getAndIncrement() == 0) { + TestHttpResponse r401 + = createWithAsyncBodyAndException(r, 401, 424242, new IOException("Fake exception")); + r401.headers.set(WWW_AUTHENTICATE, "Bearer"); + responseException.set(r401); + return r401; + } + return createWithSyncBody(r, 200, 42); + })) + .build(); + + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://fake"); + HttpResponse response = SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request).block()); + + assertEquals(200, response.getStatusCode()); + + assertEquals(2, tryCount.get()); + assertTrue(responseException.get().isConsumedOrClosed()); + assertInstanceOf(TestHttpResponse.class, response); + assertFalse(((TestHttpResponse) response).isConsumedOrClosed()); + } + + @SyncAsyncTest + public void testResponseClosureOn302() throws Exception { + AtomicInteger tryCount = new AtomicInteger(0); + + AtomicReference response302 = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RedirectPolicy()).httpClient(new TestHttpClient(r -> { + if (tryCount.getAndIncrement() == 0) { + TestHttpResponse r302 = createWithAsyncBody(r, 302, 424242); + r302.headers.set(LOCATION, "https://fake"); + response302.set(r302); + return r302; + } + return createWithAsyncBody(r, 200, 42); + })).build(); + + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://fake"); + HttpResponse response = SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request).block()); + + assertEquals(200, response.getStatusCode()); + + assertEquals(2, tryCount.get()); + assertTrue(response302.get().isConsumedOrClosed()); + assertInstanceOf(TestHttpResponse.class, response); + assertFalse(((TestHttpResponse) response).isConsumedOrClosed()); + } + + @SyncAsyncTest + public void testResponseClosureOn302AndException() throws Exception { + AtomicInteger tryCount = new AtomicInteger(0); + + AtomicReference responseException = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RedirectPolicy()).httpClient(new TestHttpClient(r -> { + if (tryCount.getAndIncrement() == 0) { + TestHttpResponse rEx + = createWithAsyncBodyAndException(r, 302, 424242, new IOException("Fake exception")); + rEx.headers.set(LOCATION, "https://fake"); + responseException.set(rEx); + return rEx; + } + return createWithSyncBody(r, 200, 42); + })).build(); + + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://fake"); + HttpResponse response = SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request).block()); + + assertEquals(200, response.getStatusCode()); + + assertEquals(2, tryCount.get()); + assertTrue(responseException.get().isConsumedOrClosed()); + assertInstanceOf(TestHttpResponse.class, response); + assertFalse(((TestHttpResponse) response).isConsumedOrClosed()); + } + + @SyncAsyncTest + public void testResponseClosureOn503() throws Exception { + AtomicInteger tryCount = new AtomicInteger(0); + + AtomicReference response503 = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy()).httpClient(new TestHttpClient(r -> { + if (tryCount.getAndIncrement() == 0) { + response503.set(createWithSyncBody(r, 503, 424242)); + return response503.get(); + } + return createWithSyncBody(r, 200, 42); + })).build(); + + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://fake"); + HttpResponse response = SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request).block()); + + assertEquals(200, response.getStatusCode()); + + assertEquals(2, tryCount.get()); + assertTrue(response503.get().isConsumedOrClosed()); + assertInstanceOf(TestHttpResponse.class, response); + assertFalse(((TestHttpResponse) response).isConsumedOrClosed()); + } + + @SyncAsyncTest + public void testResponseClosureOn503AndException() throws Exception { + AtomicInteger tryCount = new AtomicInteger(0); + + AtomicReference responseException = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy()).httpClient(new TestHttpClient(r -> { + if (tryCount.getAndIncrement() == 0) { + TestHttpResponse rEx + = createWithAsyncBodyAndException(r, 503, 424242, new IOException("Fake exception")); + responseException.set(rEx); + return rEx; + } + return createWithSyncBody(r, 200, 42); + })).build(); + + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://fake"); + HttpResponse response = SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request).block()); + + assertEquals(200, response.getStatusCode()); + + assertEquals(2, tryCount.get()); + assertTrue(responseException.get().isConsumedOrClosed()); + assertInstanceOf(TestHttpResponse.class, response); + assertFalse(((TestHttpResponse) response).isConsumedOrClosed()); + } + + private TestHttpResponse createWithSyncBody(HttpRequest request, int statusCode, int contentLength) { + HttpHeaders headers = new HttpHeaders().set(CONTENT_LENGTH, Integer.toString(contentLength)); + return new TestHttpResponse(request, statusCode, headers, new ByteArrayInputStream(new byte[contentLength])); + } + + private TestHttpResponse createWithAsyncBody(HttpRequest request, int statusCode, int contentLength) { + HttpHeaders headers = new HttpHeaders().set(CONTENT_LENGTH, Integer.toString(contentLength)); + return new TestHttpResponse(request, statusCode, headers, Flux.create(s -> { + for (int remaining = contentLength; remaining > 0; remaining -= 10) { + byte[] bytes = new byte[Math.min(10, remaining)]; + s.next(ByteBuffer.wrap(bytes)); + } + s.complete(); + })); + } + + private TestHttpResponse createWithAsyncBodyAndException(HttpRequest request, int statusCode, int contentLength, + Exception exception) { + HttpHeaders headers = new HttpHeaders().set(CONTENT_LENGTH, Integer.toString(contentLength)); + return new TestHttpResponse(request, statusCode, headers, Flux.create(s -> { + byte[] bytes = new byte[Math.min(10, contentLength)]; + s.next(ByteBuffer.wrap(bytes)); + s.error(exception); + })); + } + + private class BearerPolicyImpl extends BearerTokenAuthenticationPolicy { + private final boolean authorize; + + BearerPolicyImpl(boolean authorize, TokenCredential credential, String... scopes) { + super(credential, scopes); + this.authorize = authorize; + } + + @Override + public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, HttpResponse response) { + return authorize; + } + + @Override + public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { + return Mono.just(authorize); + } + } + + private static class TestHttpClient implements HttpClient { + private final Function responseProvider; + + TestHttpClient(Function responseProvider) { + this.responseProvider = responseProvider; + } + + @Override + public Mono send(HttpRequest request) { + return Mono.just(responseProvider.apply(request)); + } + + @Override + public HttpResponse sendSync(HttpRequest request, Context context) { + return responseProvider.apply(request); + } + } + + public class TestHttpResponse extends HttpResponse { + + private final int statusCode; + + private final HttpHeaders headers; + + private final Flux bodyFlux; + private final ByteArrayInputStream bodyStream; + private boolean closed = false; + private boolean consumed = false; + + public TestHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, Flux body) { + super(request); + this.statusCode = statusCode; + this.headers = headers; + this.bodyFlux = body.doFinally(__ -> consumed = true); + this.bodyStream = null; + } + + public TestHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, ByteArrayInputStream body) { + super(request); + this.statusCode = statusCode; + this.headers = headers; + this.bodyStream = body; + this.bodyFlux = null; + } + + public boolean isConsumedOrClosed() { + return closed || (bodyStream != null ? bodyStream.available() == 0 : consumed); + } + + @Override + public int getStatusCode() { + return statusCode; + } + + @Override + @Deprecated + public String getHeaderValue(String name) { + return headers.getValue(name); + } + + @Override + public String getHeaderValue(HttpHeaderName headerName) { + return headers.getValue(headerName); + } + + @Override + public HttpHeaders getHeaders() { + return this.headers; + } + + @Override + public Mono getBodyAsByteArray() { + if (bodyStream != null) { + return Mono.just(BinaryData.fromStream(bodyStream).toBytes()); + } else { + return FluxUtil.collectBytesInByteBufferStream(bodyFlux); + } + } + + @Override + public Flux getBody() { + if (bodyStream != null) { + return FluxUtil.toFluxByteBuffer(bodyStream); + } else { + return bodyFlux; + } + } + + @Override + public Mono getBodyAsString() { + return getBodyAsString(StandardCharsets.UTF_8); + } + + @Override + public Mono getBodyAsString(Charset charset) { + return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); + } + + @Override + public BinaryData getBodyAsBinaryData() { + if (bodyStream != null) { + return BinaryData.fromStream(bodyStream); + } else { + return BinaryData.fromFlux(bodyFlux).block(); + } + } + + @Override + public Mono getBodyAsInputStream() { + if (bodyStream != null) { + return Mono.just(bodyStream); + } else { + return getBodyAsByteArray().map(ByteArrayInputStream::new); + } + } + + @Override + public HttpResponse buffer() { + return new MockHttpResponse(getRequest(), getStatusCode(), getHeaders(), getBodyAsBinaryData().toBytes()); + } + + @Override + public Mono writeBodyToAsync(AsynchronousByteChannel channel) { + return FluxUtil.writeToAsynchronousByteChannel(getBody(), channel); + } + + @Override + public void writeBodyTo(WritableByteChannel channel) throws IOException { + FluxUtil.writeToWritableByteChannel(getBody(), channel).block(); + } + + @Override + public void close() { + this.closed = true; + if (bodyStream != null) { + try { + bodyStream.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + } +} diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml b/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml index ae5e2dfef8f8..627124a3d33d 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml +++ b/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml @@ -101,7 +101,7 @@ Licensed under the MIT License. com.azure azure-cosmos-test - 1.0.0-beta.7 + 1.0.0-beta.8 test diff --git a/sdk/cosmos/azure-cosmos-test/CHANGELOG.md b/sdk/cosmos/azure-cosmos-test/CHANGELOG.md index bb5bbe06a853..42e76a6c34c0 100644 --- a/sdk/cosmos/azure-cosmos-test/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-test/CHANGELOG.md @@ -1,5 +1,14 @@ ## Release History +### 1.0.0-beta.8 (Unreleased) + +#### Features Added + +#### Breaking Changes + +#### Bugs Fixed +* Fixed an issue where `FaultInjectionRule` can not apply on partition level when using `Gateway` Mode and non-session consistency - See [40005](https://github.com/Azure/azure-sdk-for-java/pull/40005) + ### 1.0.0-beta.7 (2024-05-03) #### Bugs Fixed diff --git a/sdk/cosmos/azure-cosmos-test/pom.xml b/sdk/cosmos/azure-cosmos-test/pom.xml index cb2d32eb7ac6..7e5429c2cf40 100644 --- a/sdk/cosmos/azure-cosmos-test/pom.xml +++ b/sdk/cosmos/azure-cosmos-test/pom.xml @@ -13,7 +13,7 @@ Licensed under the MIT License. com.azure azure-cosmos-test - 1.0.0-beta.7 + 1.0.0-beta.8 Microsoft Azure Java Cosmos Test Library This package contains core fault injection types for Azure Java Cosmos client. jar diff --git a/sdk/cosmos/azure-cosmos-tests/pom.xml b/sdk/cosmos/azure-cosmos-tests/pom.xml index b55fefbf13ea..cecbe9dc1fd9 100644 --- a/sdk/cosmos/azure-cosmos-tests/pom.xml +++ b/sdk/cosmos/azure-cosmos-tests/pom.xml @@ -104,7 +104,7 @@ Licensed under the MIT License. com.azure azure-cosmos-test - 1.0.0-beta.7 + 1.0.0-beta.8 commons-io diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index 28c11dc76f12..686ee7b6b8e2 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -4,6 +4,8 @@ #### Features Added +* Added support for non-streaming OrderBy query and a query feature `NonStreamingOrderBy` to support Vector Search queries. - See [PR 39897](https://github.com/Azure/azure-sdk-for-java/pull/39897/) + #### Breaking Changes #### Bugs Fixed diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Configs.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Configs.java index da368de5360d..c643379b2fe6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Configs.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Configs.java @@ -166,6 +166,13 @@ public class Configs { public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; + private static final String MAX_ITEM_SIZE_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; + private static final int DEFAULT_MAX_ITEM_SIZE_FOR_VECTOR_SEARCH = 50000; + + private static final String MAX_ITEM_SIZE_FOR_VECTOR_SEARCH_ENABLED = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH_ENABLED"; + + private static final boolean DEFAULT_MAX_ITEM_SIZE_FOR_VECTOR_SEARCH_ENABLED = true; + public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; @@ -484,6 +491,14 @@ public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } + public static int getMaxItemSizeForVectorSearch() { + return getJVMConfigAsInt(MAX_ITEM_SIZE_FOR_VECTOR_SEARCH, DEFAULT_MAX_ITEM_SIZE_FOR_VECTOR_SEARCH); + } + + public static boolean getMaxItemSizeForVectorSearchEnabled() { + return getJVMConfigAsBoolean(MAX_ITEM_SIZE_FOR_VECTOR_SEARCH_ENABLED, DEFAULT_MAX_ITEM_SIZE_FOR_VECTOR_SEARCH_ENABLED); + } + public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosQueryRequestOptionsImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosQueryRequestOptionsImpl.java index 4dc62089acc5..c70ded3a906f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosQueryRequestOptionsImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosQueryRequestOptionsImpl.java @@ -25,6 +25,7 @@ public final class CosmosQueryRequestOptionsImpl extends CosmosQueryRequestOptio private boolean queryPlanRetrievalDisallowed; private boolean emptyPageDiagnosticsEnabled; private String queryName; + private Integer maxItemSizeForVectorSearch; private List cancelledRequestDiagnosticsTracker = new ArrayList<>(); /** @@ -62,6 +63,7 @@ public CosmosQueryRequestOptionsImpl(CosmosQueryRequestOptionsImpl options) { this.queryName = options.queryName; this.feedRange = options.feedRange; this.cancelledRequestDiagnosticsTracker = options.cancelledRequestDiagnosticsTracker; + this.maxItemSizeForVectorSearch = options.maxItemSizeForVectorSearch; } /** @@ -196,6 +198,26 @@ public CosmosQueryRequestOptionsImpl setMaxItemCount(Integer maxItemCount) { return this; } + /** + * Gets the maximum item size to fetch during non-streaming order by queries. + * + * @return the max number of items for vector search. + */ + public Integer getMaxItemSizeForVectorSearch() { + return maxItemSizeForVectorSearch; + } + + /** + * Sets the maximum item size to fetch during non-streaming order by queries. + * + * @param maxItemSizeForVectorSearch the max number of items for vector search. + * return the CosmosQueryRequestOptions. + */ + public CosmosQueryRequestOptionsImpl setMaxItemSizeForVectorSearch(Integer maxItemSizeForVectorSearch) { + this.maxItemSizeForVectorSearch = maxItemSizeForVectorSearch; + return this; + } + /** * Gets the request continuation token. * diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DocumentQueryExecutionContextFactory.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DocumentQueryExecutionContextFactory.java index a13cfc65348d..7a530816856b 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DocumentQueryExecutionContextFactory.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DocumentQueryExecutionContextFactory.java @@ -4,9 +4,11 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.implementation.BadRequestException; +import com.azure.cosmos.implementation.Configs; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.DiagnosticsClientContext; import com.azure.cosmos.implementation.DocumentCollection; +import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.OperationType; import com.azure.cosmos.implementation.PartitionKeyRange; @@ -239,7 +241,8 @@ private static boolean canCacheQuery(QueryInfo queryInfo) { && !queryInfo.hasTop() && !queryInfo.hasOffset() && !queryInfo.hasDCount() - && !queryInfo.hasOrderBy(); + && !queryInfo.hasOrderBy() + && !queryInfo.hasNonStreamingOrderBy(); } private static boolean isScopedToSinglePartition(CosmosQueryRequestOptions cosmosQueryRequestOptions) { @@ -358,6 +361,37 @@ public static Flux> createSpecia boolean getLazyFeedResponse = queryInfo.hasTop(); + // We need to compute the optimal initial age size for non-streaming order-by queries + if (queryInfo.hasNonStreamingOrderBy() && Configs.getMaxItemSizeForVectorSearchEnabled()) { + // Validate the TOP or LIMIT for non-streaming order-by queries + if (!queryInfo.hasTop() && !queryInfo.hasLimit() && queryInfo.getTop() < 0 && queryInfo.getLimit() < 0) { + throw new NonStreamingOrderByBadRequestException(HttpConstants.StatusCodes.BADREQUEST, + "Executing a vector search query without TOP or LIMIT can consume a large number of RUs" + + "very fast and have long runtimes. Please ensure you are using one of the above two filters" + + "with you vector search query."); + } + // Validate the size of TOP or LIMIT against MaxItemSizeForVectorSearch + int maxLimit = Math.max(queryInfo.hasTop() ? queryInfo.getTop() : 0, + queryInfo.hasLimit() ? queryInfo.getLimit() : 0); + int maxItemSizeForVectorSearch = Math.max(Configs.getMaxItemSizeForVectorSearch(), + ModelBridgeInternal.getMaxItemSizeForVectorSearchFromQueryRequestOptions(cosmosQueryRequestOptions)); + if (maxLimit > maxItemSizeForVectorSearch) { + throw new NonStreamingOrderByBadRequestException(HttpConstants.StatusCodes.BADREQUEST, + "Executing a vector search query with TOP or LIMIT larger than the maxItemSizeForVectorSearch " + + "is not allowed"); + } + // Set initialPageSize based on the smallest of TOP or LIMIT + if (queryInfo.hasTop() || queryInfo.hasLimit()) { + int pageSizeWithTopOrLimit = Math.min(queryInfo.hasTop() ? queryInfo.getTop() : Integer.MAX_VALUE, + queryInfo.hasLimit() ? queryInfo.getLimit() : Integer.MAX_VALUE); + if (initialPageSize > 0) { + initialPageSize = Math.min(pageSizeWithTopOrLimit, initialPageSize); + } else { + initialPageSize = pageSizeWithTopOrLimit; + } + } + } + // We need to compute the optimal initial page size for order-by queries if (queryInfo.hasOrderBy()) { int top; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByBadRequestException.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByBadRequestException.java new file mode 100644 index 000000000000..4b3b41fbc675 --- /dev/null +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByBadRequestException.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.cosmos.implementation.query; + +import com.azure.cosmos.CosmosException; + +public class NonStreamingOrderByBadRequestException extends CosmosException { + + private static final long serialVersionUID = 1L; + + /** + * Creates a new instance of the NonStreamingOrderByBadRequestException class. + * + * @param statusCode the http status code of the response. + * @param errorMessage the error message. + */ + public NonStreamingOrderByBadRequestException(int statusCode, String errorMessage) { + super(statusCode, errorMessage); + } +} diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByDocumentProducer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByDocumentProducer.java new file mode 100644 index 000000000000..c64ef5d1fbda --- /dev/null +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByDocumentProducer.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.implementation.query; + +import com.azure.cosmos.implementation.Document; +import com.azure.cosmos.implementation.DocumentClientRetryPolicy; +import com.azure.cosmos.implementation.RxDocumentServiceRequest; +import com.azure.cosmos.implementation.feedranges.FeedRangeEpkImpl; +import com.azure.cosmos.implementation.query.orderbyquery.OrderbyRowComparer; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.FeedResponse; +import reactor.core.publisher.Mono; + +import java.util.UUID; +import java.util.function.Function; +import java.util.function.Supplier; + +public class NonStreamingOrderByDocumentProducer extends DocumentProducer { + private final OrderbyRowComparer consumeComparer; + + NonStreamingOrderByDocumentProducer( + OrderbyRowComparer consumeComparer, + IDocumentQueryClient client, + String collectionResourceId, + CosmosQueryRequestOptions cosmosQueryRequestOptions, + TriFunction createRequestFunc, + Function>> executeRequestFunc, + FeedRangeEpkImpl feedRange, + String collectionLink, + Supplier createRetryPolicyFunc, + Class resourceType, + UUID correlatedActivityId, + int initialPageSize, + String initialContinuationToken, + int top, + Supplier operationContextTextProvider) { + super(client, collectionResourceId, cosmosQueryRequestOptions, createRequestFunc, executeRequestFunc, + collectionLink, createRetryPolicyFunc, resourceType, correlatedActivityId, initialPageSize, + initialContinuationToken, top, feedRange, operationContextTextProvider); + this.consumeComparer = consumeComparer; + } +} diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByDocumentQueryExecutionContext.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByDocumentQueryExecutionContext.java new file mode 100644 index 000000000000..89a8a3065443 --- /dev/null +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByDocumentQueryExecutionContext.java @@ -0,0 +1,264 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.implementation.query; + +import com.azure.cosmos.BridgeInternal; +import com.azure.cosmos.CosmosException; +import com.azure.cosmos.implementation.ClientSideRequestStatistics; +import com.azure.cosmos.implementation.DiagnosticsClientContext; +import com.azure.cosmos.implementation.Document; +import com.azure.cosmos.implementation.DocumentClientRetryPolicy; +import com.azure.cosmos.implementation.DocumentCollection; +import com.azure.cosmos.implementation.HttpConstants; +import com.azure.cosmos.implementation.ImplementationBridgeHelpers; +import com.azure.cosmos.implementation.QueryMetrics; +import com.azure.cosmos.implementation.RequestChargeTracker; +import com.azure.cosmos.implementation.ResourceType; +import com.azure.cosmos.implementation.RxDocumentServiceRequest; +import com.azure.cosmos.implementation.Utils; +import com.azure.cosmos.implementation.feedranges.FeedRangeEpkImpl; +import com.azure.cosmos.implementation.query.orderbyquery.OrderByRowResult; +import com.azure.cosmos.implementation.query.orderbyquery.OrderbyRowComparer; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.FeedResponse; +import com.azure.cosmos.models.ModelBridgeInternal; +import com.azure.cosmos.models.SqlQuerySpec; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +public class NonStreamingOrderByDocumentQueryExecutionContext + extends ParallelDocumentQueryExecutionContextBase { + + private final static + ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = + ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); + + private static final ImplementationBridgeHelpers.FeedResponseHelper.FeedResponseAccessor feedResponseAccessor = + ImplementationBridgeHelpers.FeedResponseHelper.getFeedResponseAccessor(); + + private final static String FormatPlaceHolder = "{documentdb-formattableorderbyquery-filter}"; + private final static String True = "true"; + + private final OrderbyRowComparer consumeComparer; + private final RequestChargeTracker tracker; + private final ConcurrentMap queryMetricMap; + private final Collection clientSideRequestStatistics; + private Flux> orderByObservable; + + private int maxPageSizePerPartition; + + public NonStreamingOrderByDocumentQueryExecutionContext( + DiagnosticsClientContext diagnosticsClientContext, + IDocumentQueryClient client, + ResourceType resourceTypeEnum, + SqlQuerySpec query, + CosmosQueryRequestOptions cosmosQueryRequestOptions, + String resourceLink, + String rewrittenQuery, + OrderbyRowComparer consumeComparer, + UUID correlatedActivityId, + boolean hasSelectValue, + final AtomicBoolean isQueryCancelledOnTimeout) { + super(diagnosticsClientContext, client, resourceTypeEnum, Document.class, query, cosmosQueryRequestOptions, + resourceLink, rewrittenQuery, correlatedActivityId, hasSelectValue, isQueryCancelledOnTimeout); + this.consumeComparer = consumeComparer; + this.tracker = new RequestChargeTracker(); + this.queryMetricMap = new ConcurrentHashMap<>(); + this.clientSideRequestStatistics = ConcurrentHashMap.newKeySet(); + } + + public static Flux> createAsync( + DiagnosticsClientContext diagnosticsClientContext, + IDocumentQueryClient client, + PipelinedDocumentQueryParams initParams, + DocumentCollection collection) { + + QueryInfo queryInfo = initParams.getQueryInfo(); + + NonStreamingOrderByDocumentQueryExecutionContext context = new NonStreamingOrderByDocumentQueryExecutionContext( + diagnosticsClientContext, + client, + initParams.getResourceTypeEnum(), + initParams.getQuery(), + initParams.getCosmosQueryRequestOptions(), + initParams.getResourceLink(), + initParams.getQueryInfo().getRewrittenQuery(), + new OrderbyRowComparer<>(queryInfo.getOrderBy()), + initParams.getCorrelatedActivityId(), + queryInfo.hasSelectValue(), + initParams.isQueryCancelledOnTimeout()); + + context.setTop(initParams.getTop()); + + try { + context.initialize( + initParams.getFeedRanges(), + initParams.getQueryInfo().getOrderBy(), + initParams.getQueryInfo().getOrderByExpressions(), + initParams.getInitialPageSize(), + collection); + + return Flux.just(context); + } catch (CosmosException dce) { + return Flux.error(dce); + } + } + + private void initialize( + List feedRanges, List sortOrders, + Collection orderByExpressions, + int initialPageSize, + DocumentCollection collection) throws CosmosException { + // Since the continuation token will always be null, + // we don't need to handle any initialization based on continuationToken. + // We can directly initialize without any consideration for continuationToken. + super.initialize(collection, + feedRanges.stream().collect(Collectors.toMap( + feedRangeEpk -> feedRangeEpk, + feedRangeEpk -> null)), + initialPageSize, + new SqlQuerySpec(querySpec.getQueryText().replace(FormatPlaceHolder, True), + querySpec.getParameters())); + + orderByObservable = NonStreamingOrderByUtils.nonStreamingOrderedMerge( + consumeComparer, + tracker, + documentProducers, + initialPageSize, + queryMetricMap, + clientSideRequestStatistics); + } + + @Override + protected NonStreamingOrderByDocumentProducer createDocumentProducer( + String collectionRid, + String continuationToken, + int initialPageSize, + CosmosQueryRequestOptions cosmosQueryRequestOptions, + SqlQuerySpec querySpecForInit, + Map commonRequestHeaders, + TriFunction createRequestFunc, + Function>> executeFunc, + Supplier createRetryPolicyFunc, + FeedRangeEpkImpl feedRange) { + return new NonStreamingOrderByDocumentProducer( + consumeComparer, + client, + collectionRid, + cosmosQueryRequestOptions, + createRequestFunc, + executeFunc, + feedRange, + collectionRid, + createRetryPolicyFunc, + Document.class, + correlatedActivityId, + maxPageSizePerPartition, + continuationToken, + top, + this.getOperationContextTextProvider()); + } + + @Override + public Flux> drainAsync(int maxPageSize) { + return this.orderByObservable.transformDeferred(new ItemToPageTransformer(tracker, + maxPageSize, + this.queryMetricMap, + this.clientSideRequestStatistics)); + } + + @Override + public Flux> executeAsync() { + return drainAsync(ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(cosmosQueryRequestOptions)); + } + + private static class ItemToPageTransformer implements + Function>, Flux>> { + private final static int DEFAULT_PAGE_SIZE = 100; + private final RequestChargeTracker tracker; + private final int maxPageSize; + private final ConcurrentMap queryMetricMap; + private final Collection clientSideRequestStatistics; + + public ItemToPageTransformer(RequestChargeTracker tracker, + int maxPageSize, + ConcurrentMap queryMetricsMap, + Collection clientSideRequestStatistics) { + this.tracker = tracker; + this.maxPageSize = maxPageSize > 0 ? maxPageSize : DEFAULT_PAGE_SIZE; + this.queryMetricMap = queryMetricsMap; + this.clientSideRequestStatistics = clientSideRequestStatistics; + } + + private static Map headerResponse(double requestCharge) { + return Utils.immutableMapOf(HttpConstants.HttpHeaders.REQUEST_CHARGE, String.valueOf(requestCharge)); + } + + @Override + public Flux> apply(Flux> source) { + return source + .window(maxPageSize).map(Flux::collectList) + .flatMap(resultListObs -> resultListObs, 1) + .map(orderByRowResults -> { + // construct a page from result with request charge + FeedResponse> feedResponse = feedResponseAccessor.createFeedResponse( + orderByRowResults, + headerResponse(tracker.getAndResetCharge()), + null); + if (!queryMetricMap.isEmpty()) { + for (Map.Entry entry : queryMetricMap.entrySet()) { + BridgeInternal.putQueryMetricsIntoMap(feedResponse, + entry.getKey(), + entry.getValue()); + } + } + return feedResponse; + }) + .concatWith(Flux.defer(() -> { + return Flux.just(feedResponseAccessor.createFeedResponse(Utils.immutableListOf(), + null, null)); + })) + .map(feedOfOrderByRowResults -> { + List unwrappedResults = new ArrayList<>(); + for (OrderByRowResult orderByRowResult : feedOfOrderByRowResults.getResults()) { + unwrappedResults.add(orderByRowResult.getPayload()); + } + FeedResponse feedResponse = BridgeInternal.createFeedResponseWithQueryMetrics(unwrappedResults, + feedOfOrderByRowResults.getResponseHeaders(), + BridgeInternal.queryMetricsFromFeedResponse(feedOfOrderByRowResults), + ModelBridgeInternal.getQueryPlanDiagnosticsContext(feedOfOrderByRowResults), + false, + false, feedOfOrderByRowResults.getCosmosDiagnostics()); + diagnosticsAccessor.addClientSideDiagnosticsToFeed( + feedResponse.getCosmosDiagnostics(), clientSideRequestStatistics); + return feedResponse; + }).switchIfEmpty(Flux.defer(() -> { + // create an empty page if there is no result + FeedResponse frp = BridgeInternal.createFeedResponseWithQueryMetrics(Utils.immutableListOf(), + headerResponse( + tracker.getAndResetCharge()), + queryMetricMap, + null, + false, + false, + null); + diagnosticsAccessor.addClientSideDiagnosticsToFeed( + frp.getCosmosDiagnostics(), clientSideRequestStatistics); + return Flux.just(frp); + })); + } + } +} diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByUtils.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByUtils.java new file mode 100644 index 000000000000..1b4191e26413 --- /dev/null +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/NonStreamingOrderByUtils.java @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.cosmos.implementation.query; + +import com.azure.cosmos.BridgeInternal; +import com.azure.cosmos.implementation.ClientSideRequestStatistics; +import com.azure.cosmos.implementation.Configs; +import com.azure.cosmos.implementation.Document; +import com.azure.cosmos.implementation.ImplementationBridgeHelpers; +import com.azure.cosmos.implementation.QueryMetrics; +import com.azure.cosmos.implementation.RequestChargeTracker; +import com.azure.cosmos.implementation.Resource; +import com.azure.cosmos.implementation.query.orderbyquery.OrderByRowResult; +import com.azure.cosmos.implementation.query.orderbyquery.OrderbyRowComparer; +import reactor.core.publisher.Flux; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.function.Function; + +public class NonStreamingOrderByUtils { + private final static + ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = + ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); + + public static Flux> nonStreamingOrderedMerge(OrderbyRowComparer consumeComparer, + RequestChargeTracker tracker, + List> documentProducers, + int initialPageSize, + Map queryMetricsMap, + Collection clientSideRequestStatistics) { + @SuppressWarnings("unchecked") + Flux>[] fluxes = documentProducers + .subList(0, documentProducers.size()) + .stream() + .map(producer -> + toNonStreamingOrderByQueryResultObservable(producer, tracker, queryMetricsMap, initialPageSize, + consumeComparer, clientSideRequestStatistics)) + .toArray(Flux[]::new); + return Flux.mergeComparingDelayError(1,consumeComparer, fluxes); + } + + private static Flux> toNonStreamingOrderByQueryResultObservable(DocumentProducer producer, + RequestChargeTracker tracker, + Map queryMetricsMap, + int initialPageSize, + OrderbyRowComparer consumeComparer, + Collection clientSideRequestStatisticsList) { + return producer + .produceAsync() + .transformDeferred(new NonStreamingOrderByUtils.PageToItemTransformer(tracker, queryMetricsMap, initialPageSize, + consumeComparer, clientSideRequestStatisticsList)); + } + + private static class PageToItemTransformer implements + Function.DocumentProducerFeedResponse>, Flux>> { + private final RequestChargeTracker tracker; + private final Map queryMetricsMap; + private final Integer initialPageSize; + private final OrderbyRowComparer consumeComparer; + private final Collection clientSideRequestStatistics; + + private PageToItemTransformer(RequestChargeTracker tracker, Map queryMetricsMap, + Integer initialPageSize, OrderbyRowComparer consumeComparer, + Collection clientSideRequestStatistics) { + this.tracker = tracker; + this.queryMetricsMap = queryMetricsMap; + this.initialPageSize = initialPageSize; + this.consumeComparer = consumeComparer; + this.clientSideRequestStatistics = clientSideRequestStatistics; + } + + @Override + public Flux> apply(Flux.DocumentProducerFeedResponse> source) { + PriorityBlockingQueue> priorityQueue = new PriorityBlockingQueue<>(initialPageSize, consumeComparer); + + return source.flatMap(documentProducerFeedResponse -> { + clientSideRequestStatistics.addAll( + diagnosticsAccessor.getClientSideRequestStatisticsForQueryPipelineAggregations(documentProducerFeedResponse + .pageResult.getCosmosDiagnostics())); + + QueryMetrics.mergeQueryMetricsMap(queryMetricsMap, + BridgeInternal.queryMetricsFromFeedResponse(documentProducerFeedResponse.pageResult)); + List results = documentProducerFeedResponse.pageResult.getResults(); + results.forEach(r -> { + OrderByRowResult orderByRowResult = new OrderByRowResult( + r.toJson(), + documentProducerFeedResponse.sourceFeedRange, + null); + if (Configs.getMaxItemSizeForVectorSearchEnabled()) { + if (priorityQueue.size() < initialPageSize) { + priorityQueue.add(orderByRowResult); + } else { + priorityQueue.add(orderByRowResult); + priorityQueue.poll(); + } + } else { + priorityQueue.add(orderByRowResult); + } + + }); + tracker.addCharge(documentProducerFeedResponse.pageResult.getRequestCharge()); + // Returning an empty Flux since we are only processing and managing state here + return Flux.empty(); + }, 1) + .thenMany(Flux.defer(() -> Flux.fromIterable(priorityQueue))); + } + } +} diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/ParallelDocumentQueryExecutionContext.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/ParallelDocumentQueryExecutionContext.java index 020b8633d2be..6ed30d3a7fbe 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/ParallelDocumentQueryExecutionContext.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/ParallelDocumentQueryExecutionContext.java @@ -106,7 +106,8 @@ public static Flux> createAsync( || queryInfo.hasAggregates() || queryInfo.hasGroupBy() || queryInfo.hasDCount() - || queryInfo.hasDistinct()), + || queryInfo.hasDistinct() + || queryInfo.hasNonStreamingOrderBy()), initParams.isQueryCancelledOnTimeout()); context.setTop(initParams.getTop()); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedDocumentQueryExecutionContext.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedDocumentQueryExecutionContext.java index 7b6104271762..a6ea9fc2d5f6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedDocumentQueryExecutionContext.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedDocumentQueryExecutionContext.java @@ -15,6 +15,8 @@ import java.util.function.BiFunction; +import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. @@ -53,12 +55,17 @@ private static BiFunction, Flux { CosmosQueryRequestOptions orderByCosmosQueryRequestOptions = qryOptAccessor.clone(requestOptions); - ModelBridgeInternal.setQueryRequestOptionsContinuationToken(orderByCosmosQueryRequestOptions, continuationToken); - qryOptAccessor.getImpl(orderByCosmosQueryRequestOptions).setCustomItemSerializer(null); - - documentQueryParams.setCosmosQueryRequestOptions(orderByCosmosQueryRequestOptions); - - return OrderByDocumentQueryExecutionContext.createAsync(diagnosticsClientContext, client, documentQueryParams, collection); + if (queryInfo.hasNonStreamingOrderBy()) { + checkNotNull(continuationToken, "Can not use a continuation token for a vector search query "); + qryOptAccessor.getImpl(orderByCosmosQueryRequestOptions).setCustomItemSerializer(null); + documentQueryParams.setCosmosQueryRequestOptions(orderByCosmosQueryRequestOptions); + return NonStreamingOrderByDocumentQueryExecutionContext.createAsync(diagnosticsClientContext, client, documentQueryParams, collection); + } else { + ModelBridgeInternal.setQueryRequestOptionsContinuationToken(orderByCosmosQueryRequestOptions, continuationToken); + qryOptAccessor.getImpl(orderByCosmosQueryRequestOptions).setCustomItemSerializer(null); + documentQueryParams.setCosmosQueryRequestOptions(orderByCosmosQueryRequestOptions); + return OrderByDocumentQueryExecutionContext.createAsync(diagnosticsClientContext, client, documentQueryParams, collection); + } }; } else { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedQueryExecutionContext.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedQueryExecutionContext.java index c7f67711fabd..6c3fa2827216 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedQueryExecutionContext.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedQueryExecutionContext.java @@ -137,7 +137,7 @@ public Flux> executeAsync() { } private static QueryInfo validateQueryInfo(QueryInfo queryInfo) { - if (queryInfo.hasOrderBy() || queryInfo.hasAggregates() || queryInfo.hasGroupBy()) { + if (queryInfo.hasOrderBy() || queryInfo.hasAggregates() || queryInfo.hasGroupBy() || queryInfo.hasNonStreamingOrderBy()) { // Any query with order by, aggregates or group by needs to go through the Document query pipeline throw new IllegalStateException("This query must not use the simple query pipeline."); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedQueryExecutionContextBase.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedQueryExecutionContextBase.java index 232f942b8590..39c6c27efad8 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedQueryExecutionContextBase.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PipelinedQueryExecutionContextBase.java @@ -63,7 +63,8 @@ public static Flux> createAsync( || queryInfo.hasAggregates() || queryInfo.hasGroupBy() || queryInfo.hasDCount() - || queryInfo.hasDistinct()) { + || queryInfo.hasDistinct() + || queryInfo.hasNonStreamingOrderBy()) { return PipelinedDocumentQueryExecutionContext.createAsyncCore( diagnosticsClientContext, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryFeature.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryFeature.java index ce2b4865767c..1dd3e5928b92 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryFeature.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryFeature.java @@ -14,5 +14,6 @@ public enum QueryFeature { OrderBy, Top, NonValueAggregate, - DCount + DCount, + NonStreamingOrderBy } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryInfo.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryInfo.java index 65efb92c3325..48870a5ae52d 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryInfo.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryInfo.java @@ -36,6 +36,7 @@ public final class QueryInfo extends JsonSerializable { private DistinctQueryType distinctQueryType; private QueryPlanDiagnosticsContext queryPlanDiagnosticsContext; private DCountInfo dCountInfo; + private boolean nonStreamingOrderBy; public QueryInfo() { } @@ -160,6 +161,11 @@ public boolean hasGroupBy() { return groupByExpressions != null && !groupByExpressions.isEmpty(); } + public boolean hasNonStreamingOrderBy() { + this.nonStreamingOrderBy = Boolean.TRUE.equals(super.getBoolean("hasNonStreamingOrderBy")); + return this.nonStreamingOrderBy; + } + public Map getGroupByAliasToAggregateType(){ Map groupByAliasToAggregateMap; groupByAliasToAggregateMap = super.getMap("groupByAliasToAggregateType"); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryPlanRetriever.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryPlanRetriever.java index ce91ff2029e9..83f82dbde363 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryPlanRetriever.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryPlanRetriever.java @@ -43,7 +43,8 @@ class QueryPlanRetriever { QueryFeature.GroupBy.name() + ", " + QueryFeature.Top.name() + ", " + QueryFeature.DCount.name() + ", " + - QueryFeature.NonValueAggregate.name(); + QueryFeature.NonValueAggregate.name() + ", " + + QueryFeature.NonStreamingOrderBy.name(); static Mono getQueryPlanThroughGatewayAsync(DiagnosticsClientContext diagnosticsClientContext, IDocumentQueryClient queryClient, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosQueryRequestOptions.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosQueryRequestOptions.java index c9bf3909fd5d..309fb87a8b22 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosQueryRequestOptions.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosQueryRequestOptions.java @@ -256,6 +256,15 @@ CosmosQueryRequestOptions setMaxItemCount(Integer maxItemCount) { return this; } + /** + * Gets the maximum item size to fetch during non-streaming order by queries. + * + * @return the max number of items for vector search. + */ + public Integer getMaxItemSizeForVectorSearch() { + return this.actualRequestOptions.getMaxItemSizeForVectorSearch(); + } + /** * Gets the request continuation token. * diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java index 4931c9b3b1b0..e814cc16681b 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java @@ -544,6 +544,11 @@ public static Integer getMaxItemCountFromQueryRequestOptions(CosmosQueryRequestO return options.getMaxItemCount(); } + @Warning(value = INTERNAL_USE_ONLY_WARNING) + public static Integer getMaxItemSizeForVectorSearchFromQueryRequestOptions(CosmosQueryRequestOptions options) { + return options.getMaxItemSizeForVectorSearch(); + } + @Warning(value = INTERNAL_USE_ONLY_WARNING) public static String getRequestContinuationFromQueryRequestOptions(CosmosQueryRequestOptions options) { return options.getRequestContinuation(); diff --git a/sdk/digitaltwins/azure-digitaltwins-core/src/test/java/com/azure/digitaltwins/core/DigitalTwinsTestBase.java b/sdk/digitaltwins/azure-digitaltwins-core/src/test/java/com/azure/digitaltwins/core/DigitalTwinsTestBase.java index 3009b8a4fcbf..2cbbb0aad9f6 100644 --- a/sdk/digitaltwins/azure-digitaltwins-core/src/test/java/com/azure/digitaltwins/core/DigitalTwinsTestBase.java +++ b/sdk/digitaltwins/azure-digitaltwins-core/src/test/java/com/azure/digitaltwins/core/DigitalTwinsTestBase.java @@ -10,7 +10,6 @@ import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.test.TestMode; import com.azure.core.test.TestProxyTestBase; import com.azure.core.test.models.CustomMatcher; import com.azure.core.util.Configuration; @@ -141,9 +140,7 @@ static T deserializeJsonString(String rawJsonString, Class clazz) throws } void waitIfLive(int waitTimeInSeconds) throws InterruptedException { - if (this.getTestMode() == TestMode.LIVE || this.getTestMode() == TestMode.RECORD) { - Thread.sleep(waitTimeInSeconds * 1000); - } + sleepIfRunningAgainstService(waitTimeInSeconds * 1000L); } void waitIfLive() throws InterruptedException { diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataAggregatorTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataAggregatorTest.java index c50f9d4b94a6..86101a67af93 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataAggregatorTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataAggregatorTest.java @@ -5,6 +5,8 @@ import com.azure.core.amqp.exception.AmqpErrorCondition; import com.azure.core.amqp.exception.AmqpException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.EventHubBufferedProducerAsyncClient.BufferedProducerClientOptions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -29,6 +31,8 @@ import static org.mockito.Mockito.when; public class EventDataAggregatorTest { + private static final ClientLogger LOGGER = new ClientLogger(EventDataAggregatorTest.class); + private static final String NAMESPACE = "test.namespace"; private static final String PARTITION_ID = "test-id"; @@ -175,7 +179,7 @@ public void pushesBatchAfterMaxTime() { case 1: return batch2; default: - System.out.println("Invoked get batch for the xth time:" + current); + LOGGER.log(LogLevel.VERBOSE, () -> "Invoked get batch for the xth time:" + current); return batch3; } }; diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedPartitionProducerTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedPartitionProducerTest.java index 5ea403598f74..f7714375106c 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedPartitionProducerTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedPartitionProducerTest.java @@ -5,6 +5,8 @@ import com.azure.core.amqp.AmqpRetryOptions; import com.azure.core.amqp.exception.AmqpException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.EventHubBufferedProducerAsyncClient.BufferedProducerClientOptions; import com.azure.messaging.eventhubs.models.CreateBatchOptions; import com.azure.messaging.eventhubs.models.SendBatchFailedContext; @@ -49,6 +51,8 @@ */ @Isolated public class EventHubBufferedPartitionProducerTest { + private static final ClientLogger LOGGER = new ClientLogger(EventHubBufferedPartitionProducerTest.class); + private static final String PARTITION_ID = "10"; private static final String NAMESPACE = "test-eventhubs-namespace"; private static final String EVENT_HUB_NAME = "test-hub"; @@ -312,7 +316,7 @@ public void getBufferedEventCounts() throws InterruptedException { final BufferedProducerClientOptions options = new BufferedProducerClientOptions(); options.setMaxWaitTime(Duration.ofSeconds(5)); options.setSendSucceededContext(context -> { - System.out.println("Batch received."); + LOGGER.log(LogLevel.VERBOSE, () -> "Batch received."); holder.onSucceed(context); success.countDown(); }); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClientIntegrationTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClientIntegrationTest.java index 33de24fb11ff..d117c200ee0d 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClientIntegrationTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClientIntegrationTest.java @@ -4,6 +4,7 @@ package com.azure.messaging.eventhubs; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.models.SendBatchSucceededContext; import com.azure.messaging.eventhubs.models.SendOptions; import org.junit.jupiter.api.Tag; @@ -196,9 +197,9 @@ public void publishWithPartitionKeys() throws InterruptedException { }); return Mono.delay(Duration.ofSeconds(delay)).then(producer.enqueueEvent(eventData, sendOptions) - .doFinally(signal -> { - System.out.printf("\t[%s] %s Published event.%n", expectedPartitionId, formatter.format(Instant.now())); - })); + .doFinally(signal -> logger.log(LogLevel.VERBOSE, + () -> String.format("\t[%s] %s Published event.%n", expectedPartitionId, + formatter.format(Instant.now()))))); }).collect(Collectors.toList()); // Waiting for at least maxWaitTime because events will get published by then. diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientTest.java index 8b9bdaa665eb..06a1e658e7e7 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientTest.java @@ -24,6 +24,7 @@ import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.tracing.SpanKind; import com.azure.core.util.tracing.StartSpanOptions; import com.azure.core.util.tracing.Tracer; @@ -960,9 +961,9 @@ private void assertStartOptions(StartSpanOptions startOpts) { } private void assertPartition(String partitionId, PartitionEvent event) { - System.out.println("Event received: " + event.getPartitionContext().getPartitionId()); + LOGGER.log(LogLevel.VERBOSE, () -> "Event received: " + event.getPartitionContext().getPartitionId()); final Object value = event.getData().getProperties().get(PARTITION_ID_HEADER); - Assertions.assertTrue(value instanceof String); + Assertions.assertInstanceOf(String.class, value); Assertions.assertEquals(partitionId, value); Assertions.assertEquals(partitionId, event.getPartitionContext().getPartitionId()); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientTest.java index 2843c5f92bd9..214592630966 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientTest.java @@ -15,6 +15,8 @@ import com.azure.core.util.ClientOptions; import com.azure.core.util.Configuration; import com.azure.core.util.IterableStream; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.implementation.ClientConstants; import com.azure.messaging.eventhubs.implementation.EventHubAmqpConnection; import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; @@ -64,6 +66,8 @@ import static org.mockito.Mockito.when; public class EventHubConsumerClientTest { + private static final ClientLogger LOGGER = new ClientLogger(EventHubConsumerClientTest.class); + private static final ClientOptions CLIENT_OPTIONS = new ClientOptions(); private static final String PAYLOAD = "hello"; private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8); @@ -131,10 +135,10 @@ AmqpTransportType.AMQP_WEB_SOCKETS, new AmqpRetryOptions(), ProxyOptions.SYSTEM_ when(connection.createReceiveLink(any(), argThat(name -> name.endsWith(PARTITION_ID)), any(EventPosition.class), any(ReceiveOptions.class), anyString())).thenReturn( Mono.fromCallable(() -> { - System.out.println("Returning first link"); + LOGGER.log(LogLevel.VERBOSE, () -> "Returning first link"); return amqpReceiveLink; }), Mono.fromCallable(() -> { - System.out.println("Returning second link"); + LOGGER.log(LogLevel.VERBOSE, () -> "Returning second link"); return amqpReceiveLink2; })); @@ -291,11 +295,11 @@ public void receivesMultipleTimes() { final IterableStream receive2 = consumer.receiveFromPartition(PARTITION_ID, secondReceive, EventPosition.earliest()); // Assert - System.out.println("First receive."); + LOGGER.log(LogLevel.VERBOSE, () -> "First receive."); final Map firstActual = receive.stream() .collect(Collectors.toMap(EventHubConsumerClientTest::getPositionId, Function.identity())); - System.out.println("Second receive."); + LOGGER.log(LogLevel.VERBOSE, () -> "Second receive."); final Map secondActual = receive2.stream() .collect(Collectors.toMap(EventHubConsumerClientTest::getPositionId, Function.identity())); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java index bc8d559f26c5..8943cbb8204a 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java @@ -5,6 +5,7 @@ import com.azure.core.util.IterableStream; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.models.EventPosition; import com.azure.messaging.eventhubs.models.PartitionEvent; import com.azure.messaging.eventhubs.models.SendOptions; @@ -59,7 +60,7 @@ protected void beforeTest() { for (Map.Entry entry : integrationTestData.entrySet()) { testData = entry.getValue(); - System.out.printf("Getting entry for: %s%n", testData.getPartitionId()); + logger.log(LogLevel.VERBOSE, () -> "Getting entry for: " + testData.getPartitionId()); break; } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientBuilderTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientBuilderTest.java index 6399a399f8e3..467b2a27e703 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientBuilderTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientBuilderTest.java @@ -8,6 +8,8 @@ import com.azure.core.util.ClientOptions; import com.azure.core.util.Configuration; import com.azure.core.util.TracingOptions; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.implementation.ClientConstants; import com.azure.messaging.eventhubs.models.CloseContext; import com.azure.messaging.eventhubs.models.ErrorContext; @@ -35,6 +37,7 @@ * Unit tests for {@link EventProcessorClientBuilder}. */ public class EventProcessorClientBuilderTest { + private static final ClientLogger LOGGER = new ClientLogger(EventProcessorClientBuilderTest.class); private static final String NAMESPACE_NAME = "dummyNamespaceName"; private static final String DEFAULT_DOMAIN_NAME = Configuration.getGlobalConfiguration() @@ -68,13 +71,14 @@ public void testEventProcessorBuilderMissingProperties() { EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder() .checkpointStore(new SampleCheckpointStore()) .processEvent(eventContext -> { - System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId() + " and " - + "sequence number of event = " + eventContext.getEventData().getSequenceNumber()); + LOGGER.log(LogLevel.VERBOSE, () -> "Partition id = " + + eventContext.getPartitionContext().getPartitionId() + " and sequence number of event = " + + eventContext.getEventData().getSequenceNumber()); }) .processError(errorContext -> { - System.out.printf("Error occurred in partition processor for partition %s, %s%n", - errorContext.getPartitionContext().getPartitionId(), - errorContext.getThrowable()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error occurred in partition processor for partition %s, %s%n", + errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable())); }) .buildEventProcessorClient(); }); @@ -86,13 +90,14 @@ public void testEventProcessorBuilderWithProcessEvent() { .connectionString(CORRECT_CONNECTION_STRING) .consumerGroup("consumer-group") .processEvent(eventContext -> { - System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId() + " and " - + "sequence number of event = " + eventContext.getEventData().getSequenceNumber()); + LOGGER.log(LogLevel.VERBOSE, () -> "Partition id = " + + eventContext.getPartitionContext().getPartitionId() + " and sequence number of event = " + + eventContext.getEventData().getSequenceNumber()); }) .processError(errorContext -> { - System.out.printf("Error occurred in partition processor for partition %s, %s%n", - errorContext.getPartitionContext().getPartitionId(), - errorContext.getThrowable()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error occurred in partition processor for partition %s, %s%n", + errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable())); }) .checkpointStore(new SampleCheckpointStore()) .buildEventProcessorClient(); @@ -107,21 +112,21 @@ public void testEventProcessorBuilderWithBothSingleAndBatchConsumers() { .checkpointStore(new SampleCheckpointStore()) .consumerGroup("consumer-group") .processEvent(eventContext -> { - System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId() + " and " - + "sequence number of event = " + eventContext.getEventData().getSequenceNumber()); + LOGGER.log(LogLevel.VERBOSE, () -> ("Partition id = " + + eventContext.getPartitionContext().getPartitionId() + " and sequence number of event = " + + eventContext.getEventData().getSequenceNumber())); }) .processEventBatch(eventBatchContext -> { eventBatchContext.getEvents().forEach(event -> { - System.out - .println( - "Partition id = " + eventBatchContext.getPartitionContext().getPartitionId() + " and " - + "sequence number of event = " + event.getSequenceNumber()); + LOGGER.log(LogLevel.VERBOSE, () -> "Partition id = " + + eventBatchContext.getPartitionContext().getPartitionId() + + " and sequence number of event = " + event.getSequenceNumber()); }); }, 5, Duration.ofSeconds(1)) .processError(errorContext -> { - System.out.printf("Error occurred in partition processor for partition %s, %s%n", - errorContext.getPartitionContext().getPartitionId(), - errorContext.getThrowable()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error occurred in partition processor for partition %s, %s%n", + errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable())); }) .buildEventProcessorClient(); }); @@ -134,9 +139,9 @@ public void testEventProcessorBuilderWithNoProcessEventConsumer() { .checkpointStore(new SampleCheckpointStore()) .consumerGroup("consumer-group") .processError(errorContext -> { - System.out.printf("Error occurred in partition processor for partition %s, %s%n", - errorContext.getPartitionContext().getPartitionId(), - errorContext.getThrowable()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error occurred in partition processor for partition %s, %s%n", + errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable())); }) .buildEventProcessorClient(); }); @@ -149,15 +154,15 @@ public void testEventProcessorBuilderWithProcessEventBatch() { .consumerGroup("consumer-group") .processEventBatch(eventBatchContext -> { eventBatchContext.getEvents().forEach(event -> { - System.out - .println("Partition id = " + eventBatchContext.getPartitionContext().getPartitionId() + " and " - + "sequence number of event = " + event.getSequenceNumber()); + LOGGER.log(LogLevel.VERBOSE, () -> ("Partition id = " + + eventBatchContext.getPartitionContext().getPartitionId() + " and sequence number of event = " + + event.getSequenceNumber())); }); }, 5, Duration.ofSeconds(1)) .processError(errorContext -> { - System.out.printf("Error occurred in partition processor for partition %s, %s%n", - errorContext.getPartitionContext().getPartitionId(), - errorContext.getThrowable()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error occurred in partition processor for partition %s, %s%n", + errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable())); }) .checkpointStore(new SampleCheckpointStore()) .buildEventProcessorClient(); @@ -174,15 +179,15 @@ public void initialOffsetProviderSetMoreThanOne() { .consumerGroup("consumer-group") .processEventBatch(eventBatchContext -> { eventBatchContext.getEvents().forEach(event -> { - System.out - .println("Partition id = " + eventBatchContext.getPartitionContext().getPartitionId() + " and " - + "sequence number of event = " + event.getSequenceNumber()); + LOGGER.log(LogLevel.VERBOSE, () -> "Partition id = " + + eventBatchContext.getPartitionContext().getPartitionId() + " and sequence number of event = " + + event.getSequenceNumber()); }); }, 5, Duration.ofSeconds(1)) .processError(errorContext -> { - System.out.printf("Error occurred in partition processor for partition %s, %s%n", - errorContext.getPartitionContext().getPartitionId(), - errorContext.getThrowable()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error occurred in partition processor for partition %s, %s%n", + errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable())); }) .checkpointStore(new SampleCheckpointStore()); @@ -215,15 +220,15 @@ public void initialEventPositionProvider() { .consumerGroup("consumer-group") .processEventBatch(eventBatchContext -> { eventBatchContext.getEvents().forEach(event -> { - System.out - .println("Partition id = " + eventBatchContext.getPartitionContext().getPartitionId() + " and " - + "sequence number of event = " + event.getSequenceNumber()); + LOGGER.log(LogLevel.VERBOSE, () -> "Partition id = " + + eventBatchContext.getPartitionContext().getPartitionId() + " and sequence number of event = " + + event.getSequenceNumber()); }); }, 5, Duration.ofSeconds(1)) .processError(errorContext -> { - System.out.printf("Error occurred in partition processor for partition %s, %s%n", - errorContext.getPartitionContext().getPartitionId(), - errorContext.getThrowable()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error occurred in partition processor for partition %s, %s%n", + errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable())); }) .checkpointStore(new SampleCheckpointStore()) .initialPartitionEventPosition(eventPositionFunction) @@ -257,15 +262,15 @@ public void initialEventPositionMap() { .consumerGroup("consumer-group") .processEventBatch(eventBatchContext -> { eventBatchContext.getEvents().forEach(event -> { - System.out - .println("Partition id = " + eventBatchContext.getPartitionContext().getPartitionId() + " and " - + "sequence number of event = " + event.getSequenceNumber()); + LOGGER.log(LogLevel.VERBOSE, () -> "Partition id = " + + eventBatchContext.getPartitionContext().getPartitionId() + " and sequence number of event = " + + event.getSequenceNumber()); }); }, 5, Duration.ofSeconds(1)) .processError(errorContext -> { - System.out.printf("Error occurred in partition processor for partition %s, %s%n", - errorContext.getPartitionContext().getPartitionId(), - errorContext.getThrowable()); + LOGGER.log(LogLevel.VERBOSE, () -> String.format( + "Error occurred in partition processor for partition %s, %s%n", + errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable())); }) .checkpointStore(new SampleCheckpointStore()) .initialPartitionEventPosition(eventPositionMap) diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/IntegrationTestBase.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/IntegrationTestBase.java index ed526061a5a0..40acadca38c1 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/IntegrationTestBase.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/IntegrationTestBase.java @@ -16,6 +16,7 @@ import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.identity.ClientSecretCredential; import com.azure.identity.ClientSecretCredentialBuilder; import com.azure.messaging.eventhubs.models.SendOptions; @@ -59,6 +60,8 @@ * Test base for running integration tests. */ public abstract class IntegrationTestBase extends TestBase { + private static final ClientLogger LOGGER = new ClientLogger(IntegrationTestBase.class); + // The number of partitions we create in test-resources.json. // Partitions 0 and 1 are used for consume-only operations. 2, 3, and 4 are used to publish or consume events. protected static final int NUMBER_OF_PARTITIONS = 5; @@ -193,7 +196,7 @@ static String getConnectionString(boolean withSas) { } return String.format(connectionStringWithSasAndEntityFormat, endpoint, signatureValue, entityPath); } catch (Exception e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Error while getting connection string", e); } } return connectionString; diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/LongRunningTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/LongRunningTest.java index 79e8dc03672c..d1b6c899d297 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/LongRunningTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/LongRunningTest.java @@ -4,6 +4,7 @@ package com.azure.messaging.eventhubs; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.models.CreateBatchOptions; import com.azure.messaging.eventhubs.models.EventPosition; import org.junit.jupiter.api.Disabled; @@ -70,17 +71,12 @@ void twoConsumersAndSender() throws InterruptedException { return producer.send(batch).thenReturn(Instant.now()); })) - .subscribe(instant -> { - System.out.println("Sent batch at: " + instant); - }, error -> { - logger.error("Error sending batch: ", error); - }, () -> { - logger.info("Complete."); - })); + .subscribe(instant -> logger.log(LogLevel.VERBOSE, () -> "Sent batch at: " + instant), + error -> logger.error("Error sending batch: ", error), () -> logger.info("Complete."))); - System.out.println("Sleeping while performing work."); + logger.log(LogLevel.VERBOSE, () -> "Sleeping while performing work."); TimeUnit.MINUTES.sleep(duration.toMinutes()); - System.out.println("Complete."); + logger.log(LogLevel.VERBOSE, () -> "Complete."); } @Disabled("Testing idle clients. Connections are timed out at 30 mins.") @@ -90,7 +86,7 @@ void idleConnection() throws InterruptedException { .connectionString(getConnectionString()) .buildAsyncProducerClient()) { for (int i = 0; i < 4; i++) { - System.out.println("Iteration: " + i); + logger.verbose("Iteration: " + i); toClose(idleProducer.createBatch().flatMap(batch -> { IntStream.range(0, 3).mapToObj(number -> new EventData("Number : " + number)) @@ -102,17 +98,12 @@ void idleConnection() throws InterruptedException { }); return idleProducer.send(batch).thenReturn(Instant.now()); - }).subscribe(instant -> { - System.out.println("Sent batch at: " + instant); - }, error -> { - logger.error("Error sending batch: ", error); - }, () -> { - logger.info("Complete."); - })); - - System.out.println("Sleeping 40 mins."); + }).subscribe(instant -> logger.log(LogLevel.VERBOSE, () -> "Sent batch at: " + instant), + error -> logger.error("Error sending batch: ", error), () -> logger.info("Complete."))); + + logger.log(LogLevel.VERBOSE, () -> "Sleeping 40 mins."); TimeUnit.MINUTES.sleep(40); - System.out.println("Complete."); + logger.log(LogLevel.VERBOSE, () -> "Complete."); } } } @@ -125,14 +116,14 @@ void idleSendLinks() throws InterruptedException { .buildAsyncProducerClient()) { for (int i = 0; i < 4; i++) { - System.out.println("Iteration: " + i); + logger.verbose("Iteration: " + i); toClose(idleProducer.getEventHubProperties().subscribe(properties -> { - System.out.printf("[%s]: ids[%s]. Received: %s%n", + logger.log(LogLevel.VERBOSE, () -> String.format("[%s]: ids[%s]. Received: %s%n", properties.getName(), String.join(",", properties.getPartitionIds()), - Instant.now()); - }, error -> System.err.println("Error receiving ids: " + error))); + Instant.now())); + }, error -> logger.log(LogLevel.VERBOSE, () -> "Error receiving ids", error))); toClose(idleProducer.createBatch().flatMap(batch -> { IntStream.range(0, 3).mapToObj(number -> new EventData("Number : " + number)) @@ -144,13 +135,12 @@ void idleSendLinks() throws InterruptedException { }); return idleProducer.send(batch).thenReturn(Instant.now()); - }).subscribe(instant -> { - System.out.println("Sent batch at: " + instant); - }, error -> System.err.println("Error sending batch: " + error))); + }).subscribe(instant -> logger.log(LogLevel.VERBOSE, () -> "Sent batch at: " + instant), + error -> logger.log(LogLevel.VERBOSE, () -> "Error sending batch", error))); - System.out.println("Sleeping 15 mins."); + logger.log(LogLevel.VERBOSE, () -> "Sleeping 15 mins."); TimeUnit.MINUTES.sleep(15); - System.out.println("Completed sleep."); + logger.log(LogLevel.VERBOSE, () -> "Completed sleep."); } } } @@ -173,12 +163,9 @@ void worksAfterReconnection() throws InterruptedException { toClose(Flux.interval(Duration.ofSeconds(1)) .flatMap(position -> client.getPartitionIds().collectList()) .subscribe(partitionIds -> { - System.out.printf("Ids %s: {%s}%n", Instant.now(), String.join(",", partitionIds)); - }, error -> { - logger.error("Error fetching info.", error); - }, () -> { - logger.info("Complete."); - })); + logger.log(LogLevel.VERBOSE, + () -> String.format("Ids %s: {%s}%n", Instant.now(), String.join(",", partitionIds))); + }, error -> logger.error("Error fetching info.", error), () -> logger.info("Complete."))); toClose(Flux.interval(Duration.ofSeconds(5)) .flatMap(position -> producer.createBatch(options).flatMap(batch -> { IntStream.range(0, 3).mapToObj(number -> new EventData("Position" + position + ": " + number)) @@ -191,16 +178,11 @@ void worksAfterReconnection() throws InterruptedException { return producer.send(batch).thenReturn(Instant.now()); })) - .subscribe(instant -> { - System.out.println("---- Sent batch at: " + instant); - }, error -> { - logger.error("---- Error sending batch: ", error); - }, () -> { - logger.info("---- Complete."); - })); + .subscribe(instant -> logger.log(LogLevel.VERBOSE, () -> "---- Sent batch at: " + instant), + error -> logger.error("---- Error sending batch: ", error), () -> logger.info("---- Complete."))); - System.out.println("Sleeping while performing work."); + logger.log(LogLevel.VERBOSE, () -> "Sleeping while performing work."); TimeUnit.MINUTES.sleep(30); - System.out.println("Complete."); + logger.log(LogLevel.VERBOSE, () -> "Complete."); } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancerTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancerTest.java index 1fa96bf7fdc9..5d277e366132 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancerTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancerTest.java @@ -4,6 +4,7 @@ package com.azure.messaging.eventhubs; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.implementation.PartitionProcessor; import com.azure.messaging.eventhubs.implementation.instrumentation.EventHubsTracer; import com.azure.messaging.eventhubs.models.ErrorContext; @@ -17,7 +18,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInfo; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -109,8 +109,7 @@ public class PartitionBasedLoadBalancerTest { private final EventProcessorClientOptions processorOptions = new EventProcessorClientOptions(); @BeforeEach - public void setup(TestInfo testInfo) { - System.out.println("Running " + testInfo.getDisplayName()); + public void setup() { toClose = new ArrayList<>(); mockCloseable = MockitoAnnotations.openMocks(this); @@ -142,7 +141,7 @@ public void teardown() throws Exception { try { closeable.close(); } catch (IOException error) { - error.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Error closing resource.", error); } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxySelectorTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxySelectorTest.java index 9562eac39f4e..c43bebc11c50 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxySelectorTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxySelectorTest.java @@ -6,6 +6,7 @@ import com.azure.core.amqp.AmqpRetryOptions; import com.azure.core.amqp.AmqpTransportType; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.models.EventPosition; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; @@ -27,6 +28,8 @@ @Tag(TestUtils.INTEGRATION) class ProxySelectorTest extends IntegrationTestBase { + private static final ClientLogger LOGGER = new ClientLogger(ProxySelectorTest.class); + private static final int PROXY_PORT = 8899; private static final InetSocketAddress SIMPLE_PROXY_ADDRESS = new InetSocketAddress("localhost", PROXY_PORT); private ProxySelector defaultProxySelector; @@ -73,7 +76,7 @@ public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { .expectErrorSatisfies(error -> { // The message can vary because it is returned from proton-j, so we don't want to compare against that. // This is a transient error from ExceptionUtil.java: line 67. - System.out.println("Error: " + error); + LOGGER.log(LogLevel.VERBOSE, () -> "Error", error); }) .verify(TIMEOUT); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLinkProcessorTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLinkProcessorTest.java index c731b8bea014..b7acff2826e5 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLinkProcessorTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLinkProcessorTest.java @@ -10,6 +10,8 @@ import com.azure.core.amqp.exception.AmqpErrorContext; import com.azure.core.amqp.exception.AmqpException; import com.azure.core.amqp.implementation.AmqpReceiveLink; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.implementation.instrumentation.EventHubsConsumerInstrumentation; import org.apache.qpid.proton.message.Message; import org.junit.jupiter.api.AfterEach; @@ -49,6 +51,8 @@ import static org.mockito.Mockito.when; class AmqpReceiveLinkProcessorTest { + private static final ClientLogger LOGGER = new ClientLogger(AmqpReceiveLinkProcessorTest.class); + private static final int PREFETCH = 5; private static final EventHubsConsumerInstrumentation DEFAULT_INSTRUMENTATION = new EventHubsConsumerInstrumentation(null, null, "hostname", "hubname", "$Default", false); @@ -190,9 +194,9 @@ void respectsBackpressureLessThanMinimum() { // Act processor.subscribe( - e -> System.out.println("message: " + e), + e -> LOGGER.log(LogLevel.VERBOSE, () -> "message: " + e), Assertions::fail, - () -> System.out.println("Complete."), + () -> LOGGER.log(LogLevel.VERBOSE, () -> "Complete."), s -> s.request(backpressure)); // Assert @@ -554,7 +558,7 @@ void onlyRequestsWhenCreditsLessThanPrefetch() { assertNotNull(integerSupplier); // Invoking this once. Should return a value and notify that there are no credits left on the link. final int messages = integerSupplier.get(); - System.out.println("Messages: " + messages); + LOGGER.log(LogLevel.VERBOSE, () -> "Messages: " + messages); }) .expectNoEvent(Duration.ofSeconds(1)) .thenRequest(nextRequest) diff --git a/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md b/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md index 13782c80c116..bb5249bfbb72 100644 --- a/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md +++ b/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md @@ -121,7 +121,7 @@ private static List createPatientRecords() { // Use LocalDate to set Date patientDetails.setBirthDate(LocalDate.of(1959, 11, 11)); - + patientRecord.setInfo(patientDetails); Encounter encounter = new Encounter("encounterid1"); @@ -151,7 +151,7 @@ private static List createPatientRecords() { patientDocument.setSpecialtyType(SpecialtyType.RADIOLOGY); DocumentAdministrativeMetadata adminMetadata = new DocumentAdministrativeMetadata(); - FhirR4Extendible orderedProcedure = new FhirR4Extendible(); + OrderedProcedure orderedProcedure = new OrderedProcedure(); FhirR4CodeableConcept procedureCode = new FhirR4CodeableConcept(); FhirR4Coding procedureCoding = new FhirR4Coding(); @@ -240,8 +240,8 @@ Display critical result inferences from the example request results. ```java com.azure.health.insights.radiologyinsights.displayresults List patientResults = radiologyInsightsResult.getPatientResults(); for (RadiologyInsightsPatientResult patientResult : patientResults) { - List inferences = patientResult.getInferences(); - for (FhirR4Extendible1 inference : inferences) { + List inferences = patientResult.getInferences(); + for (RadiologyInsightsInference inference : inferences) { if (inference instanceof CriticalResultInference) { CriticalResultInference criticalResultInference = (CriticalResultInference) inference; String description = criticalResultInference.getResult().getDescription(); diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTest.java b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTest.java index 176841ed1efa..393a22f5e03f 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTest.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTest.java @@ -9,6 +9,8 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.test.http.AssertingHttpClientBuilder; import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.polling.LongRunningOperationStatus; import com.azure.core.util.polling.PollResponse; import com.azure.core.util.polling.SyncPoller; @@ -68,6 +70,8 @@ import static org.junit.jupiter.api.Assertions.fail; public class CertificateClientTest extends CertificateClientTestBase { + private static final ClientLogger LOGGER = new ClientLogger(CertificateClientTest.class); + private CertificateClient certificateClient; @Override @@ -975,7 +979,7 @@ private void pollOnCertificatePurge(String certificateName) { } } - System.err.printf("Deleted Key %s was not purged \n", certificateName); + LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Certificate " + certificateName + " was not purged"); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java index 3012b65ad5d2..3cb7feb45efa 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java @@ -7,6 +7,8 @@ import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpClient; import com.azure.core.test.TestMode; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.polling.AsyncPollResponse; import com.azure.core.util.polling.PollerFlux; import com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient; @@ -41,6 +43,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class KeyAsyncClientTest extends KeyClientTestBase { + private static final ClientLogger LOGGER = new ClientLogger(KeyAsyncClientTest.class); protected KeyAsyncClient keyAsyncClient; @Override @@ -838,7 +841,7 @@ private void pollOnKeyPurge(String keyName) { } } - System.err.printf("Deleted Key %s was not purged \n", keyName); + LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Key " + keyName + " was not purged"); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java index 10ace970322b..ae77209705b3 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java @@ -7,6 +7,8 @@ import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpClient; import com.azure.core.test.TestMode; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.polling.SyncPoller; import com.azure.security.keyvault.keys.cryptography.CryptographyClient; import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; @@ -40,6 +42,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class KeyClientTest extends KeyClientTestBase { + private static final ClientLogger LOGGER = new ClientLogger(KeyClientTest.class); + protected KeyClient keyClient; @Override @@ -751,6 +755,6 @@ private void pollOnKeyPurge(String keyName) { } } - System.err.printf("Deleted Key %s was not purged \n", keyName); + LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Key " + keyName + " was not purged"); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTest.java index 419c079e7854..01e37bb6cdac 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTest.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTest.java @@ -4,6 +4,8 @@ package com.azure.security.keyvault.keys.cryptography; import com.azure.core.http.HttpClient; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.security.keyvault.keys.KeyClient; import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; @@ -40,6 +42,8 @@ import static org.junit.jupiter.api.Assertions.fail; public class CryptographyClientTest extends CryptographyClientTestBase { + private static final ClientLogger LOGGER = new ClientLogger(CryptographyClientTest.class); + private KeyClient client; @Override @@ -349,7 +353,7 @@ public void signDataVerifyEcLocal() { } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException e) { // Could not generate a KeyPair from the given JsonWebKey. // It's likely this happened for key curve secp256k1, which is not supported on Java 16+. - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Failed to generate key pair from JsonWebKey.", e); return; } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java index 91e7ed3f2276..3aecf85da493 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java @@ -15,6 +15,7 @@ import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; import com.azure.identity.ClientSecretCredentialBuilder; import com.azure.security.keyvault.keys.KeyClientBuilder; import com.azure.security.keyvault.keys.KeyServiceVersion; @@ -52,6 +53,8 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; public abstract class CryptographyClientTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(CryptographyClientTestBase.class); + protected boolean isHsmEnabled = false; protected boolean runManagedHsmTest = false; @@ -338,10 +341,6 @@ public String getEndpoint() { } public void sleep(long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - e.printStackTrace(); - } + sleepIfRunningAgainstService(millis); } } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java index 155f022e979a..63fffc5dffbe 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java @@ -7,6 +7,8 @@ import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpClient; import com.azure.core.test.http.AssertingHttpClientBuilder; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.polling.AsyncPollResponse; import com.azure.core.util.polling.PollerFlux; import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; @@ -29,6 +31,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class SecretAsyncClientTest extends SecretClientTestBase { + private static final ClientLogger LOGGER = new ClientLogger(SecretAsyncClientTest.class); + private SecretAsyncClient secretAsyncClient; @Override @@ -574,6 +578,6 @@ private void pollOnSecretPurge(String secretName) { } } - System.err.printf("Deleted Secret %s was not purged \n", secretName); + LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Secret " + secretName + " was not purged"); } } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTest.java index 0e8309f0b9ce..4e43e1a38cb8 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTest.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTest.java @@ -7,6 +7,8 @@ import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpClient; import com.azure.core.test.http.AssertingHttpClientBuilder; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.polling.SyncPoller; import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; @@ -27,6 +29,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class SecretClientTest extends SecretClientTestBase { + private static final ClientLogger LOGGER = new ClientLogger(SecretClientTest.class); + private SecretClient secretClient; @Override @@ -494,6 +498,6 @@ private void pollOnSecretPurge(String secretName) { } } - System.err.printf("Deleted Secret %s was not purged \n", secretName); + LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Secret " + secretName + " was not purged"); } } diff --git a/sdk/keyvault/test-resources.json b/sdk/keyvault/test-resources.json index dff6a0b2c37d..3b0edf0a9a2b 100644 --- a/sdk/keyvault/test-resources.json +++ b/sdk/keyvault/test-resources.json @@ -171,7 +171,7 @@ "type": "string", "defaultValue": "core.windows.net", "metadata": { - "description": "The url suffix to use when accessing the storage data plane." + "description": "The url suffix to use when accessing the storage data plane." } } }, @@ -486,45 +486,11 @@ "azPowerShellVersion": "5.0", "timeout": "PT30M", "arguments": "[format(' -vaultName {0} -certificateName {1} -subjectName {2}', variables('kvName'), parameters('certificateName'), parameters('subjectName'))]", - "scriptContent": " - param( - [string] [Parameter(Mandatory=$true)] $vaultName, - [string] [Parameter(Mandatory=$true)] $certificateName, - [string] [Parameter(Mandatory=$true)] $subjectName - ) - - $ErrorActionPreference = 'Stop' - $DeploymentScriptOutputs = @{} - - $policy = New-AzKeyVaultCertificatePolicy -SubjectName $subjectName -IssuerName Self -ValidityInMonths 12 -Verbose - - Add-AzKeyVaultCertificate -VaultName $vaultName -Name $certificateName -CertificatePolicy $policy -Verbose - - $newCert = Get-AzKeyVaultCertificate -VaultName $vaultName -Name $certificateName - - $tries = 0 - do { - Write-Host 'Waiting for certificate creation completion...' - Start-Sleep -Seconds 10 - $operation = Get-AzKeyVaultCertificateOperation -VaultName $vaultName -Name $certificateName - $tries++ - - if ($operation.Status -eq 'failed') { - throw 'Creating certificate $certificateName in vault $vaultName failed with error $($operation.ErrorMessage)' + "scriptContent": "param([string] [Parameter(Mandatory=$true)] $vaultName, [string] [Parameter(Mandatory=$true)] $certificateName, [string] [Parameter(Mandatory=$true)] $subjectName)\n\n$ErrorActionPreference = 'Stop'\n$DeploymentScriptOutputs = @{}\n$policy = New-AzKeyVaultCertificatePolicy -SubjectName $subjectName -IssuerName Self -ValidityInMonths 12 -Verbose\n\nAdd-AzKeyVaultCertificate -VaultName $vaultName -Name $certificateName -CertificatePolicy $policy -Verbose\n\n$newCert = Get-AzKeyVaultCertificate -VaultName $vaultName -Name $certificateName\n$tries = 0\n\ndo {\n Write-Host 'Waiting for certificate creation completion...'\n Start-Sleep -Seconds 10\n $operation = Get-AzKeyVaultCertificateOperation -VaultName $vaultName -Name $certificateName\n $tries++\n\n if ($operation.Status -eq 'failed') {\n throw 'Creating certificate $certificateName in vault $vaultName failed with error $($operation.ErrorMessage)'\n }\n\n if ($tries -gt 120) {\n throw 'Timed out waiting for creation of certificate $certificateName in vault $vaultName'\n }\n} while ($operation.Status -ne 'completed')\n\n$DeploymentScriptOutputs['certThumbprint'] = $newCert.Thumbprint\n$newCert | Out-String\n", + "cleanupPreference": "OnSuccess", + "retentionInterval": "P1D" } - - if ($tries -gt 120) { - throw 'Timed out waiting for creation of certificate $certificateName in vault $vaultName' - } - } while ($operation.Status -ne 'completed') - - $DeploymentScriptOutputs['certThumbprint'] = $newCert.Thumbprint - $newCert | Out-String - ", - "cleanupPreference": "OnSuccess", - "retentionInterval": "P1D" } - } ], "outputs": { "AZURE_KEYVAULT_ENDPOINT": { @@ -565,8 +531,8 @@ "value": "[parameters('testApplicationOid')]" }, "KEYVAULT_STORAGE_ENDPOINT_SUFFIX": { - "type": "string", - "value": "[parameters('storageEndpointSuffix')]" + "type": "string", + "value": "[parameters('storageEndpointSuffix')]" }, "BLOB_STORAGE_ACCOUNT_NAME": { "type": "string", diff --git a/sdk/monitor/azure-monitor-ingestion/src/test/java/com/azure/monitor/ingestion/LogsIngestionTestBase.java b/sdk/monitor/azure-monitor-ingestion/src/test/java/com/azure/monitor/ingestion/LogsIngestionTestBase.java index eda79ce1ec45..fca9777060ae 100644 --- a/sdk/monitor/azure-monitor-ingestion/src/test/java/com/azure/monitor/ingestion/LogsIngestionTestBase.java +++ b/sdk/monitor/azure-monitor-ingestion/src/test/java/com/azure/monitor/ingestion/LogsIngestionTestBase.java @@ -19,6 +19,8 @@ import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.serializer.JsonSerializerProviders; import com.azure.core.util.serializer.TypeReference; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -43,6 +45,8 @@ * Base test class for logs ingestion client tests. */ public abstract class LogsIngestionTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionTestBase.class); + protected LogsIngestionClientBuilder clientBuilder; protected String dataCollectionEndpoint; protected String dataCollectionRuleId; @@ -210,7 +214,7 @@ private static byte[] unzipRequestBody(BinaryData bodyAsBinaryData) { outputStream.close(); return outputStream.toByteArray(); } catch (IOException exception) { - System.out.println("Failed to unzip data"); + LOGGER.log(LogLevel.VERBOSE, () -> "Failed to unzip data"); } return null; } diff --git a/sdk/monitor/azure-monitor-ingestion/src/test/java/com/azure/monitor/ingestion/implementation/UtilsTest.java b/sdk/monitor/azure-monitor-ingestion/src/test/java/com/azure/monitor/ingestion/implementation/UtilsTest.java index db75340d1d7a..afc99a8bb5ab 100644 --- a/sdk/monitor/azure-monitor-ingestion/src/test/java/com/azure/monitor/ingestion/implementation/UtilsTest.java +++ b/sdk/monitor/azure-monitor-ingestion/src/test/java/com/azure/monitor/ingestion/implementation/UtilsTest.java @@ -5,7 +5,6 @@ import org.junit.jupiter.api.Test; -import java.time.Instant; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -17,7 +16,6 @@ import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -31,13 +29,11 @@ public void shutdownHookTerminatesPool() throws InterruptedException, ExecutionE Stream stream = IntStream.of(100, 4000) .boxed() .parallel() - .map(i -> task(i)); + .map(this::task); Future> tasks = threadPool.submit(() -> stream.collect(Collectors.toList())); - long start = Instant.now().toEpochMilli(); hook.run(); - assertEquals(timeoutSec * 1000, Instant.now().toEpochMilli() - start, 1000); assertTrue(threadPool.isShutdown()); assertTrue(threadPool.isTerminated()); diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/main/java/com/azure/monitor/opentelemetry/exporter/implementation/MetricDataMapper.java b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/main/java/com/azure/monitor/opentelemetry/exporter/implementation/MetricDataMapper.java index 42bcfafe9f1a..b69e5f9dd886 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/main/java/com/azure/monitor/opentelemetry/exporter/implementation/MetricDataMapper.java +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/main/java/com/azure/monitor/opentelemetry/exporter/implementation/MetricDataMapper.java @@ -45,22 +45,22 @@ public class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); + private static final Set OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); + private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); - private static final List EXCLUDED_METRIC_NAMES = new ArrayList<>(); public static final AttributeKey APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { - EXCLUDED_METRIC_NAMES.add("http.server.active_requests"); // Servlet - EXCLUDED_METRIC_NAMES.add("http.server.response.size"); - EXCLUDED_METRIC_NAMES.add("http.client.response.size"); + // HTTP unstable metrics to be excluded via Otel auto instrumentation + OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); + OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); + // Application Insights pre-aggregated standard metrics OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); - OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.duration"); // pre-stable HTTP semconv - OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.duration"); // pre-stable HTTP semconv OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } @@ -73,10 +73,6 @@ public MetricDataMapper( } public void map(MetricData metricData, Consumer consumer) { - if (EXCLUDED_METRIC_NAMES.contains(metricData.getName())) { - return; - } - MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE @@ -85,11 +81,20 @@ public void map(MetricData metricData, Consumer consumer) { || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); - List telemetryItemList = - convertOtelMetricToAzureMonitorMetric(metricData, isPreAggregatedStandardMetric); - for (TelemetryItem telemetryItem : telemetryItemList) { - consumer.accept(telemetryItem); + if (isPreAggregatedStandardMetric) { + List preAggregatedStandardMetrics = + convertOtelMetricToAzureMonitorMetric(metricData, true); + preAggregatedStandardMetrics.forEach(consumer::accept); + } + + // DO NOT emit unstable metrics from the OpenTelemetry auto instrumentation libraries + // custom metrics are always emitted + if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) + && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { + return; } + List stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); + stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/main/java/com/azure/monitor/opentelemetry/exporter/implementation/heartbeat/DefaultHeartBeatPropertyProvider.java b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/main/java/com/azure/monitor/opentelemetry/exporter/implementation/heartbeat/DefaultHeartBeatPropertyProvider.java index 2a0c259da7fc..8d3c424251c7 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/main/java/com/azure/monitor/opentelemetry/exporter/implementation/heartbeat/DefaultHeartBeatPropertyProvider.java +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/main/java/com/azure/monitor/opentelemetry/exporter/implementation/heartbeat/DefaultHeartBeatPropertyProvider.java @@ -23,7 +23,7 @@ public class DefaultHeartBeatPropertyProvider implements HeartBeatPayloadProvide /** * Collection holding default properties for this default provider. */ - private final Set defaultFields; + final Set defaultFields; /** * Random GUID that would help in analysis when app has stopped and restarted. Each restart will diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/implementation/heartbeat/HeartbeatTests.java b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/implementation/heartbeat/HeartbeatTests.java index a08c30811c66..45d3676a11fd 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/implementation/heartbeat/HeartbeatTests.java +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/implementation/heartbeat/HeartbeatTests.java @@ -6,13 +6,8 @@ import com.azure.monitor.opentelemetry.exporter.implementation.models.MetricsData; import com.azure.monitor.opentelemetry.exporter.implementation.models.TelemetryItem; import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; -import java.lang.reflect.Field; import java.util.List; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Consumer; @@ -20,9 +15,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HeartbeatTests { - - @Mock - private Consumer> telemetryItemsConsumer; + // Dummy consumer that does nothing. + private final Consumer> telemetryItemsConsumer = ignored -> {}; @Test void heartBeatPayloadContainsDataByDefault() throws InterruptedException { @@ -80,30 +74,24 @@ void heartbeatMetricCountsForAllFailures() { } @Test - void sentHeartbeatContainsExpectedDefaultFields() throws Exception { - HeartbeatExporter mockProvider = Mockito.mock(HeartbeatExporter.class); + void sentHeartbeatContainsExpectedDefaultFields() { ConcurrentMap props = new ConcurrentHashMap<>(); - Mockito.when( - mockProvider.addHeartBeatProperty( - Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean())) - .then( - (Answer) - invocation -> { - props.put( - invocation.getArgument(0, String.class), - invocation.getArgument(1, String.class)); - return true; - }); + + HeartbeatExporter mockProvider = new HeartbeatExporter(60, (b, r) -> { + }, telemetryItemsConsumer) { + @Override + public boolean addHeartBeatProperty(String propertyName, String propertyValue, boolean isHealthy) { + props.put(propertyName, propertyValue); + return true; + } + }; + DefaultHeartBeatPropertyProvider defaultProvider = new DefaultHeartBeatPropertyProvider(); HeartbeatDefaultPayload.populateDefaultPayload(mockProvider).run(); - Field field = defaultProvider.getClass().getDeclaredField("defaultFields"); - field.setAccessible(true); - @SuppressWarnings("unchecked") - Set defaultFields = (Set) field.get(defaultProvider); - for (String fieldName : defaultFields) { + for (String fieldName : defaultProvider.defaultFields) { assertThat(props.containsKey(fieldName)).isTrue(); - assertThat(props.get(fieldName).length() > 0).isTrue(); + assertThat(!props.get(fieldName).isEmpty()).isTrue(); } } @@ -119,15 +107,11 @@ void heartBeatProviderDoesNotAllowDuplicateProperties() { } @Test - void cannotAddUnknownDefaultProperty() throws Exception { + void cannotAddUnknownDefaultProperty() { DefaultHeartBeatPropertyProvider base = new DefaultHeartBeatPropertyProvider(); String testKey = "testKey"; - Field field = base.getClass().getDeclaredField("defaultFields"); - field.setAccessible(true); - @SuppressWarnings("unchecked") - Set defaultFields = (Set) field.get(base); - defaultFields.add(testKey); + base.defaultFields.add(testKey); HeartbeatExporter provider = new HeartbeatExporter(60, (b, r) -> { }, telemetryItemsConsumer); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureFunctionsSyncTests.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureFunctionsSyncTests.java index 993a2317dab3..d13c415ca607 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureFunctionsSyncTests.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureFunctionsSyncTests.java @@ -52,11 +52,7 @@ public void parallelFunctionCallTest(HttpClient httpClient, AssistantsServiceVer // Poll the run do { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); run = client.getRun(assistantThread.getId(), run.getId()); } while (run.getStatus() == RunStatus.QUEUED || run.getStatus() == RunStatus.IN_PROGRESS); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRetrievalSyncTest.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRetrievalSyncTest.java index 372aef1d8711..e0b8132b6ee1 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRetrievalSyncTest.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRetrievalSyncTest.java @@ -58,11 +58,7 @@ public void basicRetrieval(HttpClient httpClient, AssistantsServiceVersion servi ThreadRun run = client.createRun(thread, assistant); do { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); run = client.getRun(thread.getId(), run.getId()); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRunThreadAsyncTest.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRunThreadAsyncTest.java index c303e758c988..0c41110a5607 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRunThreadAsyncTest.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRunThreadAsyncTest.java @@ -69,11 +69,7 @@ public void submitMessageAndRun(HttpClient httpClient, AssistantsServiceVersion .verifyComplete(); run = runReference.get(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -136,11 +132,7 @@ public void submitMessageAndRunWithResponse(HttpClient httpClient, AssistantsSer .verifyComplete(); run = runReference.get(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -196,11 +188,7 @@ public void createThreadAndRun(HttpClient httpClient, AssistantsServiceVersion s .verifyComplete(); run = runReference.get(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -261,11 +249,7 @@ public void createThreadAndRunWithResponse(HttpClient httpClient, AssistantsServ .verifyComplete(); run = runReference.get(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -394,11 +378,7 @@ public void listAndGetRunSteps(HttpClient httpClient, AssistantsServiceVersion s runReference.set(threadRun); }) .verifyComplete(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); run = runReference.get(); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRunThreadSyncTest.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRunThreadSyncTest.java index ce08fa777d93..5ea7a4570741 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRunThreadSyncTest.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/AzureRunThreadSyncTest.java @@ -50,11 +50,7 @@ public void submitMessageAndRun(HttpClient httpClient, AssistantsServiceVersion // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -94,11 +90,7 @@ public void submitMessageAndRunWithResponse(HttpClient httpClient, AssistantsSer // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -134,11 +126,7 @@ public void createThreadAndRun(HttpClient httpClient, AssistantsServiceVersion s // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -176,11 +164,7 @@ public void createThreadAndRunWithResponse(HttpClient httpClient, AssistantsServ // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -283,11 +267,7 @@ public void listAndGetRunSteps(HttpClient httpClient, AssistantsServiceVersion s // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/FunctionsSyncTests.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/FunctionsSyncTests.java index 50182c461a08..231da68f7344 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/FunctionsSyncTests.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/FunctionsSyncTests.java @@ -52,11 +52,7 @@ public void parallelFunctionCallTest(HttpClient httpClient, AssistantsServiceVer // Poll the run do { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); run = client.getRun(assistantThread.getId(), run.getId()); } while (run.getStatus() == RunStatus.QUEUED || run.getStatus() == RunStatus.IN_PROGRESS); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RetrievalSyncTest.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RetrievalSyncTest.java index e9ad5a5fd64f..3ab9b625ba3e 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RetrievalSyncTest.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RetrievalSyncTest.java @@ -56,11 +56,7 @@ public void basicRetrieval(HttpClient httpClient, AssistantsServiceVersion servi ThreadRun run = client.createRun(thread, assistant); do { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); run = client.getRun(thread.getId(), run.getId()); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RunThreadAsyncTest.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RunThreadAsyncTest.java index 035e80e9a8ff..fc56f839db04 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RunThreadAsyncTest.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RunThreadAsyncTest.java @@ -69,11 +69,7 @@ public void submitMessageAndRun(HttpClient httpClient, AssistantsServiceVersion .verifyComplete(); run = runReference.get(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -138,11 +134,7 @@ public void submitMessageAndRunWithResponse(HttpClient httpClient, AssistantsSer .verifyComplete(); run = runReference.get(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -198,11 +190,7 @@ public void createThreadAndRun(HttpClient httpClient, AssistantsServiceVersion s .verifyComplete(); run = runReference.get(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -263,11 +251,7 @@ public void createThreadAndRunWithResponse(HttpClient httpClient, AssistantsServ .verifyComplete(); run = runReference.get(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -396,11 +380,7 @@ public void listAndGetRunSteps(HttpClient httpClient, AssistantsServiceVersion s runReference.set(threadRun); }) .verifyComplete(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); run = runReference.get(); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RunThreadSyncTest.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RunThreadSyncTest.java index 294165e1d156..1cf4ddf547b3 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RunThreadSyncTest.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/RunThreadSyncTest.java @@ -50,11 +50,7 @@ public void submitMessageAndRun(HttpClient httpClient, AssistantsServiceVersion // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -94,11 +90,7 @@ public void submitMessageAndRunWithResponse(HttpClient httpClient, AssistantsSer // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -133,11 +125,7 @@ public void createThreadAndRun(HttpClient httpClient, AssistantsServiceVersion s // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -175,11 +163,7 @@ public void createThreadAndRunWithResponse(HttpClient httpClient, AssistantsServ // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); @@ -281,11 +265,7 @@ public void listAndGetRunSteps(HttpClient httpClient, AssistantsServiceVersion s // Wait on Run and poll the Run in a loop do { run = client.getRun(run.getThreadId(), run.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + sleepIfRunningAgainstService(500); } while (run.getStatus() == RunStatus.IN_PROGRESS || run.getStatus() == RunStatus.QUEUED); assertSame(RunStatus.COMPLETED, run.getStatus()); diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/models/FunctionCallPreset.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/models/FunctionCallPreset.java index f2ca84984c34..0cb1ab118f36 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/models/FunctionCallPreset.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/models/FunctionCallPreset.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) TypeSpec Code Generator. - package com.azure.ai.openai.implementation.models; import com.azure.core.annotation.Generated; @@ -13,6 +12,7 @@ * operation. */ public final class FunctionCallPreset extends ExpandableStringEnum { + /** * Specifies that the model may either use any of the functions provided in this chat completions request or * instead return a standard chat completions response as if no functions were provided. @@ -29,7 +29,7 @@ public final class FunctionCallPreset extends ExpandableStringEnum "Subscription id: " + getSubscriptionId()); + LOGGER.log(LogLevel.VERBOSE, () -> "Resource group: " + getResourceGroup()); + LOGGER.log(LogLevel.VERBOSE, () -> "Workspace: " + getWorkspaceName()); + LOGGER.log(LogLevel.VERBOSE, () -> "Location: " + getLocation()); + LOGGER.log(LogLevel.VERBOSE, () -> "Endpoint: " + getEndpoint()); + LOGGER.log(LogLevel.VERBOSE, () -> "Test mode: " + getTestMode()); QuantumClientBuilder builder = new QuantumClientBuilder(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/AppPlatformTest.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/AppPlatformTest.java index e296384651bd..812417c877c2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/AppPlatformTest.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/test/java/com/azure/resourcemanager/appplatform/AppPlatformTest.java @@ -10,6 +10,8 @@ import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.appservice.AppServiceManager; import com.azure.resourcemanager.dns.DnsZoneManager; import com.azure.resourcemanager.keyvault.KeyVaultManager; @@ -33,6 +35,8 @@ import java.util.List; public class AppPlatformTest extends ResourceManagerTestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(AppPlatformTest.class); + protected AppPlatformManager appPlatformManager; protected AppServiceManager appServiceManager; protected DnsZoneManager dnsZoneManager; @@ -85,10 +89,10 @@ protected boolean checkRedirect(String url) throws IOException { if (connection.getResponseCode() / 100 == 3) { return true; } - System.out.printf("Do request to %s with response code %d%n", url, connection.getResponseCode()); + LOGGER.verbose("Do request to {} with response code {}", url, connection.getResponseCode()); } } catch (Exception e) { - System.err.printf("Do request to %s with error %s%n", url, e.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> "Do request to " + url + " with error", e); } finally { connection.disconnect(); } @@ -103,13 +107,13 @@ protected boolean requestSuccess(String url) throws Exception { try { connection.connect(); if (connection.getResponseCode() == 200) { - System.out.printf("Request to %s succeeded%n", url); + LOGGER.log(LogLevel.VERBOSE, () -> "Request to " + url + " succeeded"); connection.getInputStream().close(); return true; } - System.out.printf("Do request to %s with response code %d%n", url, connection.getResponseCode()); + LOGGER.verbose("Do request to {} with response code {}", url, connection.getResponseCode()); } catch (Exception e) { - System.err.printf("Do request to %s with error %s%n", url, e.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> "Do request to " + url + " with error", e); } finally { connection.disconnect(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/OneDeployTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/OneDeployTests.java index 1d86fb736472..066f8aaf5346 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/OneDeployTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/OneDeployTests.java @@ -96,7 +96,7 @@ public void canPushDeployJar() throws Exception { Assertions.assertNotNull(deploymentId); // stream logs - webApp1.streamApplicationLogsAsync().subscribeOn(Schedulers.single()).subscribe(System.out::println); + webApp1.streamApplicationLogsAsync().subscribeOn(Schedulers.single()).subscribe(LOGGER::verbose); waitForRuntimeSuccess(webApp1, deploymentId); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/implementation/RetryTests.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/implementation/RetryTests.java index fdb1ce8debff..3e50a823425b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/implementation/RetryTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/test/java/com/azure/resourcemanager/authorization/implementation/RetryTests.java @@ -6,6 +6,8 @@ import com.azure.core.http.HttpResponse; import com.azure.core.management.exception.ManagementError; import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import com.azure.resourcemanager.test.utils.TestDelayProvider; import org.junit.jupiter.api.Assertions; @@ -19,6 +21,7 @@ import java.util.concurrent.atomic.AtomicInteger; public class RetryTests { + private static final ClientLogger LOGGER = new ClientLogger(RetryTests.class); @Test public void testRetryForGraph() { @@ -33,9 +36,8 @@ public void testRetryForGraph() { RetryBackoffSpec retry = RetryUtils.backoffRetryFor404ResourceNotFound(); AtomicInteger retryCount = new AtomicInteger(0); - retry = retry.doAfterRetry(ignored -> { - System.out.println("retry " + retryCount.incrementAndGet() + ", at " + OffsetDateTime.now()); - }); + retry = retry.doAfterRetry(ignored -> LOGGER.log(LogLevel.VERBOSE, + () -> "retry " + retryCount.incrementAndGet() + ", at " + OffsetDateTime.now())); // pass without retry Mono monoSuccess = Mono.just("foo"); @@ -106,9 +108,8 @@ public void testRetryForAuthorization() { RetryBackoffSpec retry = RetryUtils.backoffRetryFor400PrincipalNotFound(); AtomicInteger retryCount = new AtomicInteger(0); - retry = retry.doAfterRetry(ignored -> { - System.out.println("retry " + retryCount.incrementAndGet() + ", at " + OffsetDateTime.now()); - }); + retry = retry.doAfterRetry(ignored -> LOGGER.log(LogLevel.VERBOSE, + () -> "retry " + retryCount.incrementAndGet() + ", at " + OffsetDateTime.now())); // 400 with PrincipalNotFound, retry till pass AtomicInteger errorCount = new AtomicInteger(0); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineImageOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineImageOperationsTests.java index 770a9dbbf94c..c6cead94f558 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineImageOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineImageOperationsTests.java @@ -4,6 +4,8 @@ package com.azure.resourcemanager.compute; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.compute.models.DataDiskImage; import com.azure.resourcemanager.compute.models.VirtualMachineImage; import com.azure.resourcemanager.compute.models.VirtualMachineOffer; @@ -14,6 +16,8 @@ import org.junit.jupiter.api.Test; public class VirtualMachineImageOperationsTests extends ComputeManagementTest { + private static final ClientLogger LOGGER = new ClientLogger(VirtualMachineImageOperationsTests.class); + @Test public void canListVirtualMachineImages() throws Exception { /* @@ -37,7 +41,7 @@ public void canListVirtualMachineImages() throws Exception { for (VirtualMachineOffer offer : canonicalPublisher.offers().list()) { for (VirtualMachineSku sku : offer.skus().list()) { for (VirtualMachineImage image : sku.images().list()) { - System.out.println(image.version()); + LOGGER.log(LogLevel.VERBOSE, image::version); firstVMImage = image; break; } diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedDiskOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedDiskOperationsTests.java index e514f890fea4..d8e3d7ae823a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedDiskOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineManagedDiskOperationsTests.java @@ -4,6 +4,8 @@ package com.azure.resourcemanager.compute; import com.azure.core.http.HttpPipeline; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.compute.models.AvailabilitySet; import com.azure.resourcemanager.compute.models.AvailabilitySetSkuTypes; import com.azure.resourcemanager.compute.models.CachingTypes; @@ -28,6 +30,8 @@ import org.junit.jupiter.api.Test; public class VirtualMachineManagedDiskOperationsTests extends ComputeManagementTest { + private static final ClientLogger LOGGER = new ClientLogger(VirtualMachineManagedDiskOperationsTests.class); + private String rgName = ""; private Region region = Region.US_EAST; private KnownLinuxVirtualMachineImage linuxImage = KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS; @@ -314,7 +318,7 @@ public void canCreateVirtualMachineFromCustomImageWithManagedDisks() { .withSize(VirtualMachineSizeTypes.fromString("Standard_D4a_v4")) .withOSDiskCaching(CachingTypes.READ_WRITE) .create(); - System.out.println("Waiting for some time before de-provision"); + LOGGER.log(LogLevel.VERBOSE, () -> "Waiting for some time before de-provision"); sleep(60 * 1000); // Wait for some time to ensure vm is publicly accessible deprovisionAgentInLinuxVM(virtualMachine1); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineOperationsTests.java index f6acacb5f6b4..6dbbc6ab4f03 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineOperationsTests.java @@ -13,6 +13,8 @@ import com.azure.core.test.annotation.DoNotRecord; import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.polling.LongRunningOperationStatus; import com.azure.core.util.polling.PollResponse; import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner; @@ -82,6 +84,8 @@ import java.util.concurrent.atomic.AtomicInteger; public class VirtualMachineOperationsTests extends ComputeManagementTest { + private static final ClientLogger LOGGER = new ClientLogger(VirtualMachineOperationsTests.class); + private String rgName = ""; private String rgName2 = ""; private final Region region = Region.US_EAST; @@ -731,7 +735,7 @@ public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws createdResource -> { if (createdResource instanceof Resource) { Resource resource = (Resource) createdResource; - System.out.println("Created: " + resource.id()); + LOGGER.log(LogLevel.VERBOSE, () -> "Created: " + resource.id()); if (resource instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) resource; Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineRelatedResourcesDeletionTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineRelatedResourcesDeletionTests.java index aaf5daeb295a..0f72c477a604 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineRelatedResourcesDeletionTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineRelatedResourcesDeletionTests.java @@ -6,6 +6,8 @@ import com.azure.core.http.HttpPipeline; import com.azure.core.management.exception.ManagementException; import com.azure.core.test.annotation.DoNotRecord; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.compute.models.AvailabilitySet; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; import com.azure.resourcemanager.compute.models.VirtualMachine; @@ -31,6 +33,7 @@ import reactor.core.publisher.Mono; public class VirtualMachineRelatedResourcesDeletionTests extends ComputeManagementTest { + private static final ClientLogger LOGGER = new ClientLogger(VirtualMachineRelatedResourcesDeletionTests.class); private String rgName = ""; @@ -166,7 +169,7 @@ public void canDeleteRelatedResourcesFromFailedParallelVMCreations() { createdResource -> { if (createdResource instanceof Resource) { Resource resource = (Resource) createdResource; - System.out.println("Created: " + resource.id()); + LOGGER.log(LogLevel.VERBOSE, () -> "Created: " + resource.id()); if (resource instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) resource; @@ -220,22 +223,23 @@ public void canDeleteRelatedResourcesFromFailedParallelVMCreations() { // Show any errors for (Throwable error : errors) { - System.out.println("\n### ERROR ###\n"); + LOGGER.log(LogLevel.VERBOSE, () -> "\n### ERROR ###\n"); if (error instanceof ManagementException) { ManagementException ce = (ManagementException) error; - System.out.println("CLOUD EXCEPTION: " + ce.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> "CLOUD EXCEPTION: " + ce.getMessage()); } else { - error.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Only expected ManagementExceptions", error); } } - System.out.println("Number of failed/cleaned up VM creations: " + vmNonNicResourceDefinitions.size()); + LOGGER.log(LogLevel.VERBOSE, + () -> "Number of failed/cleaned up VM creations: " + vmNonNicResourceDefinitions.size()); // Verifications final int successfulVMCount = desiredVMCount - vmNonNicResourceDefinitions.size(); final int actualVMCount = TestUtilities.getSize(computeManager.virtualMachines().listByResourceGroup(resourceGroupName)); - System.out.println("Number of actual successful VMs: " + actualVMCount); + LOGGER.log(LogLevel.VERBOSE, () -> "Number of actual successful VMs: " + actualVMCount); Assertions.assertEquals(successfulVMCount, actualVMCount); final int actualNicCount = diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java index f7a3930a4ef3..66b802421cb9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java @@ -7,6 +7,8 @@ import com.azure.core.http.policy.AddHeadersFromContextPolicy; import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.containerservice.models.AgentPool; import com.azure.resourcemanager.containerservice.models.AgentPoolData; import com.azure.resourcemanager.containerservice.models.AgentPoolMode; @@ -48,6 +50,8 @@ import java.util.stream.Collectors; public class KubernetesClustersTests extends ContainerServiceManagementTest { + private static final ClientLogger LOGGER = new ClientLogger(KubernetesClustersTests.class); + private static final String SSH_KEY = sshPublicKey(); @Test @@ -256,7 +260,8 @@ public void canAutoScaleKubernetesCluster() { .create(); // print config - System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); + LOGGER.log(LogLevel.VERBOSE, + () -> new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); Assertions.assertEquals(Code.RUNNING, kubernetesCluster.powerState().code()); @@ -335,7 +340,8 @@ public void canCreateClusterWithSpotVM() { .create(); // print config - System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); + LOGGER.log(LogLevel.VERBOSE, + () -> new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName); Assertions.assertTrue(agentPoolProfile.virtualMachinePriority() == null || agentPoolProfile.virtualMachinePriority() == ScaleSetPriority.REGULAR); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorActivityAndMetricsTests.java b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorActivityAndMetricsTests.java index 83d9d1561a15..dee1fa063b69 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorActivityAndMetricsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/src/test/java/com/azure/resourcemanager/monitor/MonitorActivityAndMetricsTests.java @@ -9,6 +9,8 @@ import com.azure.core.management.exception.ManagementException; import com.azure.core.management.profile.AzureProfile; import com.azure.core.test.annotation.DoNotRecord; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.compute.models.VirtualMachine; import com.azure.resourcemanager.monitor.models.EventData; import com.azure.resourcemanager.monitor.models.EventDataPropertyName; @@ -24,6 +26,8 @@ import java.time.OffsetDateTime; public class MonitorActivityAndMetricsTests extends MonitorManagementTest { + private static final ClientLogger LOGGER = new ClientLogger(MonitorActivityAndMetricsTests.class); + private String rgName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { @@ -49,7 +53,7 @@ public void canListEventsAndMetrics() { "10.0.0.0/28"); OffsetDateTime now = OffsetDateTime.now(); - System.out.println("record timestamp: " + now); + LOGGER.log(LogLevel.VERBOSE, () -> "record timestamp: " + now); OffsetDateTime recordDateTime = now.minusDays(40); @@ -143,7 +147,7 @@ public void canListEventsAndMetricsWithWhiteSpaceInResourceId() { SqlElasticPool pool = ensureElasticPoolWithWhiteSpace(region, rgName); OffsetDateTime now = OffsetDateTime.now(); - System.out.println("record timestamp: " + now); + LOGGER.log(LogLevel.VERBOSE, () -> "record timestamp: " + now); OffsetDateTime recordDateTime = now.minusDays(40); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentsTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentsTests.java index d81b0ab2e248..a4c355636f15 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentsTests.java @@ -10,6 +10,8 @@ import com.azure.core.management.exception.ManagementError; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.polling.LongRunningOperationStatus; import com.azure.core.util.polling.PollResponse; import com.azure.resourcemanager.test.utils.TestUtilities; @@ -38,6 +40,8 @@ import java.util.stream.Collectors; public class DeploymentsTests extends ResourceManagementTest { + private static final ClientLogger LOGGER = new ClientLogger(DeploymentsTests.class); + private ResourceGroups resourceGroups; private ResourceGroup resourceGroup; @@ -446,7 +450,7 @@ public void canDeployVirtualNetworkWithContext() { try { String correlationRequestId = generateRandomUuid(); - System.out.println("x-ms-correlation-request-id: " + correlationRequestId); + LOGGER.log(LogLevel.VERBOSE, () -> "x-ms-correlation-request-id: " + correlationRequestId); Context context = new Context( AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders().set("x-ms-correlation-request-id", correlationRequestId)); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/BreadSliceImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/BreadSliceImpl.java index 4ce5407d2550..e2d2e643964b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/BreadSliceImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/BreadSliceImpl.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager.resources.fluentcore.dag; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.model.Creatable; import com.azure.resourcemanager.resources.fluentcore.model.Executable; import com.azure.resourcemanager.resources.fluentcore.model.implementation.ExecutableImpl; @@ -14,6 +16,8 @@ * Implementation for IBreadSlice. */ public class BreadSliceImpl extends ExecutableImpl implements IBreadSlice { + private static final ClientLogger LOGGER = new ClientLogger(BreadSliceImpl.class); + private final String name; public BreadSliceImpl(String name) { @@ -23,7 +27,7 @@ public BreadSliceImpl(String name) { @Override public Mono executeWorkAsync() { - System.out.println("Bread(" + this.name + ")::executeWorkAsync() [Getting slice from store]"); + LOGGER.log(LogLevel.VERBOSE, () -> "Bread(" + this.name + ")::executeWorkAsync() [Getting slice from store]"); return Mono.just(this) .delayElement(Duration.ofMillis(250)) .map(breadSlice -> breadSlice); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGErrorTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGErrorTests.java index 6d8b11398cb9..4df71ac7a2c5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGErrorTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGErrorTests.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager.resources.fluentcore.dag; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; @@ -14,6 +16,8 @@ import java.util.TreeSet; public class DAGErrorTests { + private static final ClientLogger LOGGER = new ClientLogger(DAGErrorTests.class); + @Test public void testTerminateOnInProgressTaskCompletion() { // Terminate on error strategy used in this task group is @@ -107,20 +111,19 @@ public void testTerminateOnInProgressTaskCompletion() { .withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION); IPancake rootPancake = pancakeFtg.invokeAsync(context).map(indexable -> { IPancake pancake = (IPancake) indexable; - System.out.println("map.onNext: " + pancake.name()); + LOGGER.log(LogLevel.VERBOSE, () -> "map.onNext: " + pancake.name()); seen.add(pancake.name()); return pancake; - }) - .onErrorResume(throwable -> { - System.out.println("map.onErrorResumeNext: " + throwable); - exceptions.add(throwable); - return Mono.empty(); - }).blockLast(); + }).onErrorResume(throwable -> { + LOGGER.log(LogLevel.VERBOSE, () -> "map.onErrorResumeNext: ", throwable); + exceptions.add(throwable); + return Mono.empty(); + }).blockLast(); expectedToSee.removeAll(seen); Assertions.assertTrue(expectedToSee.isEmpty()); Assertions.assertEquals(exceptions.size(), 1); - Assertions.assertTrue(exceptions.get(0) instanceof RuntimeException); + Assertions.assertInstanceOf(RuntimeException.class, exceptions.get(0)); RuntimeException runtimeException = (RuntimeException) exceptions.get(0); Assertions.assertTrue(runtimeException.getMessage().equalsIgnoreCase("B")); } @@ -227,20 +230,19 @@ public void testTerminateOnHittingLcaTask() { IPasta rootPasta = pastaFtg.invokeAsync(context).map(indexable -> { IPasta pasta = (IPasta) indexable; - System.out.println("map.onNext: " + pasta.name()); + LOGGER.log(LogLevel.VERBOSE, () -> "map.onNext: " + pasta.name()); seen.add(pasta.name()); return pasta; - }) - .onErrorResume(throwable -> { - System.out.println("map.onErrorResumeNext: " + throwable); - exceptions.add(throwable); - return Mono.empty(); - }).blockLast(); + }).onErrorResume(throwable -> { + LOGGER.log(LogLevel.VERBOSE, () -> "map.onErrorResumeNext: ", throwable); + exceptions.add(throwable); + return Mono.empty(); + }).blockLast(); expectedToSee.removeAll(seen); Assertions.assertTrue(expectedToSee.isEmpty()); Assertions.assertEquals(exceptions.size(), 1); - Assertions.assertTrue(exceptions.get(0) instanceof RuntimeException); + Assertions.assertInstanceOf(RuntimeException.class, exceptions.get(0)); RuntimeException runtimeException = (RuntimeException) exceptions.get(0); Assertions.assertTrue(runtimeException.getMessage().equalsIgnoreCase("B")); } @@ -344,11 +346,11 @@ public void testCompositeError() { IPancake rootPancake = pancakeFtg.invokeAsync(context).map(indexable -> { IPancake pancake = (IPancake) indexable; String name = pancake.name(); - System.out.println("map.onNext:" + name); + LOGGER.log(LogLevel.VERBOSE, () -> "map.onNext:" + name); seen.add(name); return pancake; }).onErrorResume(throwable -> { - System.out.println("map.onErrorResumeNext:" + throwable); + LOGGER.log(LogLevel.VERBOSE, () -> "map.onErrorResumeNext:", throwable); exceptions.add(throwable); return Mono.empty(); }).blockLast(); @@ -356,7 +358,7 @@ public void testCompositeError() { expectedToSee.removeAll(seen); Assertions.assertTrue(expectedToSee.isEmpty()); Assertions.assertEquals(exceptions.size(), 1); - Assertions.assertTrue(exceptions.get(0) instanceof RuntimeException); + Assertions.assertInstanceOf(RuntimeException.class, exceptions.get(0)); RuntimeException compositeException = (RuntimeException) exceptions.get(0); Assertions.assertEquals(compositeException.getSuppressed().length, 2); for (Throwable throwable : compositeException.getSuppressed()) { @@ -462,10 +464,10 @@ public void testErrorOnRoot() { IPancake rootPancake = pancakeFtg.invokeAsync(context).map(indexable -> { IPancake pancake = (IPancake) indexable; seen.add(pancake.name()); - System.out.println("map.onNext:" + pancake.name()); + LOGGER.log(LogLevel.VERBOSE, () -> "map.onNext:" + pancake.name()); return pancake; }).onErrorResume(throwable -> { - System.out.println("map.onErrorResumeNext:" + throwable); + LOGGER.log(LogLevel.VERBOSE, () -> "map.onErrorResumeNext:", throwable); exceptions.add(throwable); return Mono.empty(); }).blockLast(); @@ -473,7 +475,7 @@ public void testErrorOnRoot() { expectedToSee.removeAll(seen); Assertions.assertTrue(expectedToSee.isEmpty()); Assertions.assertEquals(exceptions.size(), 1); - Assertions.assertTrue(exceptions.get(0) instanceof RuntimeException); + Assertions.assertInstanceOf(RuntimeException.class, exceptions.get(0)); RuntimeException runtimeException = (RuntimeException) exceptions.get(0); Assertions.assertTrue(runtimeException.getMessage().equalsIgnoreCase("F")); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTests.java index f2a9814a8c92..ba6710befa36 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/DAGraphTests.java @@ -15,7 +15,7 @@ public class DAGraphTests { @Test public void testDAGraphGetNext() { - /** + /* * |-------->[D]------>[B]-----------[A] * | ^ ^ * | | | @@ -85,7 +85,7 @@ public void testDAGraphGetNext() { @Test public void testGraphDependency() { - /** + /* * |-------->[D]------>[B]---------->[A] * | ^ ^ * | | | @@ -148,7 +148,7 @@ public void testGraphDeadLockDetection() { boolean dlDetected; // ---------------------------------------------------- - /** + /* * [A] <-----------> [A] */ dlDetected = false; @@ -161,7 +161,7 @@ public void testGraphDeadLockDetection() { Assertions.assertTrue(dlDetected, "Expected exception is not thrown"); // ---------------------------------------------------- - /** + /* * [A] -----------> [B] * ^ ^ * | | @@ -184,7 +184,7 @@ public void testGraphDeadLockDetection() { Assertions.assertTrue(dlDetected, "Expected exception is not thrown"); // ---------------------------------------------------- - /** + /* * [2] ------------> [1] * ^ | * ----------------| | @@ -211,7 +211,7 @@ public void testGraphNodeTableBubblingUp() { // ---------------------------------------------------- // Graph-1 - /** + /* * [B] -----------> [A] * ^ ^ * | | @@ -232,7 +232,7 @@ public void testGraphNodeTableBubblingUp() { // ---------------------------------------------------- // Graph-2 - /** + /* * [E] ---> [D] ---> G * ^ * | @@ -252,7 +252,7 @@ public void testGraphNodeTableBubblingUp() { // ---------------------------------------------------- // Graph-3 - /** + /* * [J] ---> [H] ---> I */ @@ -276,7 +276,7 @@ public void testGraphNodeTableBubblingUp() { DAGraph graph4Root1 = graph2Root; // graphF DAGraph graph4Root2 = graph3Root; // graphJ - /** + /* * [B] -----------> [A] * ^ ^ * | | @@ -373,7 +373,7 @@ public void testGraphNodeTableBubblingUp() { // ---------------------------------------------------- // Graph-1 - /** + /* * [L] -----------> [K] * ^ ^ * | | @@ -395,7 +395,7 @@ public void testGraphNodeTableBubblingUp() { // graphA.addDependencyGraph(graphL); - /** + /* * |---------> [L] -----------> [K] * | ^ ^ * | | | @@ -462,17 +462,15 @@ public void testGraphNodeTableBubblingUp() { private DAGraph createGraph(String resourceName) { ItemHolder node = new ItemHolder(resourceName, "data" + resourceName); - DAGraph graph = new DAGraph<>(node); - return graph; + return new DAGraph<>(node); } private void assertExactMatch(Set set, String[] values) { - HashSet s = new HashSet<>(); - s.addAll(set); + HashSet s = new HashSet<>(set); - s.removeAll(Arrays.asList(values)); - if (s.size() != 0) { - Assertions.assertTrue(false, "Content of set " + set + " does not match with provided array " + Arrays.asList(values)); + Arrays.asList(values).forEach(s::remove); + if (!s.isEmpty()) { + Assertions.fail("Content of set " + set + " does not match with provided array " + Arrays.asList(values)); } } } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/OrderImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/OrderImpl.java index 81f498b22ec2..d4ac227fff7c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/OrderImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/OrderImpl.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager.resources.fluentcore.dag; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.model.implementation.CreatableUpdatableImpl; import reactor.core.publisher.Mono; @@ -14,6 +16,8 @@ public class OrderImpl extends CreatableUpdatableImpl implements IOrder { + private static final ClientLogger LOGGER = new ClientLogger(OrderImpl.class); + /** * Creates SandwichImpl. * @@ -26,7 +30,7 @@ protected OrderImpl(String name, OrderInner innerObject) { @Override public Mono createResourceAsync() { - System.out.println("Order(" + this.name() + ")::createResourceAsync() [Creating order]"); + LOGGER.log(LogLevel.VERBOSE, () -> "Order(" + this.name() + ")::createResourceAsync() [Creating order]"); return Mono.just(this) .delayElement(Duration.ofMillis(250)) .map(sandwich -> sandwich); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PanCakeImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PanCakeImpl.java index c1c13ddb0f92..743ff9dac62b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PanCakeImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PanCakeImpl.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager.resources.fluentcore.dag; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.model.Creatable; import com.azure.resourcemanager.resources.fluentcore.model.implementation.CreatableUpdatableImpl; import com.azure.resourcemanager.resources.fluentcore.model.implementation.CreateUpdateTask; @@ -19,6 +21,8 @@ class PancakeImpl extends CreatableUpdatableImpl implements IPancake { + private static final ClientLogger LOGGER = new ClientLogger(PancakeImpl.class); + final List> delayedPancakes; final long eventDelayInMilliseconds; final Throwable errorToThrow; @@ -73,19 +77,19 @@ public void beforeGroupCreateOrUpdate() { this.addDependency(pancake); } int newCount = this.taskGroup().getNode(this.key()).dependencyKeys().size(); - System.out.println("Pancake(" + this.name() + ")::beforeGroupCreateOrUpdate() 'delayedSize':" + this.delayedPancakes.size() - + " 'dependency count [old, new]': [" + oldCount + "," + newCount + "]"); + LOGGER.log(LogLevel.VERBOSE, () -> "Pancake(" + this.name() + ")::beforeGroupCreateOrUpdate() 'delayedSize':" + + this.delayedPancakes.size() + " 'dependency count [old, new]': [" + oldCount + "," + newCount + "]"); } @Override public Mono createResourceAsync() { if (this.errorToThrow == null) { - System.out.println("Pancake(" + this.name() + ")::createResourceAsync() 'onNext()'"); + LOGGER.log(LogLevel.VERBOSE, () -> "Pancake(" + this.name() + ")::createResourceAsync() 'onNext()'"); return Mono.just(this) .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) .map(pancake -> pancake); } else { - System.out.println("Pancake(" + this.name() + ")::createResourceAsync() 'onError()'"); + LOGGER.log(LogLevel.VERBOSE, () -> "Pancake(" + this.name() + ")::createResourceAsync() 'onError()'"); return Mono.just(this) .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) .flatMap(pancake -> toErrorMono(errorToThrow)); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PastaImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PastaImpl.java index 92c73ad79bd6..f38f7f9ebd70 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PastaImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PastaImpl.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager.resources.fluentcore.dag; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.model.Creatable; import com.azure.resourcemanager.resources.fluentcore.model.implementation.CreatableUpdatableImpl; import com.azure.resourcemanager.resources.fluentcore.model.implementation.CreateUpdateTask; @@ -19,6 +21,8 @@ class PastaImpl extends CreatableUpdatableImpl implements IPasta { + private static final ClientLogger LOGGER = new ClientLogger(PastaImpl.class); + final List> delayedPastas; final long eventDelayInMilliseconds; final Throwable errorToThrow; @@ -74,19 +78,19 @@ public void beforeGroupCreateOrUpdate() { this.addDependency(pancake); } int newCount = this.taskGroup().getNode(this.key()).dependencyKeys().size(); - System.out.println("Pasta(" + this.name() + ")::beforeGroupCreateOrUpdate() 'delayedSize':" + this.delayedPastas.size() - + " 'dependency count [old, new]': [" + oldCount + "," + newCount + "]"); + LOGGER.log(LogLevel.VERBOSE, () -> "Pasta(" + this.name() + ")::beforeGroupCreateOrUpdate() 'delayedSize':" + + this.delayedPastas.size() + " 'dependency count [old, new]': [" + oldCount + "," + newCount + "]"); } @Override public Mono createResourceAsync() { if (this.errorToThrow == null) { - System.out.println("Pasta(" + this.name() + ")::createResourceAsync() 'onNext()'"); + LOGGER.log(LogLevel.VERBOSE, () -> "Pasta(" + this.name() + ")::createResourceAsync() 'onNext()'"); return Mono.just(this) .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) .map(pasta -> pasta); } else { - System.out.println("Pasta(" + this.name() + ")::createResourceAsync() 'onError()'"); + LOGGER.log(LogLevel.VERBOSE, () -> "Pasta(" + this.name() + ")::createResourceAsync() 'onError()'"); return Mono.just(this) .delayElement(Duration.ofMillis(this.eventDelayInMilliseconds)) .flatMap(pasta -> toErrorObservable(errorToThrow)); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PizzaImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PizzaImpl.java index 761d0b600040..dc72b43c093f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PizzaImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/PizzaImpl.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager.resources.fluentcore.dag; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.model.Creatable; import com.azure.resourcemanager.resources.fluentcore.model.implementation.CreatableUpdatableImpl; import com.azure.resourcemanager.resources.fluentcore.model.implementation.CreateUpdateTask; @@ -19,6 +21,8 @@ class PizzaImpl extends CreatableUpdatableImpl implements IPizza { + private static final ClientLogger LOGGER = new ClientLogger(PizzaImpl.class); + final List> delayedPizzas; boolean prepareCalled = false; @@ -61,13 +65,13 @@ public void beforeGroupCreateOrUpdate() { this.addDependency(pizza); } int newCount = this.taskGroup().getNode(this.key()).dependencyKeys().size(); - System.out.println("Pizza(" + this.name() + ")::beforeGroupCreateOrUpdate() 'delayedSize':" + this.delayedPizzas.size() - + " 'dependency count [old, new]': [" + oldCount + "," + newCount + "]"); + LOGGER.log(LogLevel.VERBOSE, () -> "Pizza(" + this.name() + ")::beforeGroupCreateOrUpdate() 'delayedSize':" + + this.delayedPizzas.size() + " 'dependency count [old, new]': [" + oldCount + "," + newCount + "]"); } @Override public Mono createResourceAsync() { - System.out.println("Pizza(" + this.name() + ")::createResourceAsync()"); + LOGGER.log(LogLevel.VERBOSE, () -> "Pizza(" + this.name() + ")::createResourceAsync()"); return Mono.just(this) .delayElement(Duration.ofMillis(250)) .map(pizza -> pizza); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ProxyTaskGroupTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ProxyTaskGroupTests.java index c55b04569380..58fd15b5786e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ProxyTaskGroupTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/ProxyTaskGroupTests.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager.resources.fluentcore.dag; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.model.Indexable; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -19,6 +21,7 @@ import java.util.concurrent.CountDownLatch; public class ProxyTaskGroupTests { + private static final ClientLogger LOGGER = new ClientLogger(ProxyTaskGroupTests.class); @Test public void testSampleTaskGroupSanity() { @@ -539,7 +542,7 @@ public void testTaskGroupInvocationShouldInvokePostRunDependentTaskGroup() { group1.invokeAsync(group1.newInvocationContext()) - .subscribe(indexable -> System.out.println(indexable.key())); + .subscribe(indexable -> LOGGER.log(LogLevel.VERBOSE, indexable::key)); } @Test diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/SandwichImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/SandwichImpl.java index 3b6a26bf6a3a..419086bfe47c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/SandwichImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/dag/SandwichImpl.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager.resources.fluentcore.dag; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.model.Executable; import com.azure.resourcemanager.resources.fluentcore.model.implementation.CreatableUpdatableImpl; import reactor.core.publisher.Mono; @@ -15,6 +17,8 @@ public class SandwichImpl extends CreatableUpdatableImpl implements ISandwich { + private static final ClientLogger LOGGER = new ClientLogger(SandwichImpl.class); + /** * Creates SandwichImpl. * @@ -34,7 +38,7 @@ public ISandwich withBreadSliceFromStore(Executable breadFetcher) { @Override public Mono createResourceAsync() { - System.out.println("Sandwich(" + this.name() + ")::createResourceAsync() [Creating sandwich]"); + LOGGER.log(LogLevel.VERBOSE, () -> "Sandwich(" + this.name() + ")::createResourceAsync() [Creating sandwich]"); return Mono.just(this) .delayElement(Duration.ofMillis(250)) .map(sandwich -> sandwich); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml index 708b387ded37..bcfbeb0aaa34 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml @@ -124,12 +124,12 @@ com.azure azure-messaging-servicebus - 7.16.0 + 7.17.0 io.fabric8 kubernetes-client - 5.12.3 + 6.12.1 com.microsoft.sqlserver @@ -195,7 +195,7 @@ org.apache.httpcomponents:httpclient:[4.5.14] - io.fabric8:kubernetes-client:[5.12.3] + io.fabric8:kubernetes-client:[6.12.1] com.jcraft:jsch:[0.1.55] org.slf4j:slf4j-simple:[1.7.36] com.google.guava:guava:[33.1.0-jre] diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ApplicationGatewayTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ApplicationGatewayTests.java index f47cf9a846e4..b481cdee7727 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ApplicationGatewayTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/ApplicationGatewayTests.java @@ -9,6 +9,8 @@ import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; import com.azure.resourcemanager.compute.models.VirtualMachine; import com.azure.resourcemanager.network.models.ApplicationGateway; @@ -46,6 +48,8 @@ import org.junit.jupiter.api.Test; public class ApplicationGatewayTests extends ResourceManagerTestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(ApplicationGatewayTests.class); + private AzureResourceManager azureResourceManager; @Override @@ -228,7 +232,7 @@ public void testAppGatewayBackendHealthCheck() throws Exception { } } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, () -> info.toString()); // Verify app gateway Assertions.assertEquals(2, appGateway.backends().size()); @@ -247,8 +251,8 @@ public void testAppGatewayBackendHealthCheck() throws Exception { ApplicationGatewayBackendHealth backendHealth1 = backendHealths.get(backend1.name()); Assertions.assertNotNull(backendHealth1); Assertions.assertNotNull(backendHealth1.backend()); - for (int i = 0; i < ipAddresses.length; i++) { - Assertions.assertTrue(backend1.containsIPAddress(ipAddresses[i])); + for (String ipAddress : ipAddresses) { + Assertions.assertTrue(backend1.containsIPAddress(ipAddress)); } // Verify second backend (NIC based) diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java index 6f128a12344d..dcab933c7130 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java @@ -9,10 +9,14 @@ import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.Region; import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.profile.AzureProfile; import com.azure.core.test.annotation.DoNotRecord; import com.azure.core.test.models.TestProxySanitizer; import com.azure.core.test.models.TestProxySanitizerType; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.authorization.models.BuiltInRole; import com.azure.resourcemanager.compute.models.CachingTypes; import com.azure.resourcemanager.compute.models.Disk; @@ -49,27 +53,33 @@ import com.azure.resourcemanager.network.models.Subnet; import com.azure.resourcemanager.network.models.Topology; import com.azure.resourcemanager.network.models.VerificationIPFlow; -import com.azure.resourcemanager.resources.fluentcore.model.CreatedResources; -import com.azure.resourcemanager.resources.models.LockLevel; -import com.azure.resourcemanager.resources.models.ManagementLock; -import com.azure.resourcemanager.resources.models.ResourceGroup; -import com.azure.resourcemanager.storage.models.StorageAccountSkuType; -import com.azure.resourcemanager.test.utils.TestUtilities; import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; -import com.azure.core.management.Region; import com.azure.resourcemanager.resources.fluentcore.model.Creatable; -import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.resources.fluentcore.model.CreatedResources; import com.azure.resourcemanager.resources.fluentcore.utils.HttpPipelineProvider; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import com.azure.resourcemanager.resources.models.Deployment; import com.azure.resourcemanager.resources.models.DeploymentMode; import com.azure.resourcemanager.resources.models.GenericResource; import com.azure.resourcemanager.resources.models.Location; +import com.azure.resourcemanager.resources.models.LockLevel; +import com.azure.resourcemanager.resources.models.ManagementLock; import com.azure.resourcemanager.resources.models.RegionCategory; import com.azure.resourcemanager.resources.models.RegionType; +import com.azure.resourcemanager.resources.models.ResourceGroup; import com.azure.resourcemanager.resources.models.Subscription; import com.azure.resourcemanager.storage.models.StorageAccount; -import java.io.IOException; +import com.azure.resourcemanager.storage.models.StorageAccountSkuType; +import com.azure.resourcemanager.test.ResourceManagerTestProxyTestBase; +import com.azure.resourcemanager.test.utils.TestDelayProvider; +import com.azure.resourcemanager.test.utils.TestIdentifierProvider; +import com.azure.resourcemanager.test.utils.TestUtilities; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; + import java.text.MessageFormat; import java.time.Duration; import java.time.temporal.ChronoUnit; @@ -84,16 +94,9 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import com.azure.resourcemanager.test.ResourceManagerTestProxyTestBase; -import com.azure.resourcemanager.test.utils.TestDelayProvider; -import com.azure.resourcemanager.test.utils.TestIdentifierProvider; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Flux; -import reactor.core.scheduler.Schedulers; - public class AzureResourceManagerTests extends ResourceManagerTestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(AzureResourceManagerTests.class); + private AzureResourceManager azureResourceManager; public AzureResourceManagerTests() { @@ -138,7 +141,6 @@ protected void cleanUpResources() { /** * Stress-tests the resilience of ExpandableEnum to multi-threaded access * - * @throws Exception */ @Test public void testExpandableEnum() throws Exception { @@ -223,17 +225,17 @@ public void run() { // Verify country ISO codes Collection countryIsoCodes = CountryIsoCode.values(); - System.out.println("\n## Country ISO codes: " + countryIsoCodes.size()); + LOGGER.log(LogLevel.VERBOSE, () -> "\n## Country ISO codes: " + countryIsoCodes.size()); for (CountryIsoCode value : countryIsoCodes) { - System.out.println(value.toString()); + LOGGER.log(LogLevel.VERBOSE, value::toString); } Assertions.assertEquals(257, countryIsoCodes.size()); // Verify power states Collection powerStates = PowerState.values(); - System.out.println("\n## Power states: " + powerStates.size()); + LOGGER.log(LogLevel.VERBOSE, () -> "\n## Power states: " + powerStates.size()); for (PowerState value : powerStates) { - System.out.println(value.toString()); + LOGGER.log(LogLevel.VERBOSE, value::toString); } Assertions.assertEquals(27, powerStates.size()); } @@ -245,15 +247,13 @@ public void run() { /** * Tests ARM template deployments. * - * @throws IOException - * @throws ManagementException */ @DoNotRecord(skipInPlayback = true) // response contains token in hostpoolToken @Test - public void testDeployments() throws Exception { + public void testDeployments() { String testId = azureResourceManager.deployments().manager().resourceManager().internalContext().randomResourceName("", 8); PagedIterable deployments = azureResourceManager.deployments().list(); - System.out.println("Deployments: " + TestUtilities.getSize(deployments)); + LOGGER.log(LogLevel.VERBOSE, () -> "Deployments: " + TestUtilities.getSize(deployments)); Deployment deployment = azureResourceManager .deployments() @@ -263,7 +263,7 @@ public void testDeployments() throws Exception { .withParametersLink(PARAMETERS_URI, CONTENT_VERSION) .withMode(DeploymentMode.COMPLETE) .create(); - System.out.println("Created deployment: " + deployment.correlationId()); + LOGGER.log(LogLevel.VERBOSE, () -> "Created deployment: " + deployment.correlationId()); azureResourceManager.resourceGroups().beginDeleteByName("rg" + testId); } @@ -271,10 +271,9 @@ public void testDeployments() throws Exception { /** * Tests basic generic resources retrieval. * - * @throws Exception */ @Test - public void testGenericResources() throws Exception { + public void testGenericResources() { // Create some resources NetworkSecurityGroup nsg = azureResourceManager @@ -312,10 +311,9 @@ public void testGenericResources() throws Exception { * Tests management locks. * NOTE: This requires the service principal to have an Owner role on the subscription * - * @throws Exception */ @Test - public void testManagementLocks() throws Exception { + public void testManagementLocks() { // Prepare a VM final String password = ResourceManagerTestProxyTestBase.password(); final String rgName = generateRandomResourceName("rg", 15); @@ -487,14 +485,14 @@ public void testManagementLocks() throws Exception { Assertions.assertNotNull(locksGroup); int locksAllCount = TestUtilities.getSize(locksSubscription); - System.out.println("All locks: " + locksAllCount); + LOGGER.log(LogLevel.VERBOSE, () -> "All locks: " + locksAllCount); Assertions.assertTrue(6 <= locksAllCount); int locksGroupCount = TestUtilities.getSize(locksGroup); - System.out.println("Group locks: " + locksGroupCount); + LOGGER.log(LogLevel.VERBOSE, () -> "Group locks: " + locksGroupCount); Assertions.assertEquals(6, locksGroupCount); } catch (Exception ex) { - ex.printStackTrace(System.out); + LOGGER.log(LogLevel.VERBOSE, () -> "Error occurred", ex); } finally { if (resourceGroup != null) { if (lockGroup != null) { @@ -524,21 +522,19 @@ public void testManagementLocks() throws Exception { /** * Tests VM images. * - * @throws IOException - * @throws ManagementException */ @DoNotRecord(skipInPlayback = true) @Test - public void testVMImages() throws ManagementException, IOException { + public void testVMImages() throws ManagementException { PagedIterable publishers = azureResourceManager.virtualMachineImages().publishers().listByRegion(Region.US_WEST); Assertions.assertTrue(TestUtilities.getSize(publishers) > 0); for (VirtualMachinePublisher p : publishers.stream().limit(5).toArray(VirtualMachinePublisher[]::new)) { - System.out.println(String.format("Publisher name: %s, region: %s", p.name(), p.region())); + LOGGER.log(LogLevel.VERBOSE, () -> "Publisher name: " + p.name() + ", region: " + p.region()); for (VirtualMachineOffer o : p.offers().list().stream().limit(5).toArray(VirtualMachineOffer[]::new)) { - System.out.println(String.format("\tOffer name: %s", o.name())); + LOGGER.log(LogLevel.VERBOSE, () -> "\tOffer name: " + o.name()); for (VirtualMachineSku s : o.skus().list().stream().limit(5).toArray(VirtualMachineSku[]::new)) { - System.out.println(String.format("\t\tSku name: %s", s.name())); + LOGGER.log(LogLevel.VERBOSE, () -> "\t\tSku name: " + s.name()); } } } @@ -552,7 +548,6 @@ public void testVMImages() throws ManagementException, IOException { /** * Tests the network security group implementation. * - * @throws Exception */ @Test public void testNetworkSecurityGroups() throws Exception { @@ -562,7 +557,6 @@ public void testNetworkSecurityGroups() throws Exception { /** * Tests the inbound NAT rule support in load balancers. * - * @throws Exception */ @DoNotRecord(skipInPlayback = true) // TODO(weidxu) @Test @@ -574,7 +568,6 @@ public void testLoadBalancersNatRules() throws Exception { /** * Tests the inbound NAT pool support in load balancers. * - * @throws Exception */ @DoNotRecord(skipInPlayback = true) // TODO(weidxu) @Test @@ -586,7 +579,6 @@ public void testLoadBalancersNatPools() throws Exception { /** * Tests the minimum Internet-facing load balancer with a load balancing rule only * - * @throws Exception */ @Test public void testLoadBalancersInternetMinimum() throws Exception { @@ -597,7 +589,6 @@ public void testLoadBalancersInternetMinimum() throws Exception { /** * Tests the minimum Internet-facing load balancer with a NAT rule only * - * @throws Exception */ @Test public void testLoadBalancersNatOnly() throws Exception { @@ -608,7 +599,6 @@ public void testLoadBalancersNatOnly() throws Exception { /** * Tests the minimum internal load balancer. * - * @throws Exception */ @Test public void testLoadBalancersInternalMinimum() throws Exception { @@ -619,7 +609,6 @@ public void testLoadBalancersInternalMinimum() throws Exception { /** * Tests the internal load balancer with availability zone. * - * @throws Exception */ @Test @Disabled("Though valid scenario, NRP is failing") @@ -629,7 +618,7 @@ public void testLoadBalancersInternalWithAvailabilityZone() throws Exception { } @Test - public void testManagedDiskVMUpdate() throws Exception { + public void testManagedDiskVMUpdate() { ResourceManagerUtils.InternalRuntimeContext context = azureResourceManager.disks().manager().resourceManager().internalContext(); final String rgName = context.randomResourceName("rg", 13); final String linuxVM2Name = context.randomResourceName("vm" + "-", 10); @@ -661,7 +650,6 @@ public void testManagedDiskVMUpdate() throws Exception { /** * Tests the public IP address implementation. * - * @throws Exception */ @Test public void testPublicIPAddresses() throws Exception { @@ -671,7 +659,6 @@ public void testPublicIPAddresses() throws Exception { /** * Tests the public IP address implementation. * - * @throws Exception */ @Test public void testPublicIPPrefixes() throws Exception { @@ -681,7 +668,6 @@ public void testPublicIPPrefixes() throws Exception { /** * Tests the availability set implementation. * - * @throws Exception */ @Test public void testAvailabilitySets() throws Exception { @@ -691,7 +677,6 @@ public void testAvailabilitySets() throws Exception { /** * Tests the virtual network implementation. * - * @throws Exception */ @Test public void testNetworks() throws Exception { @@ -701,7 +686,6 @@ public void testNetworks() throws Exception { /** * Tests virtual network peering * - * @throws Exception */ @Test public void testNetworkWithAccessFromServiceToSubnet() throws Exception { @@ -711,7 +695,6 @@ public void testNetworkWithAccessFromServiceToSubnet() throws Exception { /** * Tests virtual network peering * - * @throws Exception */ @Test public void testNetworkPeerings() throws Exception { @@ -721,7 +704,6 @@ public void testNetworkPeerings() throws Exception { /** * Tests virtual network with DDoS protection plan * - * @throws Exception */ @Test public void testDdosAndVmProtection() throws Exception { @@ -731,7 +713,6 @@ public void testDdosAndVmProtection() throws Exception { /** * Tests updateTags for virtual network. * - * @throws Exception */ @Test public void testNetworkUpdateTags() throws Exception { @@ -741,7 +722,6 @@ public void testNetworkUpdateTags() throws Exception { /** * Tests route tables. * - * @throws Exception */ @Test public void testRouteTables() throws Exception { @@ -752,16 +732,16 @@ public void testRouteTables() throws Exception { @Test public void testRegions() { // Show built-in regions - System.out.println("Built-in regions list:"); + LOGGER.log(LogLevel.VERBOSE, () -> "Built-in regions list:"); int regionsCount = Region.values().size(); for (Region region : Region.values()) { - System.out.println("Name: " + region.name() + ", Label: " + region.label()); + LOGGER.log(LogLevel.VERBOSE, () -> "Name: " + region.name() + ", Label: " + region.label()); } // Look up built-in region Region region = Region.fromName("westus"); - Assertions.assertTrue(region == Region.US_WEST); + Assertions.assertSame(region, Region.US_WEST); // Add a region Region region2 = Region.fromName("madeUpRegion"); @@ -775,7 +755,6 @@ public void testRegions() { /** * Tests the network interface implementation. * - * @throws Exception */ @Test public void testNetworkInterfaces() throws Exception { @@ -785,7 +764,6 @@ public void testNetworkInterfaces() throws Exception { /** * Tests the network watcher implementation. * - * @throws Exception */ @Test public void testNetworkWatchers() throws Exception { @@ -859,7 +837,7 @@ public void testNetworkWatcherFunctions() throws Exception { .withRetentionPolicyDays(5) .withRetentionPolicyEnabled() .apply(); - Assertions.assertEquals(true, flowLogSettings.enabled()); + Assertions.assertTrue(flowLogSettings.enabled()); Assertions.assertEquals(5, flowLogSettings.retentionDays()); Assertions.assertEquals(storageAccount.id(), flowLogSettings.storageId()); @@ -945,7 +923,6 @@ public void testNetworkWatcherFunctions() throws Exception { /** * Tests the local network gateway implementation. * - * @throws Exception */ @DoNotRecord(skipInPlayback = true) // TODO(weidxu) @Test @@ -956,7 +933,6 @@ public void testLocalNetworkGateways() throws Exception { /** * Tests the express route circuit implementation. * - * @throws Exception */ @Test @Disabled("Failed to provision ExpressRoute circuit as the service provider does not have sufficient capacity at this location.") @@ -967,7 +943,6 @@ public void testExpressRouteCircuits() throws Exception { /** * Tests the express route circuit peerings implementation. * - * @throws Exception */ @Test @Disabled("Failed to provision ExpressRoute circuit as the service provider does not have sufficient capacity at this location.") @@ -979,7 +954,6 @@ public void testExpressRouteCircuitPeering() throws Exception { /** * Tests virtual machines. * - * @throws Exception */ @Test @Disabled("osDiskSize is returned as 127 instead of 128 - known service bug") @@ -992,7 +966,6 @@ public void testVirtualMachines() throws Exception { /** * Tests the virtual machine data disk implementation. * - * @throws Exception */ @Test public void testVirtualMachineDataDisk() throws Exception { @@ -1002,7 +975,6 @@ public void testVirtualMachineDataDisk() throws Exception { /** * Tests the virtual machine network interface implementation. * - * @throws Exception */ @Test public void testVirtualMachineNics() throws Exception { @@ -1012,7 +984,6 @@ public void testVirtualMachineNics() throws Exception { /** * Tests virtual machine support for SSH. * - * @throws Exception */ @Test public void testVirtualMachineSSh() throws Exception { @@ -1022,7 +993,6 @@ public void testVirtualMachineSSh() throws Exception { /** * Tests virtual machine sizes. * - * @throws Exception */ @Test public void testVirtualMachineSizes() throws Exception { @@ -1049,10 +1019,9 @@ public void testVirtualMachineSyncPoller() throws Exception { /** * Tests subscription listing. * - * @throws Exception */ @Test - public void listSubscriptions() throws Exception { + public void listSubscriptions() { Assertions.assertTrue(0 < TestUtilities.getSize(azureResourceManager.subscriptions().list())); Subscription subscription = azureResourceManager.getCurrentSubscription(); Assertions.assertNotNull(subscription); @@ -1064,10 +1033,9 @@ public void listSubscriptions() throws Exception { /** * Tests location listing. * - * @throws Exception */ @Test - public void listLocations() throws Exception { + public void listLocations() { Subscription subscription = azureResourceManager.getCurrentSubscription(); Assertions.assertNotNull(subscription); for (Location location : subscription.listLocations()) { @@ -1085,27 +1053,25 @@ public void listLocations() throws Exception { /** * Tests resource group listing. * - * @throws Exception */ @Test - public void listResourceGroups() throws Exception { + public void listResourceGroups() { int groupCount = TestUtilities.getSize(azureResourceManager.resourceGroups().list()); - System.out.println(String.format("Group count: %s", groupCount)); + LOGGER.log(LogLevel.VERBOSE, () -> "Group count: " + groupCount); Assertions.assertTrue(0 < groupCount); } /** * Tests storage account listing. * - * @throws Exception */ @Test - public void listStorageAccounts() throws Exception { + public void listStorageAccounts() { Assertions.assertTrue(0 < TestUtilities.getSize(azureResourceManager.storageAccounts().list())); } @Test - public void createStorageAccount() throws Exception { + public void createStorageAccount() { String storageAccountName = generateRandomResourceName("testsa", 12); StorageAccount storageAccount = azureResourceManager @@ -1175,7 +1141,7 @@ public void testContainerInstanceWithPublicIpAddressWithSystemAssignedMsi() thro } @Test - public void testContainerInstanceWithPublicIpAddressWithUserAssignedMsi() throws Exception { + public void testContainerInstanceWithPublicIpAddressWithUserAssignedMsi() { final String cgName = generateRandomResourceName("aci", 10); final String rgName = generateRandomResourceName("rgaci", 10); String identityName1 = generateRandomResourceName("msi-id", 15); @@ -1198,7 +1164,7 @@ public void testContainerInstanceWithPublicIpAddressWithUserAssignedMsi() throws .withExistingResourceGroup(rgName) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); - List dnsServers = new ArrayList(); + List dnsServers = new ArrayList<>(); dnsServers.add("dnsServer1"); ContainerGroup containerGroup = azureResourceManager @@ -1283,14 +1249,14 @@ public void testContainerInstanceWithPublicIpAddressWithUserAssignedMsi() throws List containerGroupList = azureResourceManager.containerGroups().listByResourceGroup(rgName).stream().collect(Collectors.toList()); - Assertions.assertTrue(containerGroupList.size() > 0); + Assertions.assertFalse(containerGroupList.isEmpty()); containerGroup.refresh(); Set containerGroupOperations = azureResourceManager.containerGroups().listOperations().stream().collect(Collectors.toSet()); // Number of supported operation can change hence don't assert with a predefined number. - Assertions.assertTrue(containerGroupOperations.size() > 0); + Assertions.assertFalse(containerGroupOperations.isEmpty()); } @Test @@ -1386,7 +1352,7 @@ public void generateMissingRegion() { } } - Assertions.assertTrue(sb.length() == 0, sb.toString()); + Assertions.assertEquals(0, sb.length(), sb.toString()); } private static Region findByLabelOrName(String labelOrName) { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/PrivateLinkTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/PrivateLinkTests.java index 882ce2ab1b5f..a5f66e2472fe 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/PrivateLinkTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/PrivateLinkTests.java @@ -12,8 +12,8 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.appservice.models.PricingTier; import com.azure.resourcemanager.appservice.models.RuntimeStack; import com.azure.resourcemanager.appservice.models.WebApp; @@ -50,17 +50,14 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; public class PrivateLinkTests extends ResourceManagerTestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(PrivateLinkTests.class); private AzureResourceManager azureResourceManager; private String rgName; @@ -122,7 +119,7 @@ public void testPrivateEndpoint() { // String pecName2 = generateRandomResourceName("pec", 10); String saDomainName = saName + ".blob.core.windows.net"; - System.out.println("storage account domain name: " + saDomainName); + LOGGER.log(LogLevel.VERBOSE, () -> "storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) @@ -228,7 +225,7 @@ public void testPrivateEndpoint() { Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); - System.out.println("storage account private ip: " + saPrivateIp); + LOGGER.log(LogLevel.VERBOSE, () -> "storage account private ip: " + saPrivateIp); // verify list List privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); @@ -248,7 +245,7 @@ public void testPrivateEndpointE2E() { String vmName = generateRandomResourceName("vm", 10); String saDomainName = saName + ".blob.core.windows.net"; - System.out.println("storage account domain name: " + saDomainName); + LOGGER.log(LogLevel.VERBOSE, () -> "storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) @@ -289,7 +286,7 @@ public void testPrivateEndpointE2E() { Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); - System.out.println("storage account private ip: " + saPrivateIp); + LOGGER.log(LogLevel.VERBOSE, () -> "storage account private ip: " + saPrivateIp); VirtualMachine virtualMachine = null; if (validateOnVirtualMachine) { @@ -310,7 +307,7 @@ public void testPrivateEndpointE2E() { // verify private endpoint not yet works RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { - System.out.println(status.message()); + LOGGER.log(LogLevel.VERBOSE, () -> status.message()); } Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } @@ -335,7 +332,7 @@ public void testPrivateEndpointE2E() { // verify private endpoint works RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { - System.out.println(status.message()); + LOGGER.log(LogLevel.VERBOSE, () -> status.message()); } Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } @@ -560,11 +557,4 @@ private parseAuthFile(String authFilename) throws Exception { - String content = new String(Files.readAllBytes(new File(authFilename).toPath()), StandardCharsets.UTF_8).trim(); - HashMap auth = new HashMap<>(); - auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); - return auth; - } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestApplicationGateway.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestApplicationGateway.java index 7bc709c81960..190280a546eb 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestApplicationGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestApplicationGateway.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.ApplicationGateway; import com.azure.resourcemanager.network.models.ApplicationGatewayAuthenticationCertificate; import com.azure.resourcemanager.network.models.ApplicationGatewayBackend; @@ -39,6 +41,8 @@ /** Test of application gateway management. */ public class TestApplicationGateway { + private static final ClientLogger LOGGER = new ClientLogger(TestApplicationGateway.class); + String testId = ""; static final Region REGION = Region.US_WEST; String groupName = ""; @@ -381,9 +385,8 @@ public class PrivateComplex extends TestTemplate "Uncaught exception", ex); } }; @@ -519,7 +522,7 @@ public void run() { .withInstanceCount(2) .create(); } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Error creating application gateway", e); } } }); @@ -843,9 +846,8 @@ public class PublicComplex extends TestTemplate "Uncaught exception", ex); } }; @@ -962,7 +964,7 @@ public void run() { .withHttp2() .create(); } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Uncaught exception", e); } } }); @@ -978,7 +980,7 @@ public void run() { ApplicationGateway appGateway = resources.getById(resourceId); Assertions.assertNotNull(appGateway); Assertions.assertTrue(appGateway.isPublic()); - Assertions.assertTrue(!appGateway.isPrivate()); + Assertions.assertFalse(appGateway.isPrivate()); Assertions.assertEquals(ApplicationGatewayTier.STANDARD, appGateway.tier()); Assertions.assertEquals(ApplicationGatewaySkuName.STANDARD_MEDIUM, appGateway.size()); Assertions.assertEquals(2, appGateway.instanceCount()); @@ -997,7 +999,7 @@ public void run() { Assertions.assertEquals(0, appGateway.privateFrontends().size()); ApplicationGatewayFrontend frontend = appGateway.publicFrontends().values().iterator().next(); Assertions.assertTrue(frontend.isPublic()); - Assertions.assertTrue(!frontend.isPrivate()); + Assertions.assertFalse(frontend.isPrivate()); // Verify listeners Assertions.assertEquals(3, appGateway.listeners().size()); @@ -1099,7 +1101,7 @@ public void run() { Assertions.assertEquals(2, appGateway.disabledSslProtocols().size()); Assertions.assertTrue(appGateway.disabledSslProtocols().contains(ApplicationGatewaySslProtocol.TLSV1_0)); Assertions.assertTrue(appGateway.disabledSslProtocols().contains(ApplicationGatewaySslProtocol.TLSV1_1)); - Assertions.assertTrue(!appGateway.disabledSslProtocols().contains(ApplicationGatewaySslProtocol.TLSV1_2)); + Assertions.assertFalse(appGateway.disabledSslProtocols().contains(ApplicationGatewaySslProtocol.TLSV1_2)); return appGateway; } @@ -1148,8 +1150,8 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro // Get the resource created so far Assertions.assertTrue(resource.tags().containsKey("tag1")); - Assertions.assertTrue(resource.size().equals(ApplicationGatewaySkuName.STANDARD_SMALL)); - Assertions.assertTrue(resource.instanceCount() == 1); + Assertions.assertEquals(resource.size(), ApplicationGatewaySkuName.STANDARD_SMALL); + Assertions.assertEquals(1, resource.instanceCount()); Assertions.assertFalse(resource.isHttp2Enabled()); // Verify listeners @@ -1157,10 +1159,10 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro Assertions.assertTrue("www.contoso.com".equalsIgnoreCase(listener.hostname())); // Verify request routing rules - Assertions.assertTrue(resource.requestRoutingRules().size() == rulesCount - 1); - Assertions.assertTrue(!resource.requestRoutingRules().containsKey("rule9000")); + Assertions.assertEquals(resource.requestRoutingRules().size(), rulesCount - 1); + Assertions.assertFalse(resource.requestRoutingRules().containsKey("rule9000")); ApplicationGatewayRequestRoutingRule rule = resource.requestRoutingRules().get("rule443"); - Assertions.assertTrue(rule != null); + Assertions.assertNotNull(rule); Assertions.assertTrue("listener1".equalsIgnoreCase(rule.listener().name())); // Verify probes @@ -1233,7 +1235,7 @@ public void run() { .attach() .create(); } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Error occurred", e); } } }); @@ -1246,48 +1248,48 @@ public void run() { // Get the resource as created so far String resourceId = createResourceId(resources.manager().subscriptionId()); ApplicationGateway appGateway = resources.manager().applicationGateways().getById(resourceId); - Assertions.assertTrue(appGateway != null); - Assertions.assertTrue(ApplicationGatewayTier.STANDARD.equals(appGateway.tier())); - Assertions.assertTrue(ApplicationGatewaySkuName.STANDARD_SMALL.equals(appGateway.size())); - Assertions.assertTrue(appGateway.instanceCount() == 1); + Assertions.assertNotNull(appGateway); + Assertions.assertEquals(ApplicationGatewayTier.STANDARD, appGateway.tier()); + Assertions.assertEquals(ApplicationGatewaySkuName.STANDARD_SMALL, appGateway.size()); + Assertions.assertEquals(1, appGateway.instanceCount()); // Verify frontend ports - Assertions.assertTrue(appGateway.frontendPorts().size() == 1); - Assertions.assertTrue(appGateway.frontendPortNameFromNumber(443) != null); + Assertions.assertEquals(1, appGateway.frontendPorts().size()); + Assertions.assertNotNull(appGateway.frontendPortNameFromNumber(443)); // Verify frontends - Assertions.assertTrue(!appGateway.isPrivate()); + Assertions.assertFalse(appGateway.isPrivate()); Assertions.assertTrue(appGateway.isPublic()); - Assertions.assertTrue(appGateway.frontends().size() == 1); + Assertions.assertEquals(1, appGateway.frontends().size()); // Verify listeners - Assertions.assertTrue(appGateway.listeners().size() == 1); - Assertions.assertTrue(appGateway.listenerByPortNumber(443) != null); + Assertions.assertEquals(1, appGateway.listeners().size()); + Assertions.assertNotNull(appGateway.listenerByPortNumber(443)); // Verify backends - Assertions.assertTrue(appGateway.backends().size() == 1); + Assertions.assertEquals(1, appGateway.backends().size()); // Verify backend HTTP configs - Assertions.assertTrue(appGateway.backendHttpConfigurations().size() == 1); + Assertions.assertEquals(1, appGateway.backendHttpConfigurations().size()); // Verify rules - Assertions.assertTrue(appGateway.requestRoutingRules().size() == 1); + Assertions.assertEquals(1, appGateway.requestRoutingRules().size()); ApplicationGatewayRequestRoutingRule rule = appGateway.requestRoutingRules().get("rule1"); - Assertions.assertTrue(rule != null); - Assertions.assertTrue(rule.frontendPort() == 443); - Assertions.assertTrue(ApplicationGatewayProtocol.HTTPS.equals(rule.frontendProtocol())); - Assertions.assertTrue(rule.listener() != null); - Assertions.assertTrue(rule.listener().frontend() != null); + Assertions.assertNotNull(rule); + Assertions.assertEquals(443, rule.frontendPort()); + Assertions.assertEquals(ApplicationGatewayProtocol.HTTPS, rule.frontendProtocol()); + Assertions.assertNotNull(rule.listener()); + Assertions.assertNotNull(rule.listener().frontend()); Assertions.assertTrue(rule.listener().frontend().isPublic()); - Assertions.assertTrue(!rule.listener().frontend().isPrivate()); - Assertions.assertTrue(rule.backendPort() == 8080); - Assertions.assertTrue(rule.sslCertificate() != null); - Assertions.assertTrue(rule.backendAddresses().size() == 2); + Assertions.assertFalse(rule.listener().frontend().isPrivate()); + Assertions.assertEquals(8080, rule.backendPort()); + Assertions.assertNotNull(rule.sslCertificate()); + Assertions.assertEquals(2, rule.backendAddresses().size()); Assertions.assertTrue(rule.backend().containsIPAddress("11.1.1.1")); Assertions.assertTrue(rule.backend().containsIPAddress("11.1.1.2")); // Verify certificates - Assertions.assertTrue(appGateway.sslCertificates().size() == 1); + Assertions.assertEquals(1, appGateway.sslCertificates().size()); return appGateway; } @@ -1324,47 +1326,47 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro Assertions.assertTrue(resource.tags().containsKey("tag1")); Assertions.assertTrue(resource.tags().containsKey("tag2")); - Assertions.assertTrue(ApplicationGatewaySkuName.STANDARD_MEDIUM.equals(resource.size())); - Assertions.assertTrue(resource.instanceCount() == 2); + Assertions.assertEquals(ApplicationGatewaySkuName.STANDARD_MEDIUM, resource.size()); + Assertions.assertEquals(2, resource.instanceCount()); // Verify frontend ports - Assertions.assertTrue(resource.frontendPorts().size() == 2); - Assertions.assertTrue(resource.frontendPortNameFromNumber(80) != null); + Assertions.assertEquals(2, resource.frontendPorts().size()); + Assertions.assertNotNull(resource.frontendPortNameFromNumber(80)); // Verify listeners - Assertions.assertTrue(resource.listeners().size() == 2); + Assertions.assertEquals(2, resource.listeners().size()); ApplicationGatewayListener listener = resource.listeners().get("listener2"); - Assertions.assertTrue(listener != null); - Assertions.assertTrue(!listener.frontend().isPrivate()); + Assertions.assertNotNull(listener); + Assertions.assertFalse(listener.frontend().isPrivate()); Assertions.assertTrue(listener.frontend().isPublic()); - Assertions.assertTrue(listener.frontendPortNumber() == 80); - Assertions.assertTrue(ApplicationGatewayProtocol.HTTP.equals(listener.protocol())); - Assertions.assertTrue(listener.sslCertificate() == null); + Assertions.assertEquals(80, listener.frontendPortNumber()); + Assertions.assertEquals(ApplicationGatewayProtocol.HTTP, listener.protocol()); + Assertions.assertNull(listener.sslCertificate()); // Verify backends - Assertions.assertTrue(resource.backends().size() == 2); + Assertions.assertEquals(2, resource.backends().size()); ApplicationGatewayBackend backend = resource.backends().get("backend2"); - Assertions.assertTrue(backend != null); - Assertions.assertTrue(backend.addresses().size() == 1); + Assertions.assertNotNull(backend); + Assertions.assertEquals(1, backend.addresses().size()); Assertions.assertTrue(backend.containsIPAddress("11.1.1.3")); // Verify HTTP configs - Assertions.assertTrue(resource.backendHttpConfigurations().size() == 2); + Assertions.assertEquals(2, resource.backendHttpConfigurations().size()); ApplicationGatewayBackendHttpConfiguration config = resource.backendHttpConfigurations().get("config2"); - Assertions.assertTrue(config != null); + Assertions.assertNotNull(config); Assertions.assertTrue(config.cookieBasedAffinity()); - Assertions.assertTrue(config.port() == 8081); - Assertions.assertTrue(config.requestTimeout() == 33); + Assertions.assertEquals(8081, config.port()); + Assertions.assertEquals(33, config.requestTimeout()); // Verify request routing rules - Assertions.assertTrue(resource.requestRoutingRules().size() == 2); + Assertions.assertEquals(2, resource.requestRoutingRules().size()); ApplicationGatewayRequestRoutingRule rule = resource.requestRoutingRules().get("rule2"); - Assertions.assertTrue(rule != null); - Assertions.assertTrue(rule.listener() != null); - Assertions.assertTrue("listener2".equals(rule.listener().name())); - Assertions.assertTrue(rule.backendHttpConfiguration() != null); + Assertions.assertNotNull(rule); + Assertions.assertNotNull(rule.listener()); + Assertions.assertEquals("listener2", rule.listener().name()); + Assertions.assertNotNull(rule.backendHttpConfiguration()); Assertions.assertTrue("config2".equalsIgnoreCase(rule.backendHttpConfiguration().name())); - Assertions.assertTrue(rule.backend() != null); + Assertions.assertNotNull(rule.backend()); Assertions.assertTrue("backend2".equalsIgnoreCase(rule.backend().name())); return resource; @@ -1372,10 +1374,10 @@ public ApplicationGateway updateResource(final ApplicationGateway resource) thro } // Create VNet for the app gateway - private Map ensurePIPs(PublicIpAddresses pips) throws Exception { + private Map ensurePIPs(PublicIpAddresses pips) { List> creatablePips = new ArrayList<>(); - for (int i = 0; i < pipNames.length; i++) { - creatablePips.add(pips.define(pipNames[i]).withRegion(REGION).withNewResourceGroup(groupName)); + for (String pipName : pipNames) { + creatablePips.add(pips.define(pipName).withRegion(REGION).withNewResourceGroup(groupName)); } return pips.create(creatablePips); @@ -1497,7 +1499,7 @@ static void printAppGateway(ApplicationGateway resource) { .append(httpConfig.path()); if (httpConfig.probe() != null) { - info.append("\n\t\t\tProbe: " + httpConfig.probe().name()); + info.append("\n\t\t\tProbe: ").append(httpConfig.probe().name()); } info.append("\n\t\tIs probe enabled? ").append(httpConfig.isProbeEnabled()); } @@ -1653,6 +1655,6 @@ static void printAppGateway(ApplicationGateway resource) { info.append(listener.name()); } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, () -> info.toString()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCdn.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCdn.java index 79d98ea846f2..e896eea3d65c 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCdn.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestCdn.java @@ -4,6 +4,8 @@ package com.azure.resourcemanager; import com.azure.core.management.Region; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.cdn.models.CdnEndpoint; import com.azure.resourcemanager.cdn.models.CdnProfile; import com.azure.resourcemanager.cdn.models.CdnProfiles; @@ -24,6 +26,8 @@ * Test of CDN management. */ public class TestCdn extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestCdn.class); + @Override public CdnProfile createResource(CdnProfiles profiles) throws Exception { final Region region = Region.US_EAST; @@ -50,7 +54,7 @@ public CdnProfile createResource(CdnProfiles profiles) throws Exception { .attach() .create(); - Assertions.assertTrue(cdnProfile.sku().name().equals(SkuName.STANDARD_VERIZON)); + Assertions.assertEquals(cdnProfile.sku().name(), SkuName.STANDARD_VERIZON); Assertions.assertNotNull(cdnProfile.endpoints()); Assertions.assertEquals(1, cdnProfile.endpoints().size()); CdnEndpoint endpoint = cdnProfile.endpoints().get(cdnEndpointName); @@ -165,6 +169,6 @@ public void print(CdnProfile profile) { } } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java index 435a4212f531..f5349b048003 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.authorization.models.BuiltInRole; import com.azure.resourcemanager.containerinstance.models.Container; import com.azure.resourcemanager.containerinstance.models.ContainerGroup; @@ -24,6 +26,8 @@ public class TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI extends TestTemplate { + private static final ClientLogger LOGGER + = new ClientLogger(TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.class); @Override public ContainerGroup createResource(ContainerGroups containerGroups) throws Exception { @@ -104,13 +108,13 @@ public ContainerGroup createResource(ContainerGroups containerGroups) throws Exc List containerGroupList = containerGroups.listByResourceGroup(rgName).stream().collect(Collectors.toList()); - Assertions.assertTrue(containerGroupList.size() > 0); + Assertions.assertFalse(containerGroupList.isEmpty()); containerGroup.refresh(); Set containerGroupOperations = containerGroups.listOperations().stream().collect(Collectors.toSet()); // Number of supported operation can change hence don't assert with a predefined number. - Assertions.assertTrue(containerGroupOperations.size() > 0); + Assertions.assertFalse(containerGroupOperations.isEmpty()); return containerGroup; } @@ -211,6 +215,6 @@ public void print(ContainerGroup resource) { } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestDns.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestDns.java index 21b959dda73b..e6ea71a52362 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestDns.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestDns.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.dns.models.ARecordSet; import com.azure.resourcemanager.dns.models.AaaaRecordSet; import com.azure.resourcemanager.dns.models.CnameRecordSet; @@ -34,6 +36,8 @@ import static com.azure.resourcemanager.dns.models.RecordType.TXT; public class TestDns extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestDns.class); + @Override public DnsZone createResource(DnsZones dnsZones) throws Exception { final Region region = Region.US_EAST; @@ -92,8 +96,8 @@ public DnsZone createResource(DnsZones dnsZones) throws Exception { // Check Dns zone properties Assertions.assertTrue(dnsZone.name().startsWith(topLevelDomain)); - Assertions.assertTrue(dnsZone.nameServers().size() > 0); // Default '@' name servers - Assertions.assertTrue(dnsZone.tags().size() == 2); + Assertions.assertFalse(dnsZone.nameServers().isEmpty()); // Default '@' name servers + Assertions.assertEquals(2, dnsZone.tags().size()); // Check SOA record - external child resource (created by default) SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); @@ -106,23 +110,23 @@ public DnsZone createResource(DnsZones dnsZones) throws Exception { // Check A records PagedIterable aRecordSets = dnsZone.aRecordSets().list(); - Assertions.assertTrue(aRecordSets.stream().count() == 1); - Assertions.assertTrue(aRecordSets.iterator().next().timeToLive() == 7200); + Assertions.assertEquals(1, aRecordSets.stream().count()); + Assertions.assertEquals(7200, aRecordSets.iterator().next().timeToLive()); // Check AAAA records PagedIterable aaaaRecordSets = dnsZone.aaaaRecordSets().list(); - Assertions.assertTrue(aaaaRecordSets.stream().count() == 1); + Assertions.assertEquals(1, aaaaRecordSets.stream().count()); Assertions.assertTrue(aaaaRecordSets.iterator().next().name().startsWith("www")); - Assertions.assertTrue(aaaaRecordSets.iterator().next().ipv6Addresses().size() == 2); + Assertions.assertEquals(2, aaaaRecordSets.iterator().next().ipv6Addresses().size()); // Check MX records PagedIterable mxRecordSets = dnsZone.mxRecordSets().list(); - Assertions.assertTrue(mxRecordSets.stream().count() == 1); + Assertions.assertEquals(1, mxRecordSets.stream().count()); MxRecordSet mxRecordSet = mxRecordSets.iterator().next(); Assertions.assertNotNull(mxRecordSet); Assertions.assertTrue(mxRecordSet.name().startsWith("email")); - Assertions.assertTrue(mxRecordSet.metadata().size() == 2); - Assertions.assertTrue(mxRecordSet.records().size() == 2); + Assertions.assertEquals(2, mxRecordSet.metadata().size()); + Assertions.assertEquals(2, mxRecordSet.records().size()); for (MxRecord mxRecord : mxRecordSet.records()) { Assertions.assertTrue(mxRecord.exchange().startsWith("mail.contoso-mail-exchange1.com") || mxRecord.exchange().startsWith("mail.contoso-mail-exchange2.com")); @@ -132,23 +136,23 @@ public DnsZone createResource(DnsZones dnsZones) throws Exception { // Check NS records PagedIterable nsRecordSets = dnsZone.nsRecordSets().list(); - Assertions.assertTrue(nsRecordSets.stream().count() == 2); // One created above with name 'partners' + the default '@' + Assertions.assertEquals(2, nsRecordSets.stream().count()); // One created above with name 'partners' + the default '@' // Check TXT records PagedIterable txtRecordSets = dnsZone.txtRecordSets().list(); - Assertions.assertTrue(txtRecordSets.stream().count() == 2); + Assertions.assertEquals(2, txtRecordSets.stream().count()); // Check SRV records PagedIterable srvRecordSets = dnsZone.srvRecordSets().list(); - Assertions.assertTrue(srvRecordSets.stream().count() == 1); + Assertions.assertEquals(1, srvRecordSets.stream().count()); // Check PTR records PagedIterable ptrRecordSets = dnsZone.ptrRecordSets().list(); - Assertions.assertTrue(ptrRecordSets.stream().count() == 2); + Assertions.assertEquals(2, ptrRecordSets.stream().count()); // Check CNAME records PagedIterable cnameRecordSets = dnsZone.cNameRecordSets().list(); - Assertions.assertTrue(cnameRecordSets.stream().count() == 2); + Assertions.assertEquals(2, cnameRecordSets.stream().count()); // Check Generic record set listing PagedIterable recordSets = dnsZone.listRecordSets(); @@ -214,15 +218,15 @@ public DnsZone createResource(DnsZones dnsZones) throws Exception { Assertions.assertNotNull(recordSet); } } - Assertions.assertTrue(typeToCount.get(SOA) == 1); - Assertions.assertTrue(typeToCount.get(RecordType.A) == 1); - Assertions.assertTrue(typeToCount.get(AAAA) == 1); - Assertions.assertTrue(typeToCount.get(MX) == 1); - Assertions.assertTrue(typeToCount.get(NS) == 2); - Assertions.assertTrue(typeToCount.get(TXT) == 2); - Assertions.assertTrue(typeToCount.get(SRV) == 1); - Assertions.assertTrue(typeToCount.get(PTR) == 2); - Assertions.assertTrue(typeToCount.get(RecordType.CNAME) == 2); + Assertions.assertEquals(1, (int) typeToCount.get(SOA)); + Assertions.assertEquals(1, (int) typeToCount.get(RecordType.A)); + Assertions.assertEquals(1, (int) typeToCount.get(AAAA)); + Assertions.assertEquals(1, (int) typeToCount.get(MX)); + Assertions.assertEquals(2, (int) typeToCount.get(NS)); + Assertions.assertEquals(2, (int) typeToCount.get(TXT)); + Assertions.assertEquals(1, (int) typeToCount.get(SRV)); + Assertions.assertEquals(2, (int) typeToCount.get(PTR)); + Assertions.assertEquals(2, (int) typeToCount.get(RecordType.CNAME)); return dnsZone; } @@ -269,7 +273,7 @@ public DnsZone updateResource(DnsZone dnsZone) throws Exception { // Check NS records PagedIterable nsRecordSets = dnsZone.nsRecordSets().list(); - Assertions.assertTrue(nsRecordSets.stream().count() == 2); // One created above with name 'partners' + the default '@' + Assertions.assertEquals(2, nsRecordSets.stream().count()); // One created above with name 'partners' + the default '@' for (NsRecordSet nsRecordSet : nsRecordSets) { Assertions.assertTrue(nsRecordSet.name().startsWith("partners") || nsRecordSet.name().startsWith("@")); if (nsRecordSet.name().startsWith("partners")) { @@ -291,9 +295,9 @@ public DnsZone updateResource(DnsZone dnsZone) throws Exception { // Check SRV records PagedIterable srvRecordSets = dnsZone.srvRecordSets().list(); - Assertions.assertTrue(srvRecordSets.stream().count() == 1); + Assertions.assertEquals(1, srvRecordSets.stream().count()); SrvRecordSet srvRecordSet = srvRecordSets.iterator().next(); - Assertions.assertTrue(srvRecordSet.records().size() == 4); + Assertions.assertEquals(4, srvRecordSet.records().size()); for (SrvRecord srvRecord : srvRecordSet.records()) { Assertions.assertFalse(srvRecord.target().startsWith("bigbox.contoso-service.com")); } @@ -304,11 +308,11 @@ public DnsZone updateResource(DnsZone dnsZone) throws Exception { SoaRecord soaRecord = soaRecordSet.record(); Assertions.assertNotNull(soaRecord); Assertions.assertEquals(soaRecord.minimumTtl(), Long.valueOf(600)); - Assertions.assertTrue(soaRecordSet.timeToLive() == 7200); + Assertions.assertEquals(7200, soaRecordSet.timeToLive()); // Check MX records PagedIterable mxRecordSets = dnsZone.mxRecordSets().list(); - Assertions.assertTrue(mxRecordSets.stream().count() == 2); + Assertions.assertEquals(2, mxRecordSets.stream().count()); dnsZone.update() .updateMXRecordSet("email") @@ -320,11 +324,11 @@ public DnsZone updateResource(DnsZone dnsZone) throws Exception { .withTag("d", "dd") .apply(); - Assertions.assertTrue(dnsZone.tags().size() == 3); + Assertions.assertEquals(3, dnsZone.tags().size()); // Check "mail" MX record MxRecordSet mxRecordSet = dnsZone.mxRecordSets().getByName("email"); - Assertions.assertTrue(mxRecordSet.records().size() == 1); - Assertions.assertTrue(mxRecordSet.metadata().size() == 3); + Assertions.assertEquals(1, mxRecordSet.records().size()); + Assertions.assertEquals(3, mxRecordSet.metadata().size()); Assertions.assertTrue(mxRecordSet.records().get(0).exchange().startsWith("mail.contoso-mail-exchange1.com")); return dnsZone; @@ -452,11 +456,11 @@ public void print(DnsZone dnsZone) { .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { - if (txtRecord.value().size() > 0) { + if (!txtRecord.value().isEmpty()) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, () -> info.toString()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestExpressRouteCircuit.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestExpressRouteCircuit.java index 8226a805d24f..6c0edc1c2499 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestExpressRouteCircuit.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestExpressRouteCircuit.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.ExpressRouteCircuit; import com.azure.resourcemanager.network.models.ExpressRouteCircuitSkuType; import com.azure.resourcemanager.network.models.ExpressRouteCircuits; @@ -13,6 +15,8 @@ /** Tests Express Route Circuit. */ public class TestExpressRouteCircuit { + private static final ClientLogger LOGGER = new ClientLogger(TestExpressRouteCircuit.class); + private String testId = ""; private static final Region REGION = Region.ASIA_SOUTHEAST; private String circuitName; @@ -54,7 +58,7 @@ public ExpressRouteCircuit updateResource(ExpressRouteCircuit resource) throws E .apply(); resource.refresh(); Assertions.assertTrue(resource.tags().containsKey("tag2")); - Assertions.assertTrue(!resource.tags().containsKey("tag1")); + Assertions.assertFalse(resource.tags().containsKey("tag1")); Assertions.assertEquals(Integer.valueOf(200), resource.serviceProviderProperties().bandwidthInMbps()); Assertions.assertEquals(ExpressRouteCircuitSkuType.PREMIUM_UNLIMITEDDATA, resource.sku()); @@ -131,18 +135,8 @@ public void print(ExpressRouteCircuit resource) { } private static void printExpressRouteCircuit(ExpressRouteCircuit resource) { - StringBuilder info = new StringBuilder(); - info - .append("Express Route Circuit: ") - .append(resource.id()) - .append("\n\tName: ") - .append(resource.name()) - .append("\n\tResource group: ") - .append(resource.resourceGroupName()) - .append("\n\tRegion: ") - .append(resource.regionName()) - .append("\n\tTags: ") - .append(resource.tags()); - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, () -> "Express Route Circuit: " + resource.id() + "\n\tName: " + resource.name() + + "\n\tResource group: " + resource.resourceGroupName() + "\n\tRegion: " + resource.regionName() + + "\n\tTags: " + resource.tags()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLoadBalancer.java index 867de9bf56c5..5683b621229c 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLoadBalancer.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.compute.models.AvailabilitySet; import com.azure.resourcemanager.compute.models.AvailabilitySetSkuTypes; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -45,6 +47,8 @@ /** Test of load balancer management. */ public class TestLoadBalancer { + private static final ClientLogger LOGGER = new ClientLogger(TestLoadBalancer.class); + String testId = ""; Region region = Region.US_WEST; String groupName = ""; @@ -367,10 +371,10 @@ public LoadBalancer updateResource(LoadBalancer resource) throws Exception { // Remove the NIC associations nic1.update().withoutLoadBalancerBackends().withoutLoadBalancerInboundNatRules().apply(); - Assertions.assertTrue(nic1.primaryIPConfiguration().listAssociatedLoadBalancerBackends().size() == 0); + Assertions.assertEquals(0, nic1.primaryIPConfiguration().listAssociatedLoadBalancerBackends().size()); nic2.update().withoutLoadBalancerBackends().withoutLoadBalancerInboundNatRules().apply(); - Assertions.assertTrue(nic2.primaryIPConfiguration().listAssociatedLoadBalancerBackends().size() == 0); + Assertions.assertEquals(0, nic2.primaryIPConfiguration().listAssociatedLoadBalancerBackends().size()); // Update the load balancer ensurePIPs(resource.manager().publicIpAddresses()); @@ -542,7 +546,7 @@ public LoadBalancer updateResource(LoadBalancer resource) throws Exception { // Verify backends Assertions.assertTrue(resource.backends().containsKey("backend2")); - Assertions.assertTrue(!resource.backends().containsKey(backend.name())); + Assertions.assertFalse(resource.backends().containsKey(backend.name())); // Verify NAT rules Assertions.assertTrue(resource.inboundNatRules().isEmpty()); @@ -705,7 +709,7 @@ public LoadBalancer updateResource(LoadBalancer resource) throws Exception { // Verify backends Assertions.assertEquals(1, resource.backends().size()); Assertions.assertTrue(resource.backends().containsKey("backend2")); - Assertions.assertTrue(!resource.backends().containsKey(backend.name())); + Assertions.assertFalse(resource.backends().containsKey(backend.name())); // Verify load balancing rules lbRule = resource.loadBalancingRules().get("lbrule1"); @@ -1023,23 +1027,18 @@ public LoadBalancer updateResource(LoadBalancer resource) throws Exception { } // Create VNet for the LB - private Map ensurePIPs(PublicIpAddresses pips) throws Exception { + private Map ensurePIPs(PublicIpAddresses pips) { List> creatablePips = new ArrayList<>(); - for (int i = 0; i < pipNames.length; i++) { - creatablePips - .add( - pips - .define(pipNames[i]) - .withRegion(region) - .withNewResourceGroup(groupName) - .withLeafDomainLabel(pipNames[i])); + for (String pipName : pipNames) { + creatablePips.add( + pips.define(pipName).withRegion(region).withNewResourceGroup(groupName).withLeafDomainLabel(pipName)); } return pips.create(creatablePips); } // Ensure VMs for the LB - private VirtualMachine[] ensureVMs(Networks networks, ComputeManager computeManager, int count) throws Exception { + private VirtualMachine[] ensureVMs(Networks networks, ComputeManager computeManager, int count) { // Create a network for the VMs Network network = networks @@ -1311,9 +1310,9 @@ static void printLB(LoadBalancer resource) { // Show assigned load balancing rules info .append("\n\t\t\tReferenced load balancing rules: ") - .append(new ArrayList(backend.loadBalancingRules().keySet())); + .append(new ArrayList<>(backend.loadBalancingRules().keySet())); } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLocalNetworkGateway.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLocalNetworkGateway.java index c8bf6a47f705..952f5b94bd8a 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLocalNetworkGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestLocalNetworkGateway.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.LocalNetworkGateway; import com.azure.resourcemanager.network.models.LocalNetworkGateways; import com.azure.core.management.Region; @@ -10,6 +12,8 @@ /** Tests Local Network Gateway. */ public class TestLocalNetworkGateway extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestLocalNetworkGateway.class); + private String testId = ""; private static final Region REGION = Region.US_NORTH_CENTRAL; private String groupName; @@ -51,7 +55,7 @@ public LocalNetworkGateway updateResource(LocalNetworkGateway gateway) throws Ex Assertions.assertFalse(gateway.addressSpaces().contains("192.168.3.0/24")); Assertions.assertEquals("40.71.184.216", gateway.ipAddress()); Assertions.assertTrue(gateway.tags().containsKey("tag2")); - Assertions.assertTrue(!gateway.tags().containsKey("tag1")); + Assertions.assertFalse(gateway.tags().containsKey("tag1")); gateway.updateTags().withoutTag("tag2").withTag("tag3", "value3").applyTags(); Assertions.assertFalse(gateway.tags().containsKey("tag2")); Assertions.assertEquals("value3", gateway.tags().get("tag3")); @@ -75,10 +79,10 @@ public void print(LocalNetworkGateway gateway) { if (!gateway.addressSpaces().isEmpty()) { info.append("\n\tAddress spaces:"); for (String addressSpace : gateway.addressSpaces()) { - info.append("\n\t\t" + addressSpace); + info.append("\n\t\t").append(addressSpace); } } info.append("\n\tTags: ").append(gateway.tags()); - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNSG.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNSG.java index 912d39298b15..233d88f9c0ac 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNSG.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNSG.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.ApplicationSecurityGroup; import com.azure.resourcemanager.network.models.NetworkInterface; import com.azure.resourcemanager.network.models.NetworkSecurityGroup; @@ -17,6 +19,8 @@ /** Test for network security group CRUD. */ public class TestNSG extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestNSG.class); + @Override public NetworkSecurityGroup createResource(NetworkSecurityGroups nsgs) throws Exception { String postFix = nsgs.manager().resourceManager().internalContext().randomResourceName("", 8); @@ -61,7 +65,7 @@ public NetworkSecurityGroup createResource(NetworkSecurityGroups nsgs) throws Ex .createAsync(); resourceStream - .doOnSuccess((_ignore) -> System.out.print("completed")); + .doOnSuccess((_ignore) -> LOGGER.log(LogLevel.VERBOSE, () -> "completed")); NetworkSecurityGroup nsg = resourceStream.block(); @@ -80,8 +84,8 @@ public NetworkSecurityGroup createResource(NetworkSecurityGroups nsgs) throws Ex nsg.refresh(); // Verify - Assertions.assertTrue(nsg.region().equals(region)); - Assertions.assertTrue(nsg.securityRules().size() == 2); + Assertions.assertEquals(nsg.region(), region); + Assertions.assertEquals(2, nsg.securityRules().size()); // Confirm NIC association Assertions.assertEquals(1, nsg.networkInterfaceIds().size()); @@ -191,7 +195,7 @@ public static void printNSG(NetworkSecurityGroup resource) { // Output associated subnets info.append("\n\tAssociated subnets: "); List subnets = resource.listAssociatedSubnets(); - if (subnets == null || subnets.size() == 0) { + if (subnets == null || subnets.isEmpty()) { info.append("(None)"); } else { for (Subnet subnet : subnets) { @@ -203,7 +207,7 @@ public static void printNSG(NetworkSecurityGroup resource) { } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetwork.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetwork.java index 9cba6692de9f..61e2ca7f1120 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetwork.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetwork.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.Network; import com.azure.resourcemanager.network.models.NetworkPeering; import com.azure.resourcemanager.network.models.NetworkPeeringGatewayUse; @@ -23,6 +25,8 @@ /** Test of virtual network management. */ public class TestNetwork { + private static final ClientLogger LOGGER = new ClientLogger(TestNetwork.class); + /** Test of network with subnets. */ public class WithSubnets extends TestTemplate { @Override @@ -484,13 +488,13 @@ public static void printNetwork(Network resource) { // Output services with access Map> services = subnet.servicesWithAccess(); - if (services.size() > 0) { + if (!services.isEmpty()) { info.append("\n\tServices with access"); for (Map.Entry> service : services.entrySet()) { - info - .append("\n\t\tService: ") + info.append("\n\t\tService: ") .append(service.getKey()) - .append(" Regions: " + service.getValue() + ""); + .append(" Regions: ") + .append(service.getValue()); } } } @@ -512,6 +516,6 @@ public static void printNetwork(Network resource) { .append(peering.gatewayUse()); } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkInterface.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkInterface.java index e06d10395e17..49a9451b3333 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkInterface.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkInterface.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.LoadBalancerBackend; import com.azure.resourcemanager.network.models.LoadBalancerInboundNatRule; import com.azure.resourcemanager.network.models.Network; @@ -15,6 +17,8 @@ import org.junit.jupiter.api.Assertions; public class TestNetworkInterface extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestNetworkInterface.class); + @Override public NetworkInterface createResource(NetworkInterfaces networkInterfaces) throws Exception { @@ -199,7 +203,7 @@ public static void printNic(NetworkInterface resource) { } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } @Override diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkWatcher.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkWatcher.java index 1897af7112fa..27fe629849b1 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkWatcher.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestNetworkWatcher.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; import com.azure.resourcemanager.compute.models.VirtualMachine; import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes; @@ -28,6 +30,8 @@ /** Tests Network Watcher. */ public class TestNetworkWatcher extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestNetworkWatcher.class); + private String testId = ""; private static final Region REGION = Region.EUROPE_NORTH; private String groupName; @@ -169,19 +173,9 @@ StorageAccount ensureStorageAccount(StorageAccounts storageAccounts) { @Override public void print(NetworkWatcher nw) { - StringBuilder info = new StringBuilder(); - info - .append("Network Watcher: ") - .append(nw.id()) - .append("\n\tName: ") - .append(nw.name()) - .append("\n\tResource group: ") - .append(nw.resourceGroupName()) - .append("\n\tRegion: ") - .append(nw.regionName()) - .append("\n\tTags: ") - .append(nw.tags()); - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, () -> "Network Watcher: " + nw.id() + "\n\tName: " + nw.name() + + "\n\tResource group: " + nw.resourceGroupName() + "\n\tRegion: " + nw.regionName() + "\n\tTags: " + + nw.tags()); } public String groupName() { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java index c31fdd62a87e..01ae80cd352f 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.privatedns.models.ARecordSet; import com.azure.resourcemanager.privatedns.models.AaaaRecordSet; import com.azure.resourcemanager.privatedns.models.CnameRecordSet; @@ -32,6 +34,8 @@ import static com.azure.resourcemanager.privatedns.models.RecordType.TXT; public class TestPrivateDns extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestPrivateDns.class); + @Override public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception { final Region region = Region.US_EAST; @@ -84,7 +88,7 @@ public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception // Check Dns zone properties Assertions.assertTrue(resource.name().startsWith(topLevelDomain)); - Assertions.assertTrue(resource.tags().size() == 2); + Assertions.assertEquals(2, resource.tags().size()); // Check SOA record - external child resource (created by default) SoaRecordSet soaRecordSet = resource.getSoaRecordSet(); @@ -97,23 +101,23 @@ public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception // Check A records PagedIterable aRecordSets = resource.aRecordSets().list(); - Assertions.assertTrue(aRecordSets.stream().count() == 1); - Assertions.assertTrue(aRecordSets.iterator().next().timeToLive() == 7200); + Assertions.assertEquals(1, aRecordSets.stream().count()); + Assertions.assertEquals(7200, aRecordSets.iterator().next().timeToLive()); // Check AAAA records PagedIterable aaaaRecordSets = resource.aaaaRecordSets().list(); - Assertions.assertTrue(aaaaRecordSets.stream().count() == 1); + Assertions.assertEquals(1, aaaaRecordSets.stream().count()); Assertions.assertTrue(aaaaRecordSets.iterator().next().name().startsWith("www")); - Assertions.assertTrue(aaaaRecordSets.iterator().next().ipv6Addresses().size() == 2); + Assertions.assertEquals(2, aaaaRecordSets.iterator().next().ipv6Addresses().size()); // Check MX records PagedIterable mxRecordSets = resource.mxRecordSets().list(); - Assertions.assertTrue(mxRecordSets.stream().count() == 1); + Assertions.assertEquals(1, mxRecordSets.stream().count()); MxRecordSet mxRecordSet = mxRecordSets.iterator().next(); Assertions.assertNotNull(mxRecordSet); Assertions.assertTrue(mxRecordSet.name().startsWith("email")); - Assertions.assertTrue(mxRecordSet.metadata().size() == 2); - Assertions.assertTrue(mxRecordSet.records().size() == 2); + Assertions.assertEquals(2, mxRecordSet.metadata().size()); + Assertions.assertEquals(2, mxRecordSet.records().size()); for (MxRecord mxRecord : mxRecordSet.records()) { Assertions.assertTrue(mxRecord.exchange().startsWith("mail.contoso-mail-exchange1.com") || mxRecord.exchange().startsWith("mail.contoso-mail-exchange2.com")); @@ -123,19 +127,19 @@ public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception // Check TXT records PagedIterable txtRecordSets = resource.txtRecordSets().list(); - Assertions.assertTrue(txtRecordSets.stream().count() == 2); + Assertions.assertEquals(2, txtRecordSets.stream().count()); // Check SRV records PagedIterable srvRecordSets = resource.srvRecordSets().list(); - Assertions.assertTrue(srvRecordSets.stream().count() == 1); + Assertions.assertEquals(1, srvRecordSets.stream().count()); // Check PTR records PagedIterable ptrRecordSets = resource.ptrRecordSets().list(); - Assertions.assertTrue(ptrRecordSets.stream().count() == 2); + Assertions.assertEquals(2, ptrRecordSets.stream().count()); // Check CNAME records PagedIterable cnameRecordSets = resource.cnameRecordSets().list(); - Assertions.assertTrue(cnameRecordSets.stream().count() == 2); + Assertions.assertEquals(2, cnameRecordSets.stream().count()); // Check Generic record set listing PagedIterable recordSets = resource.listRecordSets(); @@ -195,14 +199,14 @@ public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception Assertions.assertNotNull(recordSet); } } - Assertions.assertTrue(typeToCount.get(SOA) == 1); - Assertions.assertTrue(typeToCount.get(RecordType.A) == 1); - Assertions.assertTrue(typeToCount.get(AAAA) == 1); - Assertions.assertTrue(typeToCount.get(MX) == 1); - Assertions.assertTrue(typeToCount.get(TXT) == 2); - Assertions.assertTrue(typeToCount.get(SRV) == 1); - Assertions.assertTrue(typeToCount.get(PTR) == 2); - Assertions.assertTrue(typeToCount.get(RecordType.CNAME) == 2); + Assertions.assertEquals(1, (int) typeToCount.get(SOA)); + Assertions.assertEquals(1, (int) typeToCount.get(RecordType.A)); + Assertions.assertEquals(1, (int) typeToCount.get(AAAA)); + Assertions.assertEquals(1, (int) typeToCount.get(MX)); + Assertions.assertEquals(2, (int) typeToCount.get(TXT)); + Assertions.assertEquals(1, (int) typeToCount.get(SRV)); + Assertions.assertEquals(2, (int) typeToCount.get(PTR)); + Assertions.assertEquals(2, (int) typeToCount.get(RecordType.CNAME)); return resource; } @@ -254,9 +258,9 @@ public PrivateDnsZone updateResource(PrivateDnsZone resource) throws Exception { // Check SRV records PagedIterable srvRecordSets = resource.srvRecordSets().list(); - Assertions.assertTrue(srvRecordSets.stream().count() == 1); + Assertions.assertEquals(1, srvRecordSets.stream().count()); SrvRecordSet srvRecordSet = srvRecordSets.iterator().next(); - Assertions.assertTrue(srvRecordSet.records().size() == 4); + Assertions.assertEquals(4, srvRecordSet.records().size()); for (SrvRecord srvRecord : srvRecordSet.records()) { Assertions.assertFalse(srvRecord.target().startsWith("bigbox.contoso-service.com")); } @@ -267,11 +271,11 @@ public PrivateDnsZone updateResource(PrivateDnsZone resource) throws Exception { SoaRecord soaRecord = soaRecordSet.record(); Assertions.assertNotNull(soaRecord); Assertions.assertEquals(soaRecord.minimumTtl(), Long.valueOf(600)); - Assertions.assertTrue(soaRecordSet.timeToLive() == 7200); + Assertions.assertEquals(7200, soaRecordSet.timeToLive()); // Check MX records PagedIterable mxRecordSets = resource.mxRecordSets().list(); - Assertions.assertTrue(mxRecordSets.stream().count() == 2); + Assertions.assertEquals(2, mxRecordSets.stream().count()); resource.update() .updateMxRecordSet("email") @@ -283,11 +287,11 @@ public PrivateDnsZone updateResource(PrivateDnsZone resource) throws Exception { .withTag("d", "dd") .apply(); - Assertions.assertTrue(resource.tags().size() == 3); + Assertions.assertEquals(3, resource.tags().size()); // Check "mail" MX record MxRecordSet mxRecordSet = resource.mxRecordSets().getByName("email"); - Assertions.assertTrue(mxRecordSet.records().size() == 1); - Assertions.assertTrue(mxRecordSet.metadata().size() == 3); + Assertions.assertEquals(1, mxRecordSet.records().size()); + Assertions.assertEquals(3, mxRecordSet.metadata().size()); Assertions.assertTrue(mxRecordSet.records().get(0).exchange().startsWith("mail.contoso-mail-exchange1.com")); return resource; @@ -399,11 +403,11 @@ public void print(PrivateDnsZone resource) { .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { - if (txtRecord.value().size() > 0) { + if (!txtRecord.value().isEmpty()) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPAddress.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPAddress.java index 0d0b58b9436d..bcea20410bed 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPAddress.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPAddress.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.LoadBalancer; import com.azure.resourcemanager.network.models.LoadBalancerPublicFrontend; import com.azure.resourcemanager.network.models.NetworkInterface; @@ -13,6 +15,8 @@ /** Tests public IPs. */ public class TestPublicIPAddress extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestPublicIPAddress.class); + @Override public PublicIpAddress createResource(PublicIpAddresses pips) throws Exception { final String newPipName = pips.manager().resourceManager().internalContext().randomResourceName("pip", 10); @@ -44,7 +48,7 @@ public PublicIpAddress updateResource(PublicIpAddress resource) throws Exception .withTag("tag2", "value2") .apply(); Assertions.assertTrue(resource.leafDomainLabel().equalsIgnoreCase(updatedDnsName)); - Assertions.assertTrue(resource.idleTimeoutInMinutes() == updatedIdleTimeout); + Assertions.assertEquals(updatedIdleTimeout, resource.idleTimeoutInMinutes()); Assertions.assertEquals("value2", resource.tags().get("tag2")); resource.updateTags().withoutTag("tag1").withTag("tag3", "value3").applyTags(); @@ -114,6 +118,6 @@ public static void printPIP(PublicIpAddress resource) { info.append("(None)"); } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPPrefix.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPPrefix.java index 645230b91671..c0d30fe6f0bb 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPPrefix.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPublicIPPrefix.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; import com.azure.core.management.SubResource; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.IpVersion; import com.azure.resourcemanager.network.models.PublicIpPrefix; import com.azure.resourcemanager.network.models.PublicIpPrefixSku; @@ -13,6 +15,8 @@ /** Tests public Prefixes. */ public class TestPublicIPPrefix extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestPublicIPPrefix.class); + @Override public PublicIpPrefix createResource(PublicIpPrefixes pips) throws Exception { final String newPipName = pips.manager().resourceManager().internalContext().randomResourceName("pip", 10); @@ -26,7 +30,7 @@ public PublicIpPrefix createResource(PublicIpPrefixes pips) throws Exception { Assertions.assertEquals(pip.prefixLength(), (Integer) 28); Assertions.assertEquals(pip.sku().name().toString(), "Standard"); - Assertions.assertTrue(pip.publicIpAddressVersion() == IpVersion.IPV4); + Assertions.assertSame(pip.publicIpAddressVersion(), IpVersion.IPV4); return pip; } @@ -67,6 +71,6 @@ public static void printPIP(PublicIpPrefix resource) { info.append("(None)"); } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRedis.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRedis.java index 6bdc52bdad11..e2030b9d1324 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRedis.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRedis.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.redis.models.RedisCache; import com.azure.resourcemanager.redis.models.RedisCaches; import com.azure.core.management.Region; @@ -10,6 +12,8 @@ import reactor.core.publisher.Mono; public class TestRedis extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestRedis.class); + @Override public RedisCache createResource(RedisCaches resources) throws Exception { final String redisName = resources.manager().resourceManager().internalContext().randomResourceName("redis", 10); @@ -43,6 +47,6 @@ public RedisCache updateResource(RedisCache resource) throws Exception { @Override public void print(RedisCache resource) { - System.out.println("Redis Cache: " + resource.id() + ", Name: " + resource.name()); + LOGGER.log(LogLevel.VERBOSE, () -> "Redis Cache: " + resource.id() + ", Name: " + resource.name()); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRouteTables.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRouteTables.java index 551f63d06731..1ea70731a0ea 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRouteTables.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRouteTables.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.Route; import com.azure.resourcemanager.network.models.RouteNextHopType; import com.azure.resourcemanager.network.models.RouteTable; @@ -15,6 +17,8 @@ /** Test of virtual network management. */ public class TestRouteTables { + private static final ClientLogger LOGGER = new ClientLogger(TestRouteTables.class); + private String route1Name = "route1"; private String route2Name = "route2"; private String routeAddedName = "route3"; @@ -58,13 +62,13 @@ public RouteTable createResource(RouteTables routeTables) throws Exception { Route route1 = routeTable.routes().get(route1Name); Assertions.assertTrue(route1.destinationAddressPrefix().equalsIgnoreCase(route1AddressPrefix)); Assertions.assertTrue(route1.nextHopIpAddress().equalsIgnoreCase(virtualApplianceIp)); - Assertions.assertTrue(route1.nextHopType().equals(RouteNextHopType.VIRTUAL_APPLIANCE)); + Assertions.assertEquals(route1.nextHopType(), RouteNextHopType.VIRTUAL_APPLIANCE); Assertions.assertTrue(routeTable.routes().containsKey(route2Name)); Route route2 = routeTable.routes().get(route2Name); Assertions.assertTrue(route2.destinationAddressPrefix().equalsIgnoreCase(route2AddressPrefix)); - Assertions.assertTrue(route2.nextHopIpAddress() == null); - Assertions.assertTrue(route2.nextHopType().equals(hopType)); + Assertions.assertNull(route2.nextHopIpAddress()); + Assertions.assertEquals(route2.nextHopType(), hopType); Assertions.assertTrue(routeTable.isBgpRoutePropagationDisabled()); @@ -83,7 +87,7 @@ public RouteTable createResource(RouteTables routeTables) throws Exception { .create(); List subnets = routeTable.refresh().listAssociatedSubnets(); - Assertions.assertTrue(subnets.size() == 1); + Assertions.assertEquals(1, subnets.size()); Assertions.assertTrue(subnets.get(0).routeTableId().equalsIgnoreCase(routeTable.id())); return routeTable; } @@ -110,7 +114,7 @@ public RouteTable updateResource(RouteTable routeTable) throws Exception { Assertions.assertTrue(routeTable.tags().containsKey("tag1")); Assertions.assertTrue(routeTable.tags().containsKey("tag2")); - Assertions.assertTrue(!routeTable.routes().containsKey(route1Name)); + Assertions.assertFalse(routeTable.routes().containsKey(route1Name)); Assertions.assertTrue(routeTable.routes().containsKey(route2Name)); Assertions.assertTrue(routeTable.routes().containsKey(routeAddedName)); Assertions.assertFalse(routeTable.isBgpRoutePropagationDisabled()); @@ -126,7 +130,7 @@ public RouteTable updateResource(RouteTable routeTable) throws Exception { .apply(); List subnets = routeTable.refresh().listAssociatedSubnets(); - Assertions.assertTrue(subnets.size() == 0); + Assertions.assertEquals(0, subnets.size()); routeTable.updateTags().withoutTag("tag1").withTag("tag3", "value3").applyTags(); Assertions.assertFalse(routeTable.tags().containsKey("tag1")); @@ -189,6 +193,6 @@ public static void printRouteTable(RouteTable resource) { .append(subnet.routeTableId()); } info.append("\n\tDisable BGP route propagation: ").append(resource.isBgpRoutePropagationDisabled()); - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSearchService.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSearchService.java index d7cda788cbb8..ef6b4a52d942 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSearchService.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSearchService.java @@ -5,6 +5,8 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.management.Region; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.search.models.AdminKeyKind; import com.azure.resourcemanager.search.models.AdminKeys; import com.azure.resourcemanager.search.models.QueryKey; @@ -15,6 +17,7 @@ import org.junit.jupiter.api.Assertions; public class TestSearchService { + private static final ClientLogger LOGGER = new ClientLogger(TestSearchService.class); /** * Search service test. @@ -61,7 +64,7 @@ public SearchService updateResource(SearchService resource) throws Exception { .withPartitionCount(1) .apply(); Assertions.assertTrue(resource.tags().containsKey("tag2")); - Assertions.assertTrue(!resource.tags().containsKey("tag1")); + Assertions.assertFalse(resource.tags().containsKey("tag1")); Assertions.assertEquals(1, resource.replicaCount()); Assertions.assertEquals(1, resource.partitionCount()); Assertions.assertEquals(2, TestUtilities.getSize(resource.listQueryKeys())); @@ -117,7 +120,7 @@ public SearchService updateResource(SearchService resource) throws Exception { .withoutTag("tag1") .apply(); Assertions.assertTrue(resource.tags().containsKey("tag2")); - Assertions.assertTrue(!resource.tags().containsKey("tag1")); + Assertions.assertFalse(resource.tags().containsKey("tag1")); return resource; } @@ -158,7 +161,7 @@ public SearchService updateResource(SearchService resource) throws Exception { .withoutTag("tag1") .apply(); Assertions.assertTrue(resource.tags().containsKey("tag2")); - Assertions.assertTrue(!resource.tags().containsKey("tag1")); + Assertions.assertFalse(resource.tags().containsKey("tag1")); return resource; } @@ -202,7 +205,7 @@ public SearchService updateResource(SearchService resource) throws Exception { .withoutTag("tag1") .apply(); Assertions.assertTrue(resource.tags().containsKey("tag2")); - Assertions.assertTrue(!resource.tags().containsKey("tag1")); + Assertions.assertFalse(resource.tags().containsKey("tag1")); Assertions.assertEquals(SkuName.STANDARD, resource.sku().name()); Assertions.assertEquals(1, resource.replicaCount()); Assertions.assertEquals(1, resource.partitionCount()); @@ -247,7 +250,7 @@ public static void print(SearchService resource, String header) { stringBuilder.append("\n\t Key value: ").append(queryKey.key()); } - System.out.println(stringBuilder); + LOGGER.log(LogLevel.VERBOSE, stringBuilder::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTemplate.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTemplate.java index bb847d6b08d6..0f0035d66adc 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTemplate.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTemplate.java @@ -4,6 +4,8 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.resources.fluentcore.arm.Manager; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingById; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingByResourceGroup; @@ -23,12 +25,13 @@ * @param Top level resource type * @param Type representing the collection of the top level resources */ -public abstract class TestTemplate< - ResourceT extends GroupableResource, ?>, +public abstract class TestTemplate, ?>, CollectionT extends SupportsListing & SupportsGettingByResourceGroup & SupportsDeletingById & SupportsGettingById & HasManager> { + private static final ClientLogger LOGGER = new ClientLogger(TestTemplate.class); + private ResourceT resource; private CollectionT collection; private ResourceGroups resourceGroups; @@ -64,7 +67,7 @@ protected TestTemplate() { public int verifyListing() throws ManagementException, IOException { PagedIterable resources = this.collection.list(); for (ResourceT r : resources) { - System.out.println("resource id: " + r.id()); + LOGGER.log(LogLevel.VERBOSE, () -> "resource id: " + r.id()); } return TestUtilities.getSize(resources); } @@ -118,7 +121,7 @@ public void runTest(CollectionT collection, ResourceGroups resourceGroups) throw // Verify creation this.resource = createResource(collection); - System.out.println("\n------------\nAfter creation:\n"); + LOGGER.log(LogLevel.VERBOSE, () -> "\n------------\nAfter creation:\n"); print(this.resource); // Verify listing @@ -127,7 +130,7 @@ public void runTest(CollectionT collection, ResourceGroups resourceGroups) throw // Verify getting this.resource = verifyGetting(); Assertions.assertNotNull(this.resource); - System.out.println("\n------------\nRetrieved resource:\n"); + LOGGER.log(LogLevel.VERBOSE, () -> "\n------------\nRetrieved resource:\n"); print(this.resource); boolean failedUpdate = false; @@ -136,11 +139,11 @@ public void runTest(CollectionT collection, ResourceGroups resourceGroups) throw try { this.resource = updateResource(this.resource); Assertions.assertNotNull(this.resource); - System.out.println("\n------------\nUpdated resource:\n"); + LOGGER.log(LogLevel.VERBOSE, () -> "\n------------\nUpdated resource:\n"); message = "Print failed"; print(this.resource); } catch (Exception e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Update failed", e); failedUpdate = true; } @@ -150,7 +153,7 @@ public void runTest(CollectionT collection, ResourceGroups resourceGroups) throw message = "Delete failed"; verifyDeleting(); } catch (Exception e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Delete failed", e); failedDelete = true; } Assertions.assertFalse(failedUpdate, message); diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java index f0d9816d8828..71dc35953141 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.models.PublicIpAddress; import com.azure.resourcemanager.network.models.PublicIpAddresses; import com.azure.core.management.Region; @@ -19,6 +21,7 @@ /** Test of traffic manager management. */ public class TestTrafficManager extends TestTemplate { + private static final ClientLogger LOGGER = new ClientLogger(TestTrafficManager.class); private final PublicIpAddresses publicIpAddresses; @@ -405,6 +408,6 @@ public void print(TrafficManagerProfile profile) { .append(endpoint.routingWeight()); } } - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestUtils.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestUtils.java index 85091cc9ec6b..d9a0908fb063 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestUtils.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestUtils.java @@ -4,12 +4,16 @@ package com.azure.resourcemanager; import com.azure.core.util.Configuration; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.compute.models.DataDisk; import com.azure.resourcemanager.compute.models.VirtualMachine; import com.azure.resourcemanager.resources.models.ManagementLock; /** Test utilities. */ public final class TestUtils { + private static final ClientLogger LOGGER = new ClientLogger(TestUtils.class); + private TestUtils() { } @@ -22,11 +26,11 @@ public static boolean isRecordMode() { } public static void print(ManagementLock lock) { - StringBuffer info = new StringBuffer(); + StringBuilder info = new StringBuilder(); info.append("\nLock ID: ").append(lock.id()) .append("\nLocked resource ID: ").append(lock.lockedResourceId()) .append("\nLevel: ").append(lock.level()); - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } /** @@ -120,26 +124,9 @@ public static void print(VirtualMachine resource) { networkProfile.append("\n\t\tId:").append(networkInterfaceId); } - System - .out - .println( - new StringBuilder() - .append("Virtual Machine: ") - .append(resource.id()) - .append("Name: ") - .append(resource.name()) - .append("\n\tResource group: ") - .append(resource.resourceGroupName()) - .append("\n\tRegion: ") - .append(resource.region()) - .append("\n\tTags: ") - .append(resource.tags()) - .append("\n\tHardwareProfile: ") - .append("\n\t\tSize: ") - .append(resource.size()) - .append(storageProfile) - .append(osProfile) - .append(networkProfile) - .toString()); + LOGGER.log(LogLevel.VERBOSE, () -> "Virtual Machine: " + resource.id() + "Name: " + resource.name() + + "\n\tResource group: " + resource.resourceGroupName() + "\n\tRegion: " + resource.region() + "\n\tTags: " + + resource.tags() + "\n\tHardwareProfile: " + "\n\t\tSize: " + resource.size() + storageProfile + osProfile + + networkProfile); } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualNetworkGateway.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualNetworkGateway.java index b2f9099c59d8..68448d74db77 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualNetworkGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestVirtualNetworkGateway.java @@ -3,6 +3,8 @@ package com.azure.resourcemanager; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.resourcemanager.network.NetworkManager; import com.azure.resourcemanager.network.models.LocalNetworkGateway; import com.azure.resourcemanager.network.models.Network; @@ -27,6 +29,8 @@ /** Tests Virtual Network Gateway. */ public class TestVirtualNetworkGateway { + private static final ClientLogger LOGGER = new ClientLogger(TestVirtualNetworkGateway.class); + private String testId = ""; private Region region = Region.US_NORTH_CENTRAL; private String groupName; @@ -324,7 +328,7 @@ certificateName, new File(getClass().getClassLoader().getResource(certificateNam // contains credential in the profile string String profile = vngw1.generateVpnProfile(); - System.out.println(profile); + LOGGER.log(LogLevel.VERBOSE, () -> profile); return vngw1; } @@ -359,6 +363,6 @@ static void printVirtualNetworkGateway(VirtualNetworkGateway gateway) { .append(gateway.regionName()) .append("\n\tTags: ") .append(gateway.tags()); - System.out.println(info.toString()); + LOGGER.log(LogLevel.VERBOSE, info::toString); } } diff --git a/sdk/search/azure-search-documents/CHANGELOG.md b/sdk/search/azure-search-documents/CHANGELOG.md index 6eb9e26cea40..c48fcced8334 100644 --- a/sdk/search/azure-search-documents/CHANGELOG.md +++ b/sdk/search/azure-search-documents/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 11.7.0-beta.3 (Unreleased) +## 11.7.0-beta.4 (Unreleased) ### Features Added @@ -10,6 +10,27 @@ ### Other Changes +## 11.7.0-beta.3 (2024-05-07) + +### Features Added + +- Added support for `Byte[]` and `List` in `FieldBuilder` +- Added support for `HybridSearch` +- Index models added: `AIServicesVisionParameters`, `AIServicesVisionVectorizer`, `AIStudioModelCatalogName`, + `AzureMachineLearningParameters`, `AzureMachineLearningVectorizer`, `AzureOpenAIModelName`, `VectorEncodingFormat`, + `VisionVectorizeSkill` +- Search models added: `HybridCountAndFacetMode`, `HybridSearch`, `SearchScoreThreshold`, `VectorSimilarityThreshold`, + `VectorThreshold`, `VectorThresholdKind`, `VectorizableImageBinaryQuery`, `VectorizableImageUrlQuery` + +### Other Changes + +- Sample added for creating a vector fields index with reduced dimensions. + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to version `1.49.0`. +- Upgraded `azure-core-http-netty` from `1.14.2` to version `1.15.0`. +- Upgraded `azure-core-serializer-json-jackson` from `1.4.11` to version `1.4.12`. ## 11.6.4 (2024-04-23) diff --git a/sdk/search/azure-search-documents/README.md b/sdk/search/azure-search-documents/README.md index be283cdbff32..c54420328ded 100644 --- a/sdk/search/azure-search-documents/README.md +++ b/sdk/search/azure-search-documents/README.md @@ -75,7 +75,7 @@ add the direct dependency to your project as follows. com.azure azure-search-documents - 11.7.0-beta.2 + 11.7.0-beta.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/search/azure-search-documents/pom.xml b/sdk/search/azure-search-documents/pom.xml index 974db62b9f51..55d68a917965 100644 --- a/sdk/search/azure-search-documents/pom.xml +++ b/sdk/search/azure-search-documents/pom.xml @@ -16,7 +16,7 @@ com.azure azure-search-documents - 11.7.0-beta.3 + 11.7.0-beta.4 jar @@ -103,6 +103,11 @@ 1.12.1 test + + com.azure + azure-ai-openai + 1.0.0-beta.8 + org.junit.jupiter junit-jupiter-api diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java index 47680fb5bf86..27b62030f428 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java @@ -54,6 +54,7 @@ public final class FieldBuilder { private static final int MAX_DEPTH = 10000; private static final Map SUPPORTED_NONE_PARAMETERIZED_TYPE = new HashMap<>(); private static final Set UNSUPPORTED_TYPES = new HashSet<>(); + private static final Set UNSUPPORTED_SERVICE_TYPES = new HashSet<>(); private static final SearchFieldDataType COLLECTION_STRING = SearchFieldDataType.collection(SearchFieldDataType.STRING); @@ -83,6 +84,7 @@ public final class FieldBuilder { SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Byte.class, SearchFieldDataType.SBYTE); SUPPORTED_NONE_PARAMETERIZED_TYPE.put(short.class, SearchFieldDataType.INT16); SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Short.class, SearchFieldDataType.INT16); + UNSUPPORTED_SERVICE_TYPES.add(SearchFieldDataType.BYTE); } /** diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AMLParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningParameters.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AMLParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningParameters.java index bce09e0d1505..a27e14a17c3f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AMLParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningParameters.java @@ -19,7 +19,7 @@ * Specifies the properties for connecting to an AML vectorizer. */ @Fluent -public final class AMLParameters implements JsonSerializable { +public final class AzureMachineLearningParameters implements JsonSerializable { /* * (Required for no authentication or key authentication) The scoring URI of the AML service to which the JSON * payload will be sent. Only the https URI scheme is allowed. @@ -55,11 +55,11 @@ public final class AMLParameters implements JsonSerializable { private AIStudioModelCatalogName modelName; /** - * Creates an instance of AMLParameters class. + * Creates an instance of AzureMachineLearningParameters class. * * @param scoringUri the scoringUri value to set. */ - public AMLParameters(String scoringUri) { + public AzureMachineLearningParameters(String scoringUri) { this.scoringUri = scoringUri; } @@ -86,9 +86,9 @@ public String getAuthenticationKey() { * Set the authenticationKey property: (Required for key authentication) The key for the AML service. * * @param authenticationKey the authenticationKey value to set. - * @return the AMLParameters object itself. + * @return the AzureMachineLearningParameters object itself. */ - public AMLParameters setAuthenticationKey(String authenticationKey) { + public AzureMachineLearningParameters setAuthenticationKey(String authenticationKey) { this.authenticationKey = authenticationKey; return this; } @@ -110,9 +110,9 @@ public String getResourceId() { * subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. * * @param resourceId the resourceId value to set. - * @return the AMLParameters object itself. + * @return the AzureMachineLearningParameters object itself. */ - public AMLParameters setResourceId(String resourceId) { + public AzureMachineLearningParameters setResourceId(String resourceId) { this.resourceId = resourceId; return this; } @@ -132,9 +132,9 @@ public Duration getTimeout() { * call. * * @param timeout the timeout value to set. - * @return the AMLParameters object itself. + * @return the AzureMachineLearningParameters object itself. */ - public AMLParameters setTimeout(Duration timeout) { + public AzureMachineLearningParameters setTimeout(Duration timeout) { this.timeout = timeout; return this; } @@ -152,9 +152,9 @@ public String getRegion() { * Set the region property: (Optional for token authentication). The region the AML service is deployed in. * * @param region the region value to set. - * @return the AMLParameters object itself. + * @return the AzureMachineLearningParameters object itself. */ - public AMLParameters setRegion(String region) { + public AzureMachineLearningParameters setRegion(String region) { this.region = region; return this; } @@ -174,9 +174,9 @@ public AIStudioModelCatalogName getModelName() { * the provided endpoint. * * @param modelName the modelName value to set. - * @return the AMLParameters object itself. + * @return the AzureMachineLearningParameters object itself. */ - public AMLParameters setModelName(AIStudioModelCatalogName modelName) { + public AzureMachineLearningParameters setModelName(AIStudioModelCatalogName modelName) { this.modelName = modelName; return this; } @@ -194,15 +194,15 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of AMLParameters from the JsonReader. + * Reads an instance of AzureMachineLearningParameters from the JsonReader. * * @param jsonReader The JsonReader being read. - * @return An instance of AMLParameters if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. + * @return An instance of AzureMachineLearningParameters if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the AMLParameters. + * @throws IOException If an error occurs while reading the AzureMachineLearningParameters. */ - public static AMLParameters fromJson(JsonReader jsonReader) throws IOException { + public static AzureMachineLearningParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { boolean scoringUriFound = false; String scoringUri = null; @@ -233,14 +233,15 @@ public static AMLParameters fromJson(JsonReader jsonReader) throws IOException { } } if (scoringUriFound) { - AMLParameters deserializedAMLParameters = new AMLParameters(scoringUri); - deserializedAMLParameters.authenticationKey = authenticationKey; - deserializedAMLParameters.resourceId = resourceId; - deserializedAMLParameters.timeout = timeout; - deserializedAMLParameters.region = region; - deserializedAMLParameters.modelName = modelName; - - return deserializedAMLParameters; + AzureMachineLearningParameters deserializedAzureMachineLearningParameters + = new AzureMachineLearningParameters(scoringUri); + deserializedAzureMachineLearningParameters.authenticationKey = authenticationKey; + deserializedAzureMachineLearningParameters.resourceId = resourceId; + deserializedAzureMachineLearningParameters.timeout = timeout; + deserializedAzureMachineLearningParameters.region = region; + deserializedAzureMachineLearningParameters.modelName = modelName; + + return deserializedAzureMachineLearningParameters; } throw new IllegalStateException("Missing required property: uri"); }); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AMLVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningVectorizer.java similarity index 69% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AMLVectorizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningVectorizer.java index 505a34a8d926..301ad886d438 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AMLVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningVectorizer.java @@ -17,18 +17,18 @@ * vector embedding of a query string. */ @Fluent -public final class AMLVectorizer extends VectorSearchVectorizer { +public final class AzureMachineLearningVectorizer extends VectorSearchVectorizer { /* * Specifies the properties of the AML vectorizer. */ - private AMLParameters aMLParameters; + private AzureMachineLearningParameters aMLParameters; /** - * Creates an instance of AMLVectorizer class. + * Creates an instance of AzureMachineLearningVectorizer class. * * @param name the name value to set. */ - public AMLVectorizer(String name) { + public AzureMachineLearningVectorizer(String name) { super(name); } @@ -37,7 +37,7 @@ public AMLVectorizer(String name) { * * @return the aMLParameters value. */ - public AMLParameters getAMLParameters() { + public AzureMachineLearningParameters getAMLParameters() { return this.aMLParameters; } @@ -45,9 +45,9 @@ public AMLParameters getAMLParameters() { * Set the aMLParameters property: Specifies the properties of the AML vectorizer. * * @param aMLParameters the aMLParameters value to set. - * @return the AMLVectorizer object itself. + * @return the AzureMachineLearningVectorizer object itself. */ - public AMLVectorizer setAMLParameters(AMLParameters aMLParameters) { + public AzureMachineLearningVectorizer setAMLParameters(AzureMachineLearningParameters aMLParameters) { this.aMLParameters = aMLParameters; return this; } @@ -63,20 +63,20 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of AMLVectorizer from the JsonReader. + * Reads an instance of AzureMachineLearningVectorizer from the JsonReader. * * @param jsonReader The JsonReader being read. - * @return An instance of AMLVectorizer if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. + * @return An instance of AzureMachineLearningVectorizer if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties or the * polymorphic discriminator. - * @throws IOException If an error occurs while reading the AMLVectorizer. + * @throws IOException If an error occurs while reading the AzureMachineLearningVectorizer. */ - public static AMLVectorizer fromJson(JsonReader jsonReader) throws IOException { + public static AzureMachineLearningVectorizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { boolean nameFound = false; String name = null; - AMLParameters aMLParameters = null; + AzureMachineLearningParameters aMLParameters = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -92,16 +92,17 @@ public static AMLVectorizer fromJson(JsonReader jsonReader) throws IOException { name = reader.getString(); nameFound = true; } else if ("amlParameters".equals(fieldName)) { - aMLParameters = AMLParameters.fromJson(reader); + aMLParameters = AzureMachineLearningParameters.fromJson(reader); } else { reader.skipChildren(); } } if (nameFound) { - AMLVectorizer deserializedAMLVectorizer = new AMLVectorizer(name); - deserializedAMLVectorizer.aMLParameters = aMLParameters; + AzureMachineLearningVectorizer deserializedAzureMachineLearningVectorizer + = new AzureMachineLearningVectorizer(name); + deserializedAzureMachineLearningVectorizer.aMLParameters = aMLParameters; - return deserializedAMLVectorizer; + return deserializedAzureMachineLearningVectorizer; } throw new IllegalStateException("Missing required property: name"); }); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceLimits.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceLimits.java index 1a7bd1686be1..dd77354f1469 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceLimits.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceLimits.java @@ -52,7 +52,7 @@ public SearchServiceLimits() { /** * Get the maxFieldsPerIndex property: The maximum allowed fields per index. - * + * * @return the maxFieldsPerIndex value. */ public Integer getMaxFieldsPerIndex() { @@ -61,7 +61,7 @@ public Integer getMaxFieldsPerIndex() { /** * Set the maxFieldsPerIndex property: The maximum allowed fields per index. - * + * * @param maxFieldsPerIndex the maxFieldsPerIndex value to set. * @return the SearchServiceLimits object itself. */ @@ -73,7 +73,7 @@ public SearchServiceLimits setMaxFieldsPerIndex(Integer maxFieldsPerIndex) { /** * Get the maxFieldNestingDepthPerIndex property: The maximum depth which you can nest sub-fields in an index, * including the top-level complex field. For example, a/b/c has a nesting depth of 3. - * + * * @return the maxFieldNestingDepthPerIndex value. */ public Integer getMaxFieldNestingDepthPerIndex() { @@ -83,7 +83,7 @@ public Integer getMaxFieldNestingDepthPerIndex() { /** * Set the maxFieldNestingDepthPerIndex property: The maximum depth which you can nest sub-fields in an index, * including the top-level complex field. For example, a/b/c has a nesting depth of 3. - * + * * @param maxFieldNestingDepthPerIndex the maxFieldNestingDepthPerIndex value to set. * @return the SearchServiceLimits object itself. */ @@ -95,7 +95,7 @@ public SearchServiceLimits setMaxFieldNestingDepthPerIndex(Integer maxFieldNesti /** * Get the maxComplexCollectionFieldsPerIndex property: The maximum number of fields of type * Collection(Edm.ComplexType) allowed in an index. - * + * * @return the maxComplexCollectionFieldsPerIndex value. */ public Integer getMaxComplexCollectionFieldsPerIndex() { @@ -105,7 +105,7 @@ public Integer getMaxComplexCollectionFieldsPerIndex() { /** * Set the maxComplexCollectionFieldsPerIndex property: The maximum number of fields of type * Collection(Edm.ComplexType) allowed in an index. - * + * * @param maxComplexCollectionFieldsPerIndex the maxComplexCollectionFieldsPerIndex value to set. * @return the SearchServiceLimits object itself. */ @@ -117,7 +117,7 @@ public SearchServiceLimits setMaxComplexCollectionFieldsPerIndex(Integer maxComp /** * Get the maxComplexObjectsInCollectionsPerDocument property: The maximum number of objects in complex collections * allowed per document. - * + * * @return the maxComplexObjectsInCollectionsPerDocument value. */ public Integer getMaxComplexObjectsInCollectionsPerDocument() { @@ -127,7 +127,7 @@ public Integer getMaxComplexObjectsInCollectionsPerDocument() { /** * Set the maxComplexObjectsInCollectionsPerDocument property: The maximum number of objects in complex collections * allowed per document. - * + * * @param maxComplexObjectsInCollectionsPerDocument the maxComplexObjectsInCollectionsPerDocument value to set. * @return the SearchServiceLimits object itself. */ @@ -139,7 +139,7 @@ public Integer getMaxComplexObjectsInCollectionsPerDocument() { /** * Get the maxStoragePerIndexInBytes property: The maximum amount of storage in bytes allowed per index. - * + * * @return the maxStoragePerIndexInBytes value. */ public Long getMaxStoragePerIndexInBytes() { @@ -148,7 +148,7 @@ public Long getMaxStoragePerIndexInBytes() { /** * Set the maxStoragePerIndexInBytes property: The maximum amount of storage in bytes allowed per index. - * + * * @param maxStoragePerIndexInBytes the maxStoragePerIndexInBytes value to set. * @return the SearchServiceLimits object itself. */ @@ -165,13 +165,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("maxComplexCollectionFieldsPerIndex", this.maxComplexCollectionFieldsPerIndex); jsonWriter.writeNumberField("maxComplexObjectsInCollectionsPerDocument", this.maxComplexObjectsInCollectionsPerDocument); - jsonWriter.writeNumberField("maxStoragePerIndexInBytes", this.maxStoragePerIndexInBytes); + jsonWriter.writeNumberField("maxStoragePerIndex", this.maxStoragePerIndexInBytes); return jsonWriter.writeEndObject(); } /** * Reads an instance of SearchServiceLimits from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchServiceLimits if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -195,7 +195,7 @@ public static SearchServiceLimits fromJson(JsonReader jsonReader) throws IOExcep } else if ("maxComplexObjectsInCollectionsPerDocument".equals(fieldName)) { deserializedSearchServiceLimits.maxComplexObjectsInCollectionsPerDocument = reader.getNullable(JsonReader::getInt); - } else if ("maxStoragePerIndexInBytes".equals(fieldName)) { + } else if ("maxStoragePerIndex".equals(fieldName)) { deserializedSearchServiceLimits.maxStoragePerIndexInBytes = reader.getNullable(JsonReader::getLong); } else { reader.skipChildren(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizer.java index 092234212721..a7b7fd0717e3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizer.java @@ -25,7 +25,7 @@ public class VectorSearchVectorizer implements JsonSerializable com.azure azure-search-documents - 11.7.0-beta.2 + 11.7.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -97,6 +97,7 @@ The following sections provide several code snippets covering some of the most c - [Setting customer x-ms-client-request-id per API call](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/PerCallRequestIdExample.java) - [Index vector fields and perform vector search](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchExample.java). - [Rewrite Request URL to replace OData URL syntax with standard syntax](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchRequestUrlRewriterPolicy.java) +- [Vector search using reduced embeddings](https://github.com/Azure/azure-sdk-for-java/blob/40261403b3a75aa56a3eeaf18c2ba0fd071c87a6/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchReducedEmbeddings.java) ## Troubleshooting Troubleshooting steps can be found [here][SDK_README_TROUBLESHOOTING]. diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchReducedEmbeddings.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchReducedEmbeddings.java new file mode 100644 index 000000000000..e48b5cbf382c --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchReducedEmbeddings.java @@ -0,0 +1,347 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents; + +import com.azure.ai.openai.OpenAIClient; +import com.azure.ai.openai.OpenAIClientBuilder; +import com.azure.ai.openai.models.Embeddings; +import com.azure.ai.openai.models.EmbeddingsOptions; +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.credential.KeyCredential; +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.SearchIndexClient; +import com.azure.search.documents.indexes.SearchIndexClientBuilder; +import com.azure.search.documents.indexes.SearchableField; +import com.azure.search.documents.indexes.SimpleField; +import com.azure.search.documents.indexes.models.AzureOpenAIModelName; +import com.azure.search.documents.indexes.models.AzureOpenAIParameters; +import com.azure.search.documents.indexes.models.AzureOpenAIVectorizer; +import com.azure.search.documents.indexes.models.HnswAlgorithmConfiguration; +import com.azure.search.documents.indexes.models.IndexDocumentsBatch; +import com.azure.search.documents.indexes.models.SearchField; +import com.azure.search.documents.indexes.models.SearchFieldDataType; +import com.azure.search.documents.indexes.models.SearchIndex; +import com.azure.search.documents.indexes.models.VectorSearch; +import com.azure.search.documents.indexes.models.VectorSearchProfile; +import com.azure.search.documents.models.SearchOptions; +import com.azure.search.documents.models.SearchResult; +import com.azure.search.documents.models.VectorSearchOptions; +import com.azure.search.documents.models.VectorizableTextQuery; +import com.azure.search.documents.util.SearchPagedIterable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * This sample demonstrates how to create a vector fields index with reduced dimensions, upload reduced embeddings into + * the index, and query the documents. To accomplish this, you can utilize Azure OpenAI embedding models: a smaller and + * highly efficient {@code text-embedding-3-small} model or a larger and more powerful {@code text-embedding-3-large} + * model. These models are significantly more efficient and require less storage space. + */ +public class VectorSearchReducedEmbeddings { + public static void main(String[] args) { + SearchIndex vectorIndex = defineVectorIndex(); + + // After creating an instance of the 'SearchIndex',we need to instantiate the 'SearchIndexClient' and call the + // 'createIndex' method to create the search index. + createVectorIndex(vectorIndex); + + // Now, we can instantiate the 'SearchClient' and upload the documents to the 'Hotel' index we created earlier. + SearchClient searchClient = new SearchClientBuilder() + .endpoint(Configuration.getGlobalConfiguration().get("SEARCH_ENDPOINT")) + .indexName("hotel") + .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("SEARCH_API_KEY"))) + .buildClient(); + + // Next, we will create sample hotel documents. The vector field requires submitting text input to an embedding + // model that converts human-readable text into a vector representation. To convert a text query string provided + // by a user into a vector representation, your application should utilize an embedding library that offers this + // functionality. + indexDocuments(searchClient, getHotelDocuments()); + + // When using 'VectorizableTextQuery', the query for a vector field should be the text that will be vectorized + // based on the 'Vectorizer' configuration in order to perform a vector search. + // + // Let's query the index and make sure everything works as implemented. You can also refer to + // https://learn.microsoft.com/azure/search/vector-search-how-to-query for more information on querying vector + // data. + } + + /** + * Let's consider the example of a 'Hotel'. First, we need to create an index for storing hotel information. In this + * index, we will define vector fields called 'DescriptionVector' and 'CategoryVector'. To configure the vector + * field, you need to provide the model dimensions, which indicate the size of the embeddings generated for this + * field. You can pass reduced dimensions and the name of the vector search profile that specifies the algorithm + * configuration, along with 'Vectorizer'. + *

+ * In order to get the reduced embeddings using either the {@code text-embedding-3-small} or + * {@code text-embedding-3-large} models, it is necessary to include the 'Dimensions' parameter. This parameter + * configures the desired number of dimensions for the output vector. Therefore, for {@link AzureOpenAIVectorizer}, + * we will retrieve the 'VectorSearchDimensions' that is already specified in the corresponding index field + * definition. However, to ensure that dimensions are only passed along in the vectorizer for a model that supports + * it, we need to pass a required property named 'ModelName'. This property enables the service to determine which + * model we are using, and dimensions will only be passed along when it is for a known supported model name. + *

+ * We will create an instace of {@code SearchIndex} and define 'Hotel' fields. + */ + public static SearchIndex defineVectorIndex() { + String vectorSearchProfileName = "my-vector-profile"; + String vectorSearchHnswConfig = "my-hnsw-vector-config"; + String deploymentId = "my-text-embedding-3-small"; + int modelDimensions = 256; // Here's the reduced model dimensions + String indexName = "hotel"; + return new SearchIndex(indexName).setFields(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true), new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true) + .setFilterable(true) + .setSortable(true), + new SearchField("Description", SearchFieldDataType.STRING).setSearchable(true).setFilterable(true), + new SearchField("DescriptionVector", + SearchFieldDataType.collection(SearchFieldDataType.SINGLE)).setSearchable(true) + .setFilterable(true) + .setVectorSearchDimensions(modelDimensions) + .setVectorSearchProfileName(vectorSearchProfileName), + new SearchField("Category", SearchFieldDataType.STRING).setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true), + new SearchField("CategoryVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)).setSearchable( + true) + .setFilterable(true) + .setVectorSearchDimensions(modelDimensions) + .setVectorSearchProfileName(vectorSearchProfileName)) + .setVectorSearch(new VectorSearch().setProfiles( + new VectorSearchProfile(vectorSearchProfileName, vectorSearchHnswConfig).setVectorizer("openai")) + .setAlgorithms(new HnswAlgorithmConfiguration(vectorSearchHnswConfig)) + .setVectorizers(Collections.singletonList(new AzureOpenAIVectorizer("openai").setAzureOpenAIParameters( + new AzureOpenAIParameters().setResourceUri( + Configuration.getGlobalConfiguration().get("OPENAI_ENDPOINT")) + .setApiKey(Configuration.getGlobalConfiguration().get("OPENAI_KEY")) + .setDeploymentId(deploymentId) + .setModelName(AzureOpenAIModelName.TEXT_EMBEDDING3LARGE))))); + } + + public static void createVectorIndex(SearchIndex vectorIndex) { + // Instantiate the 'SearchIndexClient' and call the 'createIndex' method to create the search index. + String endpoint = Configuration.getGlobalConfiguration().get("SEARCH_ENDPOINT"); + String key = Configuration.getGlobalConfiguration().get("SEARCH_API_KEY"); + AzureKeyCredential credential = new AzureKeyCredential(key); + + SearchIndexClient indexClient = new SearchIndexClientBuilder().endpoint(endpoint) + .credential(credential) + .buildClient(); + + indexClient.createIndex(vectorIndex); + } + + // Simple model type for Hotel + + /** + * Hotel model with an additional field for the vector description. + */ + public static final class VectorHotel implements JsonSerializable { + @SimpleField(isKey = true) + private String hotelId; + @SearchableField(isFilterable = true, isSortable = true, analyzerName = "en.lucene") + private String hotelName; + @SearchableField(analyzerName = "en.lucene") + private String description; + @SearchableField(vectorSearchDimensions = 256, vectorSearchProfileName = "my-vector-profile") + private List descriptionVector; + @SearchableField(isFilterable = true, isFacetable = true, isSortable = true) + private String category; + @SearchableField(vectorSearchDimensions = 256, vectorSearchProfileName = "my-vector-profile") + private List categoryVector; + + public VectorHotel() { + } + + public String getHotelId() { + return hotelId; + } + + public VectorHotel setHotelId(String hotelId) { + this.hotelId = hotelId; + return this; + } + + public String getHotelName() { + return hotelName; + } + + public VectorHotel setHotelName(String hotelName) { + this.hotelName = hotelName; + return this; + } + + public String getDescription() { + return description; + } + + public VectorHotel setDescription(String description) { + this.description = description; + return this; + } + + public List getDescriptionVector() { + return descriptionVector == null ? null : Collections.unmodifiableList(descriptionVector); + } + + public VectorHotel setDescriptionVector(List descriptionVector) { + this.descriptionVector = descriptionVector == null ? null : new ArrayList<>(descriptionVector); + return this; + } + + public String getCategory() { + return category; + } + + public VectorHotel setCategory(String category) { + this.category = category; + return this; + } + + public List getCategoryVector() { + return categoryVector == null ? null : Collections.unmodifiableList(categoryVector); + } + + public VectorHotel setCategoryVector(List categoryVector) { + this.categoryVector = categoryVector == null ? null : new ArrayList<>(categoryVector); + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("HotelId", hotelId) + .writeStringField("HotelName", hotelName) + .writeStringField("Description", description) + .writeArrayField("DescriptionVector", descriptionVector, JsonWriter::writeFloat) + .writeStringField("Category", category) + .writeArrayField("DescriptionVector", categoryVector, JsonWriter::writeFloat) + .writeEndObject(); + } + + public static VectorHotel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VectorHotel vectorHotel = new VectorHotel(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("HotelId".equals(fieldName)) { + vectorHotel.hotelId = reader.getString(); + } else if ("HotelName".equals(fieldName)) { + vectorHotel.hotelName = reader.getString(); + } else if ("Description".equals(fieldName)) { + vectorHotel.description = reader.getString(); + } else if ("DescriptionVector".equals(fieldName)) { + vectorHotel.descriptionVector = reader.readArray(JsonReader::getFloat); + } else if ("Category".equals(fieldName)) { + vectorHotel.category = reader.getString(); + } else if ("CategoryVector".equals(fieldName)) { + vectorHotel.categoryVector = reader.readArray(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return vectorHotel; + }); + } + } + + /** + * Get Embeddings using {@code azure-ai-openai} library. + *

+ * You can use Azure OpenAI embedding models, {@code text-embedding-3-small} or {@code text-embedding-3-large}, to + * get the reduced embeddings. With these models, you can specify the desired number of dimensions for the output + * vector by passing the 'Dimensions' property. This enables you to customize the output according to your needs. + *

+ * For more details about how to generate embeddings, refer to the + * documentation. + * Here's an example of how you can get embeddings using + * azure-ai-openai + * library. + */ + public static List getEmbeddings(String input) { + // Get embeddings using Azure OpenAI + String endpoint = Configuration.getGlobalConfiguration().get("OPENAI_ENDPOINT"); + String key = Configuration.getGlobalConfiguration().get("OPENAI_API_KEY"); + KeyCredential credential = new KeyCredential(key); + + OpenAIClient openAIClient = new OpenAIClientBuilder() + .endpoint(endpoint) + .credential(credential) + .buildClient(); + EmbeddingsOptions embeddingsOptions = new EmbeddingsOptions(Collections.singletonList(input)) + .setModel("my-text-embedding-3-small") + .setDimensions(256); + + Embeddings embeddings = openAIClient.getEmbeddings("my-text-embedding-3-small", embeddingsOptions); + return embeddings.getData().get(0).getEmbedding(); + } + + public static List getHotelDocuments() { + // In the sample code below, we are using 'getEmbeddings' method mentioned above to get embeddings for the + // vector fields named 'DescriptionVector' and 'CategoryVector'. + return Arrays.asList( + new VectorHotel().setHotelId("1") + .setHotelName("Fancy Stay") + .setDescription("Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a " + + "spa, and a really helpful concierge. The location is perfect -- right downtown, close to " + + "all the tourist attractions. We highly recommend this hotel.") + .setDescriptionVector(getEmbeddings( + "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, " + + "and a really helpful concierge. The location is perfect -- right downtown, close to all " + + "the tourist attractions. We highly recommend this hotel.")) + .setCategory("Luxury") + .setCategoryVector(getEmbeddings("Luxury")), + new VectorHotel().setHotelId("2") + .setHotelName("Roach Motel") + .setDescription("Cheapest hotel in town. Infact, a motel.") + .setDescriptionVector(getEmbeddings("Cheapest hotel in town. Infact, a motel.")) + .setCategory("Budget") + .setCategoryVector(getEmbeddings("Budget")) + // Add more hotel documents here... + ); + } + + public static void indexDocuments(SearchClient searchClient, List hotelDocuments) { + searchClient.indexDocuments(new IndexDocumentsBatch().addUploadActions(hotelDocuments)); + } + + /** + * In this vector query, the 'VectorQueries' contains the vectorizable text of the query input. The 'Fields' + * property specifies which vector fields are searched. The 'KNearestNeighborsCount' property specifies the number + * of nearest neighbors to return as top hits. + */ + public static void vectorSearch(SearchClient searchClient) { + SearchPagedIterable response = searchClient.search(null, new SearchOptions() + .setVectorSearchOptions(new VectorSearchOptions() + .setQueries(new VectorizableTextQuery("Luxury hotels in town") + .setKNearestNeighborsCount(3) + .setFields("DescriptionVector"))), Context.NONE); + + int count = 0; + System.out.println("Vector Search Results:"); + + for (SearchResult result : response) { + count++; + VectorHotel doc = result.getDocument(VectorHotel.class); + System.out.println(doc.getHotelId() + ": " + doc.getHotelName()); + } + + System.out.println("Total number of search results: " + count); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTests.java index 7aad823cce5f..f01ddf6a69b6 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTests.java @@ -126,7 +126,7 @@ public void ignoredPropertyName() { public void supportedFields() { List fields = SearchIndexClient.buildSearchFields(AllSupportedFields.class, null); - assertEquals(23, fields.size()); + assertEquals(25, fields.size()); Map fieldToDataType = fields.stream() .collect(Collectors.toMap(SearchField::getName, SearchField::getType)); @@ -154,6 +154,9 @@ public void supportedFields() { assertEquals(SearchFieldDataType.INT16, fieldToDataType.get("primitiveShort")); assertEquals(SearchFieldDataType.SBYTE, fieldToDataType.get("nullableByte")); assertEquals(SearchFieldDataType.SBYTE, fieldToDataType.get("primitiveByte")); + assertEquals(SearchFieldDataType.collection(SearchFieldDataType.SBYTE), fieldToDataType.get("byteArray")); + assertEquals(SearchFieldDataType.collection(SearchFieldDataType.SBYTE), fieldToDataType.get("byteList")); + } @SuppressWarnings({"unused", "UseOfObsoleteDateTimeApi"}) @@ -296,6 +299,18 @@ public byte getPrimitiveByte() { public Byte getNullableByte() { return nullableByte; } + + // 24. name = 'byteArray', OData type = COMPLEX + private byte[] byteArray; + public byte[] getByteArray() { + return byteArray; + } + + // 25. name = 'byteList', OData type = COMPLEX + private List byteList; + public List getByteList() { + return byteList; + } } @Test public void validNormalizerField() { diff --git a/sdk/search/azure-search-documents/swagger/README.md b/sdk/search/azure-search-documents/swagger/README.md index 9be65913d502..243c95197879 100644 --- a/sdk/search/azure-search-documents/swagger/README.md +++ b/sdk/search/azure-search-documents/swagger/README.md @@ -216,17 +216,6 @@ directive: return $; ``` -### Rename `maxStoragePerIndex` property to `maxStoragePerIndexInBytes` in ServiceLimits - -``` yaml $(tag) == 'searchservice' -directive: - - from: swagger-document - where: $.definitions.ServiceLimits.properties - transform: > - $.maxStoragePerIndexInBytes = $.maxStoragePerIndex; - delete $.maxStoragePerIndex; -``` - ### Set `hybridSearch` property to be type `HybridSearch` in SearchRequest ``` yaml $(tag) == 'searchindex' @@ -264,6 +253,7 @@ directive: transform: > $.ServiceCounters["x-ms-client-name"] = "SearchServiceCounters"; $.ServiceLimits["x-ms-client-name"] = "SearchServiceLimits"; + $.ServiceLimits.properties.maxStoragePerIndex["x-ms-client-name"] = "maxStoragePerIndexInBytes"; $.ServiceStatistics["x-ms-client-name"] = "SearchServiceStatistics"; ``` @@ -438,3 +428,21 @@ directive: where: $.definitions.VectorQuery.properties.k transform: $["x-ms-client-name"] = "KNearestNeighborsCount"; ``` + +### Rename `AMLVectorizer` to `AzureMachineLearningVectorizer` + +```yaml $(tag) == 'searchservice' +directive: +- from: swagger-document + where: $.definitions.AMLVectorizer + transform: $["x-ms-client-name"] = "AzureMachineLearningVectorizer"; +``` + +### Rename `AMLParameters` to `AzureMachineLearningParameters` + +```yaml $(tag) == 'searchservice' +directive: +- from: swagger-document + where: $.definitions.AMLParameters + transform: $["x-ms-client-name"] = "AzureMachineLearningParameters"; +``` diff --git a/sdk/search/azure-search-perf/pom.xml b/sdk/search/azure-search-perf/pom.xml index 99c82327d705..89de330df1ed 100644 --- a/sdk/search/azure-search-perf/pom.xml +++ b/sdk/search/azure-search-perf/pom.xml @@ -29,7 +29,7 @@ com.azure azure-search-documents - 11.7.0-beta.3 + 11.7.0-beta.4 diff --git a/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml b/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml index 863ce3a617b8..209473483a77 100644 --- a/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml @@ -45,7 +45,7 @@ com.azure azure-messaging-servicebus - 7.17.0-beta.1 + 7.18.0-beta.1 diff --git a/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml b/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml index ddeb33bf3870..d6ac324a524b 100644 --- a/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml @@ -23,7 +23,7 @@ com.azure azure-messaging-servicebus - 7.17.0-beta.1 + 7.18.0-beta.1 com.azure diff --git a/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md b/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md index 62e74ebff15c..34f6139030e7 100644 --- a/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md +++ b/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md @@ -1,18 +1,24 @@ # Release History -## 7.17.0-beta.1 (Unreleased) +## 7.18.0-beta.1 (Unreleased) ### Features Added ### Breaking Changes ### Bugs Fixed - - Fixes the session message disposition to use management node as fall back. ([#39913](https://github.com/Azure/azure-sdk-for-java/issues/ 39913)) - Fixes the session processor idle timeout to fall back to RetryOptions::tryTimeout. ([#39993](https://github.com/Azure/azure-sdk-for-java/issues/39993)) ### Other Changes +## 7.17.0 (2024-05-06) + +### Bugs Fixed + +- Fixes the session message disposition to use management node as fall back. ([#39913](https://github.com/Azure/azure-sdk-for-java/issues/39913)) +- Fixes the session processor idle timeout to fall back to RetryOptions::tryTimeout. ([#39993](https://github.com/Azure/azure-sdk-for-java/issues/39993)) + ## 7.16.0 (2024-04-22) ### Features Added diff --git a/sdk/servicebus/azure-messaging-servicebus/README.md b/sdk/servicebus/azure-messaging-servicebus/README.md index 4cd5ddc50248..227abebb2b8d 100644 --- a/sdk/servicebus/azure-messaging-servicebus/README.md +++ b/sdk/servicebus/azure-messaging-servicebus/README.md @@ -69,7 +69,7 @@ add the direct dependency to your project as follows. com.azure azure-messaging-servicebus - 7.16.0 + 7.17.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/servicebus/azure-messaging-servicebus/docs/pom.xml b/sdk/servicebus/azure-messaging-servicebus/docs/pom.xml index 8940a0bd44d0..1a3222098498 100644 --- a/sdk/servicebus/azure-messaging-servicebus/docs/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus/docs/pom.xml @@ -20,7 +20,7 @@ com.azure azure-messaging-servicebus - 7.17.0-beta.1 + 7.18.0-beta.1 diff --git a/sdk/servicebus/azure-messaging-servicebus/pom.xml b/sdk/servicebus/azure-messaging-servicebus/pom.xml index e0687d632fa7..d316d54174b6 100644 --- a/sdk/servicebus/azure-messaging-servicebus/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus/pom.xml @@ -14,7 +14,7 @@ com.azure azure-messaging-servicebus - 7.17.0-beta.1 + 7.18.0-beta.1 Microsoft Azure client library for Service Bus This package contains the Microsoft Azure Service Bus client library https://github.com/Azure/azure-sdk-for-java diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/FluxTrace.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/FluxTrace.java index 8649598d6f23..a6908ec0f5ec 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/FluxTrace.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/FluxTrace.java @@ -60,7 +60,10 @@ protected void hookOnNext(ServiceBusMessageContext message) { return; } - Context span = instrumentation.startProcessInstrumentation("ServiceBus.process", message.getMessage(), Context.NONE); + Context span = instrumentation.startProcessInstrumentation("ServiceBus.process", + message.getMessage().getApplicationProperties(), + message.getMessage().getEnqueuedTime(), + Context.NONE); message.getMessage().setContext(span); AutoCloseable scope = tracer.makeSpanCurrent(span); try { diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/FluxTraceV2.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/FluxTraceV2.java deleted file mode 100644 index 33c9b3021780..000000000000 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/FluxTraceV2.java +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.messaging.servicebus; - -import com.azure.messaging.servicebus.implementation.instrumentation.ReceiverKind; -import com.azure.messaging.servicebus.implementation.instrumentation.ServiceBusReceiverInstrumentation; -import org.reactivestreams.Subscription; -import reactor.core.CoreSubscriber; -import reactor.core.publisher.BaseSubscriber; -import reactor.core.publisher.Flux; -import reactor.core.publisher.FluxOperator; - -import java.util.Objects; - -/** - * Flux operator that traces receive and process calls - */ -final class FluxTraceV2 extends FluxOperator { - private final ServiceBusReceiverInstrumentation instrumentation; - - FluxTraceV2(Flux upstream, ServiceBusReceiverInstrumentation instrumentation) { - super(upstream); - this.instrumentation = instrumentation; - } - - @Override - public void subscribe(CoreSubscriber coreSubscriber) { - Objects.requireNonNull(coreSubscriber, "'coreSubscriber' cannot be null."); - - source.subscribe(new TracingSubscriber(coreSubscriber, instrumentation)); - } - - private static class TracingSubscriber extends BaseSubscriber { - - private final CoreSubscriber downstream; - private final ServiceBusReceiverInstrumentation instrumentation; - TracingSubscriber(CoreSubscriber downstream, ServiceBusReceiverInstrumentation instrumentation) { - this.downstream = downstream; - this.instrumentation = instrumentation; - } - - @Override - public reactor.util.context.Context currentContext() { - return downstream.currentContext(); - } - - @Override - protected void hookOnSubscribe(Subscription subscription) { - downstream.onSubscribe(this); - } - - @Override - protected void hookOnNext(ServiceBusReceivedMessage message) { - instrumentation.instrumentProcess(message, ReceiverKind.ASYNC_RECEIVER, msg -> { - downstream.onNext(msg); - return null; - }); - } - - @Override - protected void hookOnError(Throwable throwable) { - downstream.onError(throwable); - } - - @Override - protected void hookOnComplete() { - downstream.onComplete(); - } - } -} diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusAsyncConsumer.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusAsyncConsumer.java index 280490f15070..fcddd200a436 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusAsyncConsumer.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusAsyncConsumer.java @@ -49,19 +49,10 @@ class ServiceBusAsyncConsumer implements AutoCloseable { this.linkProcessor = null; this.messageSerializer = messageSerializer; - final boolean useFluxTrace = instrumentation.isEnabled() && instrumentation.isAsyncReceiverInstrumentation(); - if (useFluxTrace) { - // This ServiceBusAsyncConsumer is backing ServiceBusReceiverAsyncClient instance (client has instrumentation is enabled). - final Flux deserialize = messageFlux - .map(message -> this.messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)); - this.processor = new FluxTraceV2(deserialize, instrumentation); - } else { - // This ServiceBusAsyncConsumer is backing either - // 1. a ServiceBusReceiverAsyncClient instance (client has no instrumentation enabled) - // 2. Or a ServiceBusProcessorClient instance (processor client internally deal with instrumentation). - this.processor = messageFlux - .map(message -> this.messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)); - } + // This ServiceBusAsyncConsumer is backing ServiceBusReceiverAsyncClient instance (client has instrumentation is enabled). + final Flux deserialize = messageFlux + .map(message -> this.messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)); + this.processor = TracingFluxOperator.create(deserialize, instrumentation); } /** diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSessionReceiverAsyncClient.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSessionReceiverAsyncClient.java index 9cb63ce4a85f..0e7c2205227a 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSessionReceiverAsyncClient.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSessionReceiverAsyncClient.java @@ -274,7 +274,7 @@ private Mono acquireSpecificOrNextSession(String session, null, receiverOptions.getMaxLockRenewDuration()); final ServiceBusSingleSessionManager sessionManager = new ServiceBusSingleSessionManager(LOGGER, identifier, - sessionReceiver, receiverOptions.getPrefetchCount(), messageSerializer, connectionCacheWrapper.getRetryOptions()); + sessionReceiver, receiverOptions.getPrefetchCount(), messageSerializer, connectionCacheWrapper.getRetryOptions(), instrumentation); final ReceiverOptions newReceiverOptions = createNamedSessionOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), receiverOptions.getMaxLockRenewDuration(), diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSingleSessionManager.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSingleSessionManager.java index 702ac378cc5d..cccad6ed8d4d 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSingleSessionManager.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSingleSessionManager.java @@ -11,7 +11,9 @@ import com.azure.core.util.logging.LoggingEventBuilder; import com.azure.messaging.servicebus.implementation.DispositionStatus; import com.azure.messaging.servicebus.implementation.MessageUtils; +import com.azure.messaging.servicebus.implementation.instrumentation.ServiceBusReceiverInstrumentation; import org.apache.qpid.proton.amqp.transport.DeliveryState; +import org.apache.qpid.proton.message.Message; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; import reactor.core.publisher.Mono; @@ -34,11 +36,12 @@ final class ServiceBusSingleSessionManager implements IServiceBusSessionManager private final MessageSerializer serializer; private final Duration operationTimeout; private final ServiceBusSessionReactorReceiver sessionReceiver; - private final MessageFlux messageFlux; + private final Flux messageFlux; + private final ServiceBusReceiverInstrumentation instrumentation; ServiceBusSingleSessionManager(ClientLogger logger, String identifier, ServiceBusSessionReactorReceiver sessionReceiver, int prefetch, - MessageSerializer serializer, AmqpRetryOptions retryOptions) { + MessageSerializer serializer, AmqpRetryOptions retryOptions, ServiceBusReceiverInstrumentation instrumentation) { this.logger = Objects.requireNonNull(logger, "logger cannot be null."); this.identifier = identifier; this.sessionReceiver = Objects.requireNonNull(sessionReceiver, "sessionReceiver cannot be null."); @@ -46,7 +49,10 @@ final class ServiceBusSingleSessionManager implements IServiceBusSessionManager Objects.requireNonNull(retryOptions, "retryOptions cannot be null."); this.operationTimeout = retryOptions.getTryTimeout(); final Flux messageFluxUpstream = new SessionReceiverStream(sessionReceiver).flux(); - this.messageFlux = new MessageFlux(messageFluxUpstream, prefetch, CreditFlowMode.RequestDriven, NULL_RETRY_POLICY); + this.instrumentation = Objects.requireNonNull(instrumentation, "instrumentation cannot be null"); + MessageFlux messageFluxLocal = new MessageFlux(messageFluxUpstream, prefetch, CreditFlowMode.RequestDriven, + NULL_RETRY_POLICY); + this.messageFlux = TracingFluxOperator.create(messageFluxLocal, instrumentation); } @Override diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/SessionsMessagePump.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/SessionsMessagePump.java index 2afe6d63cedc..fb3bb5d6e403 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/SessionsMessagePump.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/SessionsMessagePump.java @@ -177,7 +177,7 @@ final class SessionsMessagePump { this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null."); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null."); this.onTerminate = Objects.requireNonNull(onTerminate, "'onTerminate' cannot be null."); - this.receiversTracker = new SessionReceiversTracker(logger, maxConcurrentSessions, fullyQualifiedNamespace, entityPath, receiveMode); + this.receiversTracker = new SessionReceiversTracker(logger, maxConcurrentSessions, fullyQualifiedNamespace, entityPath, receiveMode, instrumentation); this.nextSession = new NextSession(pumpId, fullyQualifiedNamespace, entityPath, sessionAcquirer).mono(); } @@ -645,14 +645,16 @@ static final class SessionReceiversTracker { private final String entityPath; private final ServiceBusReceiveMode receiveMode; private final ConcurrentHashMap receivers; + private final ServiceBusReceiverInstrumentation instrumentation; private SessionReceiversTracker(ClientLogger logger, int size, String fullyQualifiedNamespace, String entityPath, - ServiceBusReceiveMode receiveMode) { + ServiceBusReceiveMode receiveMode, ServiceBusReceiverInstrumentation instrumentation) { this.logger = logger; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.entityPath = entityPath; this.receiveMode = receiveMode; this.receivers = new ConcurrentHashMap<>(size); + this.instrumentation = instrumentation; } private void track(ServiceBusSessionReactorReceiver receiver) { @@ -749,11 +751,14 @@ private Mono updateDisposition(ServiceBusReceivedMessage message, Disposit final ServiceBusSessionReactorReceiver receiver = receivers.get(sessionId); final DeliveryState deliveryState = MessageUtils.getDeliveryState(dispositionStatus, deadLetterReason, deadLetterDescription, propertiesToModify, transactionContext); + + Mono updateDispositionMono; if (receiver != null) { - return receiver.updateDisposition(message.getLockToken(), deliveryState); + updateDispositionMono = receiver.updateDisposition(message.getLockToken(), deliveryState); } else { - return Mono.error(DeliveryNotOnLinkException.noMatchingDelivery(message.getLockToken(), deliveryState)); + updateDispositionMono = Mono.error(DeliveryNotOnLinkException.noMatchingDelivery(message.getLockToken(), deliveryState)); } + return instrumentation.instrumentSettlement(updateDispositionMono, message, message.getContext(), dispositionStatus); } private Mono checkNull(Object options, ServiceBusTransactionContext transactionContext) { diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/TracingFluxOperator.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/TracingFluxOperator.java new file mode 100644 index 000000000000..830f52086389 --- /dev/null +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/TracingFluxOperator.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.servicebus; + +import com.azure.messaging.servicebus.implementation.instrumentation.ReceiverKind; +import com.azure.messaging.servicebus.implementation.instrumentation.ServiceBusReceiverInstrumentation; +import org.apache.qpid.proton.message.Message; +import org.reactivestreams.Subscription; +import reactor.core.CoreSubscriber; +import reactor.core.publisher.BaseSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.publisher.FluxOperator; + +import java.util.Objects; +import java.util.function.BiConsumer; +import java.util.function.Function; + +/** + * Flux operator that traces receive and process calls + */ +final class TracingFluxOperator extends BaseSubscriber { + + public static Flux create(Flux upstream, ServiceBusReceiverInstrumentation instrumentation) { + if (!instrumentation.isEnabled() && instrumentation.isAsyncReceiverInstrumentation()) { + return upstream; + } + + return new FluxOperator(upstream) { + @SuppressWarnings("unchecked") + @Override + public void subscribe(CoreSubscriber actual) { + Objects.requireNonNull(actual, "'actual' cannot be null."); + source.subscribe(new TracingFluxOperator(actual, (msg, handler) -> { + if (msg instanceof Message) { + instrumentation.instrumentProcess((Message) msg, ReceiverKind.ASYNC_RECEIVER, + (Function) handler); + } else if (msg instanceof ServiceBusReceivedMessage) { + instrumentation.instrumentProcess((ServiceBusReceivedMessage) msg, ReceiverKind.ASYNC_RECEIVER, + (Function) handler); + } + })); + } + }; + } + + private final CoreSubscriber downstream; + private final BiConsumer> instrumentation; + private TracingFluxOperator(CoreSubscriber downstream, BiConsumer> instrumentation) { + this.downstream = downstream; + this.instrumentation = instrumentation; + } + + @Override + public reactor.util.context.Context currentContext() { + return downstream.currentContext(); + } + + @Override + protected void hookOnSubscribe(Subscription subscription) { + downstream.onSubscribe(this); + } + + @Override + protected void hookOnNext(T message) { + instrumentation.accept(message, msg -> { + downstream.onNext(msg); + return null; + }); + } + + @Override + protected void hookOnError(Throwable throwable) { + downstream.onError(throwable); + } + + @Override + protected void hookOnComplete() { + downstream.onComplete(); + } +} + diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusReceiverInstrumentation.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusReceiverInstrumentation.java index 5cb4616c97bd..cb54adcb41a2 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusReceiverInstrumentation.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusReceiverInstrumentation.java @@ -8,16 +8,25 @@ import com.azure.core.util.tracing.Tracer; import com.azure.messaging.servicebus.ServiceBusReceivedMessage; import com.azure.messaging.servicebus.implementation.DispositionStatus; +import org.apache.qpid.proton.amqp.Symbol; +import org.apache.qpid.proton.message.Message; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.Map; import java.util.function.Function; +import static com.azure.core.amqp.AmqpMessageConstant.ENQUEUED_TIME_UTC_ANNOTATION_NAME; + /** * Contains convenience methods to instrument specific calls with traces and metrics. */ public final class ServiceBusReceiverInstrumentation { + private static final Symbol ENQUEUED_TIME_SYMBOL = Symbol.getSymbol(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); private final ServiceBusMeter meter; private final ServiceBusTracer tracer; private final ReceiverKind receiverKind; @@ -67,37 +76,44 @@ public boolean isAsyncReceiverInstrumentation() { * for sync receiver. * Reports consumer lag metric. */ - public Context startProcessInstrumentation(String name, ServiceBusReceivedMessage message, Context parent) { - if (message == null || (!tracer.isEnabled() && !meter.isConsumerLagEnabled())) { + public Context startProcessInstrumentation(String name, Map applicationProperties, + OffsetDateTime enqueuedTime, Context parent) { + if (applicationProperties == null || (!tracer.isEnabled() && !meter.isConsumerLagEnabled())) { return parent; } - Context span = (tracer.isEnabled() && receiverKind != ReceiverKind.SYNC_RECEIVER) ? tracer.startProcessSpan(name, message, parent) : parent; + Context span = (tracer.isEnabled() && receiverKind != ReceiverKind.SYNC_RECEIVER) + ? tracer.startProcessSpan(name, applicationProperties, enqueuedTime, parent) + : parent; // important to record metric after span is started - meter.reportConsumerLag(message.getEnqueuedTime(), span); + meter.reportConsumerLag(enqueuedTime, span); return span; } public void instrumentProcess(ServiceBusReceivedMessage message, ReceiverKind caller, Function handleMessage) { - if (receiverKind != caller) { + if (receiverKind != caller || message == null) { handleMessage.apply(message); return; } - Context span = startProcessInstrumentation("ServiceBus.process", message, Context.NONE); + Context span = startProcessInstrumentation("ServiceBus.process", message.getApplicationProperties(), + message.getEnqueuedTime(), Context.NONE); ContextAccessor.setContext(message, span); - AutoCloseable scope = tracer.makeSpanCurrent(span); - Throwable error = null; - try { - error = handleMessage.apply(message); - } catch (Throwable t) { - error = t; - throw t; - } finally { - tracer.endSpan(error, span, scope); + wrap(span, message, handleMessage); + } + + public void instrumentProcess(Message message, ReceiverKind caller, Function handleMessage) { + if (receiverKind != caller || message == null || message.getApplicationProperties() == null) { + handleMessage.apply(message); + return; } + + Context span = startProcessInstrumentation("ServiceBus.process", message.getApplicationProperties().getValue(), + getEnqueuedTime(message), Context.NONE); + //ContextAccessor.setContext(message, span); + wrap(span, message, handleMessage); } /** @@ -145,4 +161,30 @@ private static String getSettlementSpanName(DispositionStatus status) { return "ServiceBus.unknown"; } } + + private void wrap(Context span, T message, Function handleMessage) { + AutoCloseable scope = tracer.makeSpanCurrent(span); + Throwable error = null; + try { + error = handleMessage.apply(message); + } catch (Throwable t) { + error = t; + throw t; + } finally { + tracer.endSpan(error, span, scope); + } + } + + private OffsetDateTime getEnqueuedTime(Message message) { + if (message.getMessageAnnotations() == null || message.getMessageAnnotations().getValue() == null) { + return null; + } + + Object date = message.getMessageAnnotations().getValue().get(ENQUEUED_TIME_SYMBOL); + if (date instanceof Date) { + return ((Date) date).toInstant().atOffset(ZoneOffset.UTC); + } + + return null; + } } diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusTracer.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusTracer.java index 4f24630ec75f..532a71a249f0 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusTracer.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusTracer.java @@ -285,13 +285,13 @@ Context startSpanWithLink(String spanName, OperationName operationName, ServiceB /** * Starts span. Used by ServiceBus*Instrumentations. */ - Context startProcessSpan(String spanName, ServiceBusReceivedMessage message, Context parent) { - if (isEnabled() && message != null) { + Context startProcessSpan(String spanName, Map applicationProperties, OffsetDateTime enqueuedTime, Context parent) { + if (isEnabled() && applicationProperties != null) { StartSpanOptions startOptions = createStartOption(SpanKind.CONSUMER, OperationName.PROCESS) - .setRemoteParent(extractContext(message.getApplicationProperties())); + .setRemoteParent(extractContext(applicationProperties)); - if (message.getEnqueuedTime() != null) { - startOptions.setAttribute(MESSAGE_ENQUEUED_TIME_ATTRIBUTE_NAME, message.getEnqueuedTime().toEpochSecond()); + if (enqueuedTime != null) { + startOptions.setAttribute(MESSAGE_ENQUEUED_TIME_ATTRIBUTE_NAME, enqueuedTime.toEpochSecond()); } return tracer.start(spanName, startOptions, parent); diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ProxySelectorTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ProxySelectorTest.java index 7047f8138369..1dff7bec6184 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ProxySelectorTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ProxySelectorTest.java @@ -7,6 +7,7 @@ import com.azure.core.amqp.AmqpTransportType; import com.azure.core.util.BinaryData; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -25,6 +26,8 @@ import java.util.concurrent.TimeUnit; public class ProxySelectorTest extends IntegrationTestBase { + private static final ClientLogger LOGGER = new ClientLogger(ProxySelectorTest.class); + private static final int PROXY_PORT = 9002; private static final InetSocketAddress SIMPLE_PROXY_ADDRESS = new InetSocketAddress("localhost", PROXY_PORT); private ProxySelector defaultProxySelector; @@ -78,7 +81,7 @@ public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { .expectErrorSatisfies(error -> { // The message can vary because it is returned from proton-j, so we don't want to compare against that. // This is a transient error from ExceptionUtil.java: line 67. - System.out.println("Error: " + error); + LOGGER.log(LogLevel.VERBOSE, () -> "Error", error); }) .verify(TIMEOUT); diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ReceiveLinkTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ReceiveLinkTest.java index 033b74509fed..98b6c3f71787 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ReceiveLinkTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ReceiveLinkTest.java @@ -4,6 +4,8 @@ import com.azure.core.amqp.AmqpEndpointState; import com.azure.core.amqp.implementation.AmqpReceiveLink; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import org.junit.jupiter.api.AfterEach; import org.mockito.Mockito; import reactor.core.publisher.Flux; @@ -21,6 +23,8 @@ import static org.mockito.Mockito.when; public class ReceiveLinkTest { + private static final ClientLogger LOGGER = new ClientLogger(ReceiveLinkTest.class); + private final AtomicInteger counter = new AtomicInteger(); private final AmqpReceiveLink[] allLinks = new AmqpReceiveLink[4]; @@ -47,7 +51,7 @@ public void verifyCreation() { when(link2.getLinkName()).thenReturn("link2-name"); when(link2.getEndpointStates()).thenAnswer(invocation -> { - System.out.println("link2-name endpoints"); + LOGGER.log(LogLevel.VERBOSE, () -> "link2-name endpoints"); return Flux.create(sink -> { sink.onRequest(r -> sink.next(AmqpEndpointState.UNINITIALIZED)); @@ -56,7 +60,7 @@ public void verifyCreation() { when(link3.getLinkName()).thenReturn("link3-name"); when(link3.getEndpointStates()).thenAnswer(invocation -> { - System.out.println("link3-name endpoints"); + LOGGER.log(LogLevel.VERBOSE, () -> "link3-name endpoints"); return Flux.create(sink -> { // Emit uninitialized first. After 3 seconds, emit ACTIVE. sink.onRequest(r -> { @@ -88,7 +92,7 @@ private Mono getActiveLink() { }) .retryWhen(Retry.from(retrySignals -> retrySignals.flatMap(signal -> { final Throwable failure = signal.failure(); - System.err.printf(" Retry: %s. Error occurred while waiting: %s%n", signal.totalRetriesInARow(), failure); + LOGGER.verbose(" Retry: {}. Error occurred while waiting: {}", signal.totalRetriesInARow(), failure); if (failure instanceof TimeoutException) { return Mono.delay(Duration.ofSeconds(4)); } else { @@ -100,7 +104,7 @@ private Mono getActiveLink() { private Mono createReceiveLink() { int index = counter.getAndIncrement(); - System.out.println("Index: " + index); + LOGGER.log(LogLevel.VERBOSE, () -> "Index: " + index); if (index < allLinks.length) { return Mono.just(allLinks[index]); } else { diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusMixClientIntegrationTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusMixClientIntegrationTest.java index 0b46e7fb5473..9709bc8f7726 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusMixClientIntegrationTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusMixClientIntegrationTest.java @@ -4,6 +4,7 @@ package com.azure.messaging.servicebus; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.servicebus.implementation.MessagingEntityType; import com.azure.messaging.servicebus.models.CompleteOptions; import com.azure.messaging.servicebus.models.ServiceBusReceiveMode; @@ -28,6 +29,8 @@ * Test where various clients are involved for example Sender, Receiver and Processor client. */ public class ServiceBusMixClientIntegrationTest extends IntegrationTestBase { + private static final ClientLogger LOGGER = new ClientLogger(ServiceBusMixClientIntegrationTest.class); + private ServiceBusSenderAsyncClient sender; private ServiceBusReceiverAsyncClient receiver; private final AtomicInteger messagesPending = new AtomicInteger(); @@ -106,7 +109,7 @@ void crossEntityQueueTransaction(boolean isSessionEnabled) throws InterruptedExc receivedMessages.incrementAndGet(); messagesPending.incrementAndGet(); ServiceBusReceivedMessage myMessage = context.getMessage(); - System.out.printf("Processing message. MessageId: %s, Sequence #: %s. Contents: %s %n", myMessage.getMessageId(), + LOGGER.verbose("Processing message. MessageId: {}, Sequence #: {}. Contents: {}", myMessage.getMessageId(), myMessage.getSequenceNumber(), myMessage.getBody()); if (receivedMessages.get() == 1) { @@ -122,12 +125,12 @@ void crossEntityQueueTransaction(boolean isSessionEnabled) throws InterruptedExc }; Consumer processError = context -> { - System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'. Error Source: '%s' %n", + LOGGER.verbose("Error when receiving messages from namespace: '{}'. Entity: '{}'. Error Source: '{}'", context.getFullyQualifiedNamespace(), context.getEntityPath(), context.getErrorSource()); Assertions.fail("Failed processing of message.", context.getException()); if (!(context.getException() instanceof ServiceBusException)) { - System.out.printf("Non-ServiceBusException occurred: %s%n", context.getException()); + LOGGER.log(LogLevel.VERBOSE, () -> "Non-ServiceBusException occurred: " + context.getException()); } }; @@ -150,17 +153,17 @@ void crossEntityQueueTransaction(boolean isSessionEnabled) throws InterruptedExc // Create an instance of the processor through the ServiceBusClientBuilder // Act - System.out.println("Starting the processor"); + LOGGER.log(LogLevel.VERBOSE, () -> "Starting the processor"); processorA.start(); toClose((AutoCloseable) () -> processorA.stop()); // Assert - System.out.println("Listening for 10 seconds..."); + LOGGER.log(LogLevel.VERBOSE, () -> "Listening for 10 seconds..."); if (countdownLatch.await(10, TimeUnit.SECONDS)) { - System.out.println("Completed processing successfully."); + LOGGER.log(LogLevel.VERBOSE, () -> "Completed processing successfully."); Assertions.assertTrue(transactionComplete.get()); } else { - System.out.println("Closing processor."); + LOGGER.log(LogLevel.VERBOSE, () -> "Closing processor."); Assertions.fail("Failed to process message."); } @@ -216,7 +219,7 @@ void crossEntitySubscriptionTransaction(boolean isSessionEnabled) throws Interru receivedMessages.incrementAndGet(); messagesPending.incrementAndGet(); ServiceBusReceivedMessage myMessage = context.getMessage(); - System.out.printf("Processing message. MessageId: %s, Sequence #: %s. Contents: %s %n", myMessage.getMessageId(), + LOGGER.verbose("Processing message. MessageId: {}, Sequence #: {}. Contents: {}", myMessage.getMessageId(), myMessage.getSequenceNumber(), myMessage.getBody()); if (receivedMessages.get() == 1) { @@ -232,12 +235,12 @@ void crossEntitySubscriptionTransaction(boolean isSessionEnabled) throws Interru }; Consumer processError = context -> { - System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'. Error Source: '%s' %n", + LOGGER.verbose("Error when receiving messages from namespace: '{}'. Entity: '{}'. Error Source: '{}'", context.getFullyQualifiedNamespace(), context.getEntityPath(), context.getErrorSource()); Assertions.fail("Failed processing of message.", context.getException()); if (!(context.getException() instanceof ServiceBusException)) { - System.out.printf("Non-ServiceBusException occurred: %s%n", context.getException()); + LOGGER.log(LogLevel.VERBOSE, () -> "Non-ServiceBusException occurred: " + context.getException()); } }; @@ -268,17 +271,17 @@ void crossEntitySubscriptionTransaction(boolean isSessionEnabled) throws Interru // Create an instance of the processor through the ServiceBusClientBuilder // Act - System.out.println("Starting the processor"); + LOGGER.log(LogLevel.VERBOSE, () -> "Starting the processor"); processorA.start(); toClose((AutoCloseable) () -> processorA.stop()); // Assert - System.out.println("Listening for 10 seconds..."); + LOGGER.log(LogLevel.VERBOSE, () -> "Listening for 10 seconds..."); if (countdownLatch.await(10, TimeUnit.SECONDS)) { - System.out.println("Completed processing successfully."); + LOGGER.log(LogLevel.VERBOSE, () -> "Completed processing successfully."); Assertions.assertTrue(transactionComplete.get()); } else { - System.out.println("Closing processor."); + LOGGER.log(LogLevel.VERBOSE, () -> "Closing processor."); Assertions.fail("Failed to process message."); } @@ -361,12 +364,12 @@ void crossEntityQueueTransactionWithReceiverSenderTest(boolean isSessionEnabled) toClose(subscription); // Act - System.out.println("Listening for 10 seconds..."); + LOGGER.log(LogLevel.VERBOSE, () -> "Listening for 10 seconds..."); if (countdownLatch.await(10, TimeUnit.SECONDS)) { - System.out.println("Completed message processing successfully."); + LOGGER.log(LogLevel.VERBOSE, () -> "Completed message processing successfully."); Assertions.assertTrue(transactionComplete.get()); } else { - System.out.println("Some error."); + LOGGER.log(LogLevel.VERBOSE, () -> "Some error."); Assertions.fail("Failed to process message."); } @@ -447,12 +450,12 @@ void crossEntitySubscriptionTransactionWithReceiverSenderTest(boolean isSessionE }).subscribe(); toClose(subscription); // Act - System.out.println("Listening for 10 seconds..."); + LOGGER.log(LogLevel.VERBOSE, () -> "Listening for 10 seconds..."); if (countdownLatch.await(10, TimeUnit.SECONDS)) { - System.out.println("Completed message processing successfully."); + LOGGER.log(LogLevel.VERBOSE, () -> "Completed message processing successfully."); Assertions.assertTrue(transactionComplete.get()); } else { - System.out.println("Some error."); + LOGGER.log(LogLevel.VERBOSE, () -> "Some error."); Assertions.fail("Failed to process message."); } diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusReceiverAsyncClientTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusReceiverAsyncClientTest.java index 42052a460dc0..4686edf67643 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusReceiverAsyncClientTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusReceiverAsyncClientTest.java @@ -24,6 +24,7 @@ import com.azure.core.util.ClientOptions; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.core.util.tracing.StartSpanOptions; import com.azure.core.util.tracing.Tracer; import com.azure.messaging.servicebus.ServiceBusClientBuilder.ServiceBusReceiverClientBuilder; @@ -1317,13 +1318,14 @@ void autoCompleteMessage(boolean isV2) { try { // Act & Assert - StepVerifier.create(receiver2.receiveMessages().take(numberOfEvents).doOnComplete(() -> System.out.println("take complete.."))) + StepVerifier.create(receiver2.receiveMessages().take(numberOfEvents) + .doOnComplete(() -> LOGGER.log(LogLevel.VERBOSE, () -> "take complete.."))) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .expectComplete() .verify(DEFAULT_TIMEOUT); } finally { - System.out.println("CLOSING...."); + LOGGER.log(LogLevel.VERBOSE, () -> "CLOSING...."); receiver2.close(); } diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSenderAsyncClientIntegrationTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSenderAsyncClientIntegrationTest.java index 2da9dc8d8788..d62e825e3a4d 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSenderAsyncClientIntegrationTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSenderAsyncClientIntegrationTest.java @@ -4,6 +4,7 @@ package com.azure.messaging.servicebus; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.servicebus.implementation.MessagingEntityType; import com.azure.messaging.servicebus.models.CreateMessageBatchOptions; import com.azure.messaging.servicebus.models.ServiceBusReceiveMode; @@ -35,6 +36,8 @@ */ @Tag("integration") class ServiceBusSenderAsyncClientIntegrationTest extends IntegrationTestBase { + private static final ClientLogger LOGGER = new ClientLogger(ServiceBusSenderAsyncClientIntegrationTest.class); + private ServiceBusSenderAsyncClient sender; private ServiceBusReceiverAsyncClient receiver; private final AtomicInteger messagesPending = new AtomicInteger(); @@ -358,17 +361,17 @@ void transactionMessageSendAndCompleteTransaction(MessagingEntityType entityType .verify(TIMEOUT); StepVerifier.create(receiver.receiveMessages().take(total)) .assertNext(receivedMessage -> { - System.out.println("1"); + LOGGER.log(LogLevel.VERBOSE, () -> "1"); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .assertNext(receivedMessage -> { - System.out.println("2"); + LOGGER.log(LogLevel.VERBOSE, () -> "2"); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .assertNext(receivedMessage -> { - System.out.println("3"); + LOGGER.log(LogLevel.VERBOSE, () -> "3"); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSessionManagerTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSessionManagerTest.java index 05804738519f..aa93866c66fd 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSessionManagerTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSessionManagerTest.java @@ -13,6 +13,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.util.ClientOptions; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.servicebus.implementation.MessagingEntityType; import com.azure.messaging.servicebus.implementation.ServiceBusAmqpConnection; import com.azure.messaging.servicebus.implementation.ServiceBusConnectionProcessor; @@ -382,23 +383,23 @@ void multipleSessions() { } }) .assertNext(context -> { - System.out.println("1"); + LOGGER.log(LogLevel.VERBOSE, () -> "1"); assertMessageEquals(sessionId, receivedMessage, context); }) .assertNext(context -> { - System.out.println("2"); + LOGGER.log(LogLevel.VERBOSE, () -> "2"); assertMessageEquals(sessionId, receivedMessage, context); }) .assertNext(context -> { - System.out.println("3"); + LOGGER.log(LogLevel.VERBOSE, () -> "3"); assertMessageEquals(sessionId, receivedMessage, context); }) .assertNext(context -> { - System.out.println("4"); + LOGGER.log(LogLevel.VERBOSE, () -> "4"); assertMessageEquals(sessionId, receivedMessage, context); }) .assertNext(context -> { - System.out.println("5"); + LOGGER.log(LogLevel.VERBOSE, () -> "5"); assertMessageEquals(sessionId, receivedMessage, context); }) .thenAwait(Duration.ofSeconds(13)) @@ -408,15 +409,15 @@ void multipleSessions() { } }) .assertNext(context -> { - System.out.println("6"); + LOGGER.log(LogLevel.VERBOSE, () -> "6"); assertMessageEquals(sessionId2, receivedMessage2, context); }) .assertNext(context -> { - System.out.println("7"); + LOGGER.log(LogLevel.VERBOSE, () -> "7"); assertMessageEquals(sessionId2, receivedMessage2, context); }) .assertNext(context -> { - System.out.println("8"); + LOGGER.log(LogLevel.VERBOSE, () -> "8"); assertMessageEquals(sessionId2, receivedMessage2, context); }) .thenAwait(Duration.ofSeconds(15)) diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/TestUtils.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/TestUtils.java index 6416b0409ef5..8531bdedeb7a 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/TestUtils.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/TestUtils.java @@ -8,6 +8,8 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.servicebus.administration.models.AccessRights; import com.azure.messaging.servicebus.administration.models.AuthorizationRule; import org.apache.qpid.proton.Proton; @@ -46,6 +48,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class TestUtils { + private static final ClientLogger LOGGER = new ClientLogger(TestUtils.class); // System and application properties from the generated test message. static final Instant ENQUEUED_TIME = Instant.ofEpochSecond(1561344661); @@ -145,7 +148,7 @@ public static String getConnectionString(boolean withSas) { } return String.format(connectionStringWithSasAndEntityFormat, endpoint, signatureValue, entityPath); } catch (Exception e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Error while getting connection string", e); } } return connectionString; diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/TracingIntegrationTests.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/TracingIntegrationTests.java index 7a50929d25f9..6bc5730921d2 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/TracingIntegrationTests.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/TracingIntegrationTests.java @@ -592,6 +592,62 @@ public void sendAndProcessNoAutoComplete() throws InterruptedException { assertSettledVsProcessed(completed, processed, 1); } + @Test + public void sendAndProcessSessionNoAutoComplete() throws InterruptedException { + String sessionQueueName = getSessionQueueName(0); + String sessionId = UUID.randomUUID().toString(); + ServiceBusMessage message = new ServiceBusMessage(CONTENTS_BYTES).setSessionId(sessionId); + + OpenTelemetry otel = configureOTel(getFullyQualifiedDomainName(), sessionQueueName); + clientOptions = new ClientOptions().setTracingOptions(new OpenTelemetryTracingOptions().setOpenTelemetry(otel)); + sender = toClose(new ServiceBusClientBuilder() + .connectionString(getConnectionString()) + .clientOptions(clientOptions) + .sender() + .queueName(sessionQueueName) + .buildAsyncClient()); + + StepVerifier.create(sender.sendMessage(message)).expectComplete().verify(TIMEOUT); + + CountDownLatch processFound = new CountDownLatch(2); + spanProcessor.notifyIfCondition(processFound, span -> span.getName().equals("ServiceBus.process") || span.getName().equals("ServiceBus.complete")); + + AtomicReference currentInProcess = new AtomicReference<>(); + AtomicReference receivedMessage = new AtomicReference<>(); + processor = toClose(new ServiceBusClientBuilder() + .connectionString(getConnectionString()) + .clientOptions(clientOptions) + .sessionProcessor() + .maxConcurrentSessions(1) + .queueName(sessionQueueName) + .disableAutoComplete() + .processMessage(mc -> { + currentInProcess.compareAndSet(null, Span.current()); + receivedMessage.compareAndSet(null, mc.getMessage()); + mc.complete(); + }) + .processError(e -> fail("unexpected error", e.getException())) + .buildProcessorClient()); + + toClose((AutoCloseable) () -> processor.stop()); + processor.start(); + assertTrue(processFound.await(20, TimeUnit.SECONDS)); + processor.stop(); + + assertTrue(currentInProcess.get().getSpanContext().isValid()); + List spans = spanProcessor.getEndedSpans(); + + List processed = findSpans(spans, "ServiceBus.process") + .stream().filter(p -> p.equals(currentInProcess.get())).collect(Collectors.toList()); + assertEquals(1, processed.size()); + assertConsumerSpan(processed.get(0), receivedMessage.get(), "ServiceBus.process"); + + List completed = findSpans(spans, "ServiceBus.complete"); + assertEquals(1, completed.size()); + assertClientSpan(completed.get(0), Collections.singletonList(receivedMessage.get()), "ServiceBus.complete", "settle"); + assertSettledVsProcessed(completed, processed, 1); + } + @Test public void sendAndProcessParallel() throws InterruptedException { int messageCount = 10; diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/ServiceBusReceiveLinkProcessorTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/ServiceBusReceiveLinkProcessorTest.java index 3f108c6b6678..66720fb5fd24 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/ServiceBusReceiveLinkProcessorTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/ServiceBusReceiveLinkProcessorTest.java @@ -7,6 +7,8 @@ import com.azure.core.amqp.exception.AmqpErrorCondition; import com.azure.core.amqp.exception.AmqpErrorContext; import com.azure.core.amqp.exception.AmqpException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import org.apache.qpid.proton.amqp.transport.DeliveryState; import org.apache.qpid.proton.message.Message; import org.junit.jupiter.api.AfterEach; @@ -36,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -55,6 +58,8 @@ * Tests for {@link ServiceBusReceiveLinkProcessor}. */ class ServiceBusReceiveLinkProcessorTest { + private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiveLinkProcessorTest.class); + private static final int PREFETCH = 5; @Mock private ServiceBusReceiveLink link1; @@ -172,9 +177,9 @@ void respectsBackpressureLessThanMinimum() throws InterruptedException { // Act semaphore.acquire(); processor.subscribe( - e -> System.out.println("message: " + e), + e -> LOGGER.log(LogLevel.VERBOSE, () -> "message: " + e), Assertions::fail, - () -> System.out.println("Complete."), + () -> LOGGER.log(LogLevel.VERBOSE, () -> "Complete."), s -> { s.request(backpressure); semaphore.release(); @@ -262,9 +267,7 @@ void newLinkOnClose() { }) .expectNext(message3) .expectNext(message4) - .then(() -> { - processor.cancel(); - }) + .then(processor::cancel) .verifyComplete(); assertTrue(processor.isTerminated()); @@ -336,12 +339,12 @@ void nonRetryableError() { // Verify that we get the first connection. StepVerifier.create(processor) .then(() -> { - System.out.println("Outputting exception."); + LOGGER.log(LogLevel.VERBOSE, () -> "Outputting exception."); endpointProcessor.error(amqpException); }) .expectErrorSatisfies(error -> { - System.out.println("Asserting exception."); - assertTrue(error instanceof AmqpException); + LOGGER.log(LogLevel.VERBOSE, () -> "Asserting exception."); + assertInstanceOf(AmqpException.class, error); AmqpException exception = (AmqpException) error; assertFalse(exception.isTransient()); diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusReceiverInstrumentationTests.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusReceiverInstrumentationTests.java index 46597b57f963..55766945d4e4 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusReceiverInstrumentationTests.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/instrumentation/ServiceBusReceiverInstrumentationTests.java @@ -35,7 +35,7 @@ public void testInstrumentNullMessageNoMeter() { ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(tracer, null, "fqdn", "entityPath", null, ReceiverKind.ASYNC_RECEIVER); - instrumentation.startProcessInstrumentation("span name", null, Context.NONE); + instrumentation.startProcessInstrumentation("span name", null, null, Context.NONE); instrumentation.instrumentSettlement(Mono.just(1), null, Context.NONE, DispositionStatus.ABANDONED); verify(tracer, never()).start(anyString(), any(StartSpanOptions.class), any(Context.class)); } @@ -48,7 +48,7 @@ public void testInstrumentNullMessageNoTracer() { "fqdn", "entityPath", null, ReceiverKind.ASYNC_RECEIVER); // does not throw - instrumentation.startProcessInstrumentation("span name", null, Context.NONE); + instrumentation.startProcessInstrumentation("span name", null, null, Context.NONE); instrumentation.instrumentSettlement(Mono.just(1), null, Context.NONE, DispositionStatus.ABANDONED); } @@ -58,7 +58,7 @@ public void testInstrumentNullMessageDisabled() { "fqdn", "entityPath", null, ReceiverKind.ASYNC_RECEIVER); // does not throw - instrumentation.startProcessInstrumentation("span name", null, Context.NONE); + instrumentation.startProcessInstrumentation("span name", null, null, Context.NONE); instrumentation.instrumentSettlement(Mono.just(1), null, Context.NONE, DispositionStatus.ABANDONED); } } diff --git a/sdk/spring/CHANGELOG.md b/sdk/spring/CHANGELOG.md index 86a39eb52077..e9cff45da533 100644 --- a/sdk/spring/CHANGELOG.md +++ b/sdk/spring/CHANGELOG.md @@ -1,5 +1,18 @@ # Release History +## 4.18.0 (2024-05-07) +- This release is compatible with Spring Boot 2.5.0-2.5.15, 2.6.0-2.6.15, 2.7.0-2.7.18. (Note: 2.5.x (x>15), 2.6.y (y>15) and 2.7.z (z>18) should be supported, but they aren't tested with this release.) +- This release is compatible with Spring Cloud 2020.0.3-2020.0.6, 2021.0.0-2021.0.9. (Note: 2020.0.x (x>6) and 2021.0.y (y>9) should be supported, but they aren't tested with this release.) + +### Spring Cloud Azure Dependencies (BOM) + +#### Dependency Updates +- Upgrade `azure-sdk-bom` to 1.2.23. + +### Azure Spring Data Cosmos +This section includes changes in `azure-spring-data-cosmos` module. +Please refer to [azure-spring-data-cosmos/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md#3450-2024-05-07) for more details. + ## 5.11.0 (2024-03-29) - This release is compatible with Spring Boot 3.0.0-3.0.13, 3.1.0-3.1.8, 3.2.0-3.2.4. (Note: 3.0.x (x>13), 3.1.y (y>8) and 3.2.z (z>4) should be supported, but they aren't tested with this release.) - This release is compatible with Spring Cloud 2022.0.0-2022.0.5, 2023.0.0-2023.0.0. (Note: 2022.0.x (x>5) and 2023.0.y (y>0) should be supported, but they aren't tested with this release.) diff --git a/sdk/spring/README.md b/sdk/spring/README.md index bcc381424cf4..ad63adfed482 100644 --- a/sdk/spring/README.md +++ b/sdk/spring/README.md @@ -139,7 +139,7 @@ If you’re a Maven user, add our BOM to your pom.xml `` s com.azure.spring spring-cloud-azure-dependencies - 4.17.0 + 4.18.0 pom import diff --git a/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md b/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md index b2e844f18e23..ee1ac98b5886 100644 --- a/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md +++ b/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md @@ -1,16 +1,26 @@ ## Release History -### 3.45.0-beta.1 (Unreleased) +### 3.46.0-beta.1 (Unreleased) #### Features Added -* Exposing the `indexQueryMetrics` to the `CosmosConfig` via the `application.properties` configuration file - See [PR 39433](https://github.com/Azure/azure-sdk-for-java/pull/39433). #### Breaking Changes +#### Bugs Fixed + +#### Other Changes + +### 3.45.0 (2024-05-07) + +#### Features Added +* Exposing the `indexQueryMetrics` to the `CosmosConfig` via the `application.properties` configuration file - See [PR 39433](https://github.com/Azure/azure-sdk-for-java/pull/39433). + #### Bugs Fixed * Fixed all saveAll/insertAll bulk functionality to populated audit data - See [PR 39620](https://github.com/Azure/azure-sdk-for-java/pull/39620). +* Fixed `existsById` API in `ReactiveCosmosTemplate` to return `Mono` containing `False` in case the item does not exist - See [PR 40022](https://github.com/Azure/azure-sdk-for-java/pull/40022) #### Other Changes +* Updated `azure-cosmos` to version `4.58.0`. ### 5.11.0 (2024-03-29) diff --git a/sdk/spring/azure-spring-data-cosmos/README.md b/sdk/spring/azure-spring-data-cosmos/README.md index 2439fec3860e..8d417d0265d6 100644 --- a/sdk/spring/azure-spring-data-cosmos/README.md +++ b/sdk/spring/azure-spring-data-cosmos/README.md @@ -100,7 +100,7 @@ If you are using Maven, add the following dependency. com.azure azure-spring-data-cosmos - 3.44.0 + 3.45.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/spring/azure-spring-data-cosmos/pom.xml b/sdk/spring/azure-spring-data-cosmos/pom.xml index ff5b5d10fe5a..38407fa19e58 100644 --- a/sdk/spring/azure-spring-data-cosmos/pom.xml +++ b/sdk/spring/azure-spring-data-cosmos/pom.xml @@ -12,7 +12,7 @@ com.azure azure-spring-data-cosmos - 3.45.0-beta.1 + 3.46.0-beta.1 jar Spring Data for Azure Cosmos DB SQL API Spring Data for Azure Cosmos DB SQL API diff --git a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java index b33a473d6b2d..20612e32dc35 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java +++ b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java @@ -850,7 +850,8 @@ public Mono exists(CosmosQuery query, Class domainType, String conta */ public Mono existsById(Object id, Class domainType, String containerName) { return findById(containerName, id, domainType) - .flatMap(o -> Mono.just(o != null)); + .flatMap(o -> Mono.just(o != null)) + .switchIfEmpty(Mono.just(false)); } /** diff --git a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java index 9a5248b2dc24..90f30b632128 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java +++ b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java @@ -714,6 +714,26 @@ public void testExists() { Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } + @Test + public void testNotExists() { + final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", + Collections.singletonList("randomFirstName"), Part.IgnoreCaseType.NEVER); + final CosmosQuery query = new CosmosQuery(criteria); + final Mono exists = cosmosTemplate.exists(query, Person.class, containerName); + StepVerifier.create(exists).expectNext(false).verifyComplete(); + + // add ignore testing + final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", + Collections.singletonList("randomFirstName".toUpperCase()), Part.IgnoreCaseType.ALWAYS); + final CosmosQuery queryIgnoreCase = new CosmosQuery(criteriaIgnoreCase); + final Mono existsIgnoreCase = cosmosTemplate.exists(queryIgnoreCase, Person.class, containerName); + StepVerifier.create(existsIgnoreCase).expectNext(false).verifyComplete(); + + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); + } + @Test public void testCount() { final Mono count = cosmosTemplate.count(containerName); diff --git a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/ReactiveUUIDIdDomainRepositoryIT.java b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/ReactiveUUIDIdDomainRepositoryIT.java index dd13d14ccf5a..56a1a65418a8 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/ReactiveUUIDIdDomainRepositoryIT.java +++ b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/ReactiveUUIDIdDomainRepositoryIT.java @@ -150,6 +150,9 @@ public void testExistsById() { Mono booleanMono = this.repository.existsById(DOMAIN_1.getNumber()); StepVerifier.create(booleanMono).expectNext(true).expectComplete().verify(); + + booleanMono = this.repository.existsById(UUID.randomUUID()); + StepVerifier.create(booleanMono).expectNext(false).expectComplete().verify(); } private static class InvalidDomain { diff --git a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveLongIdDomainPartitionPartitionRepositoryIT.java b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveLongIdDomainPartitionPartitionRepositoryIT.java index 823b7897bc8f..03bf88ce9359 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveLongIdDomainPartitionPartitionRepositoryIT.java +++ b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveLongIdDomainPartitionPartitionRepositoryIT.java @@ -171,6 +171,9 @@ public void testExistsById() { Mono booleanMono = this.repository.existsById(DOMAIN_1.getNumber()); StepVerifier.create(booleanMono).expectNext(true).expectComplete().verify(); + + booleanMono = this.repository.existsById(0L); + StepVerifier.create(booleanMono).expectNext(false).expectComplete().verify(); } @Test diff --git a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/CHANGELOG.md b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml index 1fba53d1705f..25077a86639a 100644 --- a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml +++ b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-actuator-autoconfigure - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Actuator AutoConfigure Spring Cloud Azure Starter Actuator AutoConfigure @@ -43,17 +43,17 @@ com.azure.spring spring-cloud-azure-actuator - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-autoconfigure - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-appconfiguration-config-web - 4.18.0-beta.1 + 4.19.0-beta.1 true diff --git a/sdk/spring/spring-cloud-azure-actuator/CHANGELOG.md b/sdk/spring/spring-cloud-azure-actuator/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-cloud-azure-actuator/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-actuator/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-actuator/pom.xml b/sdk/spring/spring-cloud-azure-actuator/pom.xml index de867f093e46..652a5c62968e 100644 --- a/sdk/spring/spring-cloud-azure-actuator/pom.xml +++ b/sdk/spring/spring-cloud-azure-actuator/pom.xml @@ -17,7 +17,7 @@ com.azure.spring spring-cloud-azure-actuator - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Actuator https://microsoft.github.io/spring-cloud-azure @@ -105,7 +105,7 @@ com.azure.spring spring-cloud-azure-appconfiguration-config-web - 4.18.0-beta.1 + 4.19.0-beta.1 true diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config-web/CHANGELOG.md b/sdk/spring/spring-cloud-azure-appconfiguration-config-web/CHANGELOG.md index 13b0a6a7f223..3085354f0d80 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config-web/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config-web/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config-web/pom.xml b/sdk/spring/spring-cloud-azure-appconfiguration-config-web/pom.xml index 5c91d1b8b219..e118e9a0b181 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config-web/pom.xml +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config-web/pom.xml @@ -10,7 +10,7 @@ com.azure.spring spring-cloud-azure-appconfiguration-config-web - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure App Configuration Config Web Integration of Spring Cloud Config and Azure App Configuration Service @@ -24,7 +24,7 @@ com.azure.spring spring-cloud-azure-appconfiguration-config - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config/CHANGELOG.md b/sdk/spring/spring-cloud-azure-appconfiguration-config/CHANGELOG.md index da680e820d80..ef0518a75b38 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml b/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml index 9aca0209389d..2442d649f6aa 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml @@ -9,7 +9,7 @@ 4.0.0 com.azure.spring spring-cloud-azure-appconfiguration-config - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure App Configuration Config Integration of Spring Cloud Config and Azure App Configuration Service @@ -63,12 +63,12 @@ com.azure.spring spring-cloud-azure-service - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-autoconfigure - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config/src/test/java/com/azure/spring/cloud/appconfiguration/config/implementation/TestUtils.java b/sdk/spring/spring-cloud-azure-appconfiguration-config/src/test/java/com/azure/spring/cloud/appconfiguration/config/implementation/TestUtils.java index 1a09cdf8ed1a..e9fe610f0e4c 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config/src/test/java/com/azure/spring/cloud/appconfiguration/config/implementation/TestUtils.java +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config/src/test/java/com/azure/spring/cloud/appconfiguration/config/implementation/TestUtils.java @@ -7,6 +7,8 @@ import java.util.Map; import java.util.Set; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.data.appconfiguration.models.ConfigurationSetting; import com.azure.data.appconfiguration.models.FeatureFlagConfigurationSetting; import com.azure.data.appconfiguration.models.FeatureFlagFilter; @@ -23,6 +25,7 @@ * Utility methods which can be used across different test classes */ public final class TestUtils { + private static final ClientLogger LOGGER = new ClientLogger(TestUtils.class); private static final ObjectMapper MAPPER = new ObjectMapper(); @@ -75,7 +78,7 @@ static FeatureFlagConfigurationSetting createItemFeatureFlag(String prefix, Stri item.addClientFilter(filter); } } catch (JsonProcessingException e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Failed to create FeatureFlagConfigurationSetting.", e); } return item; } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/CHANGELOG.md b/sdk/spring/spring-cloud-azure-autoconfigure/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-autoconfigure/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml b/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml index 6cd733b405b2..da9cd157ee9b 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml +++ b/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-autoconfigure - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure AutoConfigure Spring Cloud Azure AutoConfigure @@ -37,20 +37,20 @@ com.azure.spring spring-cloud-azure-service - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-resourcemanager - 4.18.0-beta.1 + 4.19.0-beta.1 true com.azure.spring spring-cloud-azure-trace-sleuth - 4.18.0-beta.1 + 4.19.0-beta.1 true @@ -59,7 +59,7 @@ com.azure.spring spring-integration-azure-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 true @@ -73,7 +73,7 @@ com.azure.spring spring-integration-azure-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 true @@ -81,7 +81,7 @@ com.azure.spring spring-integration-azure-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 true @@ -111,7 +111,7 @@ com.azure azure-spring-data-cosmos - 3.45.0-beta.1 + 3.46.0-beta.1 true @@ -175,7 +175,7 @@ com.azure azure-messaging-servicebus - 7.16.0 + 7.17.0 true diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/aad/implementation/TestJwks.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/aad/implementation/TestJwks.java index 5dca4d976bd8..99546b479151 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/aad/implementation/TestJwks.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/aad/implementation/TestJwks.java @@ -3,6 +3,8 @@ package com.azure.spring.cloud.autoconfigure.aad.implementation; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.util.Base64URL; @@ -14,6 +16,7 @@ import java.security.interfaces.RSAPublicKey; public final class TestJwks { + private static final ClientLogger LOGGER = new ClientLogger(TestJwks.class); // @formatter:off public static final RSAKey DEFAULT_RSA_JWK = @@ -38,7 +41,7 @@ public static RSAKey.Builder jwk(RSAPublicKey publicKey, RSAPrivateKey privateKe .x509CertThumbprint(Base64URL.encode(bytes)) .keyID("rsa-jwk-kid"); } catch (CertificateEncodingException | NoSuchAlgorithmException e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Failed to generate thumbprint for certificate.", e); } return null; // @formatter:on diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/aad/implementation/graph/UserPrincipalMicrosoftGraphTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/aad/implementation/graph/UserPrincipalMicrosoftGraphTests.java index d49e86657011..98024e7579db 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/aad/implementation/graph/UserPrincipalMicrosoftGraphTests.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/aad/implementation/graph/UserPrincipalMicrosoftGraphTests.java @@ -3,6 +3,8 @@ package com.azure.spring.cloud.autoconfigure.aad.implementation.graph; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.spring.cloud.autoconfigure.aad.filter.UserPrincipal; import com.azure.spring.cloud.autoconfigure.aad.properties.AadAuthenticationProperties; import com.azure.spring.cloud.autoconfigure.aad.properties.AadAuthorizationServerEndpoints; @@ -49,6 +51,7 @@ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserPrincipalMicrosoftGraphTests { + private static final ClientLogger LOGGER = new ClientLogger(UserPrincipalMicrosoftGraphTests.class); private static final String MOCK_MICROSOFT_GRAPH_ENDPOINT = "http://localhost:8080/"; @@ -68,7 +71,7 @@ class UserPrincipalMicrosoftGraphTests { }); userGroupsJson = objectMapper.writeValueAsString(json); } catch (IOException e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Failed to load user groups json.", e); userGroupsJson = null; } assertNotNull(userGroupsJson); diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/graph/ThreadInterruptedStatusRestoreTest.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/graph/ThreadInterruptedStatusRestoreTest.java index bd8b448ca437..8ea467b01370 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/graph/ThreadInterruptedStatusRestoreTest.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/graph/ThreadInterruptedStatusRestoreTest.java @@ -3,6 +3,8 @@ package com.azure.spring.cloud.autoconfigure.implementation.graph; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -10,6 +12,7 @@ import java.util.concurrent.TimeUnit; public class ThreadInterruptedStatusRestoreTest { + private static final ClientLogger LOGGER = new ClientLogger(ThreadInterruptedStatusRestoreTest.class); @Test void testThreadInterruptedRestoreFromAnotherThread() throws InterruptedException { @@ -22,9 +25,9 @@ void testThreadInterruptedRestoreFromAnotherThread() throws InterruptedException testThread.interrupt(); latchForInCatch.await(); - System.out.println(Thread.currentThread().getName() + ": begin assertion"); + LOGGER.log(LogLevel.VERBOSE, () -> Thread.currentThread().getName() + ": begin assertion"); Assertions.assertTrue((testThread).getIsInterrupted()); - System.out.println(Thread.currentThread().getName() + ": end assertion"); + LOGGER.log(LogLevel.VERBOSE, () -> Thread.currentThread().getName() + ": end assertion"); } @Test @@ -38,9 +41,9 @@ void testThreadInterruptedNotRestoreFromAnotherThread() throws InterruptedExcept testThread.interrupt(); latchForInCatch.await(); - System.out.println(Thread.currentThread().getName() + ": begin assertion"); + LOGGER.log(LogLevel.VERBOSE, () -> Thread.currentThread().getName() + ": begin assertion"); Assertions.assertFalse(testThread.getIsInterrupted()); - System.out.println(Thread.currentThread().getName() + ": end assertion"); + LOGGER.log(LogLevel.VERBOSE, () -> Thread.currentThread().getName() + ": end assertion"); } @@ -64,7 +67,8 @@ public void run() { latchForInWhile.countDown(); TimeUnit.SECONDS.sleep(3); } catch (InterruptedException ex) { - System.out.println(Thread.currentThread().getName() + ": current thread was interrupted!"); + LOGGER.log(LogLevel.VERBOSE, + () -> Thread.currentThread().getName() + ": current thread was interrupted!"); if (restore) { Thread.currentThread().interrupt(); } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/jms/AzureServiceBusJmsPropertiesTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/jms/AzureServiceBusJmsPropertiesTests.java index e198123d55a9..fff6275c6c85 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/jms/AzureServiceBusJmsPropertiesTests.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/jms/AzureServiceBusJmsPropertiesTests.java @@ -3,6 +3,8 @@ package com.azure.spring.cloud.autoconfigure.jms; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.spring.cloud.autoconfigure.jms.properties.AzureServiceBusJmsProperties; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -17,6 +19,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class AzureServiceBusJmsPropertiesTests { + private static final ClientLogger LOGGER = new ClientLogger(AzureServiceBusJmsPropertiesTests.class); + static final String CONNECTION_STRING = "Endpoint=sb://host/;SharedAccessKeyName=sasKeyName;" + "SharedAccessKey=sasKey"; @@ -31,7 +35,7 @@ void connectionStringNotValid() { String expectedMessage = "'spring.jms.servicebus.connection-string' should be provided."; String actualMessage = ex.getMessage(); - System.out.println("message:" + actualMessage); + LOGGER.log(LogLevel.VERBOSE, () -> "message:" + actualMessage); assertTrue(actualMessage.contains(expectedMessage)); } @@ -47,7 +51,7 @@ void pricingTierNotValid(String pricingTier) { String expectedMessage = "'spring.jms.servicebus.pricing-tier' is not valid"; String actualMessage = ex.getMessage(); - System.out.println("message:" + actualMessage); + LOGGER.log(LogLevel.VERBOSE, () -> "message:" + actualMessage); assertTrue(actualMessage.contains(expectedMessage)); } diff --git a/sdk/spring/spring-cloud-azure-core/CHANGELOG.md b/sdk/spring/spring-cloud-azure-core/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-cloud-azure-core/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-core/pom.xml b/sdk/spring/spring-cloud-azure-core/pom.xml index e52f7d5e25ef..3f910bb950f0 100644 --- a/sdk/spring/spring-cloud-azure-core/pom.xml +++ b/sdk/spring/spring-cloud-azure-core/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Core https://microsoft.github.io/spring-cloud-azure diff --git a/sdk/spring/spring-cloud-azure-feature-management-web/CHANGELOG.md b/sdk/spring/spring-cloud-azure-feature-management-web/CHANGELOG.md index cb045c6fcbc4..2fb0c4fca339 100644 --- a/sdk/spring/spring-cloud-azure-feature-management-web/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-feature-management-web/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-feature-management-web/pom.xml b/sdk/spring/spring-cloud-azure-feature-management-web/pom.xml index 5c818caef1e7..60eca8c08ff5 100644 --- a/sdk/spring/spring-cloud-azure-feature-management-web/pom.xml +++ b/sdk/spring/spring-cloud-azure-feature-management-web/pom.xml @@ -9,7 +9,7 @@ com.azure.spring spring-cloud-azure-feature-management-web - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Feature Management Web Adds Feature Management into Spring Web @@ -46,7 +46,7 @@ com.azure.spring spring-cloud-azure-feature-management - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot @@ -65,7 +65,7 @@ - com.azure.spring:spring-cloud-azure-feature-management:[4.18.0-beta.1] + com.azure.spring:spring-cloud-azure-feature-management:[4.19.0-beta.1] javax.servlet:javax.servlet-api:[4.0.1] org.springframework:spring-web:[5.3.32] org.springframework:spring-webmvc:[5.3.32] diff --git a/sdk/spring/spring-cloud-azure-feature-management/CHANGELOG.md b/sdk/spring/spring-cloud-azure-feature-management/CHANGELOG.md index 1473db8045d9..836db6260b31 100644 --- a/sdk/spring/spring-cloud-azure-feature-management/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-feature-management/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-feature-management/pom.xml b/sdk/spring/spring-cloud-azure-feature-management/pom.xml index 13bed8a8b617..fe740c88b88e 100644 --- a/sdk/spring/spring-cloud-azure-feature-management/pom.xml +++ b/sdk/spring/spring-cloud-azure-feature-management/pom.xml @@ -11,7 +11,7 @@ com.azure.spring spring-cloud-azure-feature-management - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Feature Management Adds Feature Management into Spring diff --git a/sdk/spring/spring-cloud-azure-integration-test-appconfiguration-config/pom.xml b/sdk/spring/spring-cloud-azure-integration-test-appconfiguration-config/pom.xml index caf82424a10a..bf5a689c0fe6 100644 --- a/sdk/spring/spring-cloud-azure-integration-test-appconfiguration-config/pom.xml +++ b/sdk/spring/spring-cloud-azure-integration-test-appconfiguration-config/pom.xml @@ -24,7 +24,7 @@ com.azure.spring spring-cloud-azure-starter-appconfiguration-config - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot diff --git a/sdk/spring/spring-cloud-azure-integration-tests/pom.xml b/sdk/spring/spring-cloud-azure-integration-tests/pom.xml index a27b86269a21..d6bbd8c0b7b4 100644 --- a/sdk/spring/spring-cloud-azure-integration-tests/pom.xml +++ b/sdk/spring/spring-cloud-azure-integration-tests/pom.xml @@ -40,72 +40,72 @@ com.azure.spring spring-cloud-azure-starter-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-servicebus-jms - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-keyvault-secrets - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-blob - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-file-share - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-appconfiguration - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-data-cosmos - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-cosmos - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-stream-binder-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-stream-binder-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-jdbc-mysql - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-redis - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot diff --git a/sdk/spring/spring-cloud-azure-resourcemanager/CHANGELOG.md b/sdk/spring/spring-cloud-azure-resourcemanager/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-cloud-azure-resourcemanager/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-resourcemanager/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-resourcemanager/pom.xml b/sdk/spring/spring-cloud-azure-resourcemanager/pom.xml index 06bbce088766..33ee068b5162 100644 --- a/sdk/spring/spring-cloud-azure-resourcemanager/pom.xml +++ b/sdk/spring/spring-cloud-azure-resourcemanager/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-resourcemanager - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Resource Manager Spring Cloud Azure Resource Manager @@ -37,7 +37,7 @@ com.azure.spring spring-cloud-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-service/CHANGELOG.md b/sdk/spring/spring-cloud-azure-service/CHANGELOG.md index 69bda720e930..aa68b8828d29 100644 --- a/sdk/spring/spring-cloud-azure-service/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-service/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-service/pom.xml b/sdk/spring/spring-cloud-azure-service/pom.xml index 9cc495eb56df..beb2fc5f648a 100644 --- a/sdk/spring/spring-cloud-azure-service/pom.xml +++ b/sdk/spring/spring-cloud-azure-service/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-service - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Service Spring Cloud Azure Service @@ -37,7 +37,7 @@ com.azure.spring spring-cloud-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 @@ -56,7 +56,7 @@ com.azure azure-messaging-servicebus - 7.16.0 + 7.17.0 true diff --git a/sdk/spring/spring-cloud-azure-starter-active-directory-b2c/pom.xml b/sdk/spring/spring-cloud-azure-starter-active-directory-b2c/pom.xml index d54e58f42ac6..d38c8cfca95f 100644 --- a/sdk/spring/spring-cloud-azure-starter-active-directory-b2c/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-active-directory-b2c/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-active-directory-b2c - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Active Directory B2C Spring Cloud Azure Starter Active Directory B2C @@ -87,7 +87,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.security diff --git a/sdk/spring/spring-cloud-azure-starter-active-directory/pom.xml b/sdk/spring/spring-cloud-azure-starter-active-directory/pom.xml index 56822ae1cdcc..65ee7a0c8e1f 100644 --- a/sdk/spring/spring-cloud-azure-starter-active-directory/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-active-directory/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-active-directory - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Active Directory Spring Cloud Azure Starter Active Directory @@ -86,7 +86,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.security diff --git a/sdk/spring/spring-cloud-azure-starter-actuator/pom.xml b/sdk/spring/spring-cloud-azure-starter-actuator/pom.xml index cb56bec792fe..5505e39f13df 100644 --- a/sdk/spring/spring-cloud-azure-starter-actuator/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-actuator/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-actuator - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Actuator Spring Cloud Azure Starter Actuator @@ -88,12 +88,12 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-actuator-autoconfigure - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot diff --git a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/CHANGELOG.md b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/CHANGELOG.md index ccd45b959538..c5dbeb34c7a4 100644 --- a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/README.md b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/README.md index ab94a09b3945..7d8d1083487d 100644 --- a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/README.md +++ b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/README.md @@ -21,7 +21,7 @@ There are two libraries that can be used spring-cloud-azure-appconfiguration-con com.azure.spring spring-cloud-azure-appconfiguration-config - 4.17.0 + 4.18.0 ``` [//]: # ({x-version-update-end}) @@ -33,7 +33,7 @@ or com.azure.spring spring-cloud-azure-appconfiguration-config-web - 4.17.0 + 4.18.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/pom.xml b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/pom.xml index 46b1a21899c1..539ffd20d827 100644 --- a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-starter-appconfiguration-config - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter App Configuration Config Spring Cloud Azure Starter App Configuration Config @@ -20,12 +20,12 @@ com.azure.spring spring-cloud-azure-appconfiguration-config-web - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-feature-management-web - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-appconfiguration/pom.xml b/sdk/spring/spring-cloud-azure-starter-appconfiguration/pom.xml index ef64a2d7aa22..606ca13761c0 100644 --- a/sdk/spring/spring-cloud-azure-starter-appconfiguration/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-appconfiguration/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-appconfiguration - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter App Configuration Spring Cloud Azure Starter App Configuration @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure diff --git a/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml b/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml index 961413466935..77a60f670a47 100644 --- a/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-cosmos - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Cosmos DB Spring Cloud Azure Starter Cosmos DB @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure diff --git a/sdk/spring/spring-cloud-azure-starter-data-cosmos/pom.xml b/sdk/spring/spring-cloud-azure-starter-data-cosmos/pom.xml index f6d7e5a43353..e347970cb041 100644 --- a/sdk/spring/spring-cloud-azure-starter-data-cosmos/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-data-cosmos/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-data-cosmos - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Data Cosmos DB Spring Cloud Azure Starter Data Cosmos DB @@ -88,12 +88,12 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure azure-spring-data-cosmos - 3.45.0-beta.1 + 3.46.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-eventgrid/pom.xml b/sdk/spring/spring-cloud-azure-starter-eventgrid/pom.xml index f0aa79e39afa..5ea00a9ab071 100644 --- a/sdk/spring/spring-cloud-azure-starter-eventgrid/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-eventgrid/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-eventgrid - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Event Grid Spring Cloud Azure Starter Event Grid @@ -87,7 +87,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-eventhubs/pom.xml b/sdk/spring/spring-cloud-azure-starter-eventhubs/pom.xml index b228381b4c49..8fb9ab784b65 100644 --- a/sdk/spring/spring-cloud-azure-starter-eventhubs/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-eventhubs/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Event Hubs Spring Cloud Azure Starter Event Hubs @@ -87,7 +87,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-integration-eventhubs/pom.xml b/sdk/spring/spring-cloud-azure-starter-integration-eventhubs/pom.xml index 5889b59d7bbf..dfb76b3d5e77 100644 --- a/sdk/spring/spring-cloud-azure-starter-integration-eventhubs/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-integration-eventhubs/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-integration-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Integration Event Hubs Spring Cloud Azure Starter Integration Event Hubs @@ -87,7 +87,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot @@ -97,7 +97,7 @@ com.azure.spring spring-integration-azure-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-integration-servicebus/pom.xml b/sdk/spring/spring-cloud-azure-starter-integration-servicebus/pom.xml index 40d4ea9d1992..a89f23385c88 100644 --- a/sdk/spring/spring-cloud-azure-starter-integration-servicebus/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-integration-servicebus/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-integration-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Integration Service Bus Spring Cloud Azure Starter Integration Service Bus @@ -89,7 +89,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot @@ -99,7 +99,7 @@ com.azure.spring spring-integration-azure-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-integration-storage-queue/pom.xml b/sdk/spring/spring-cloud-azure-starter-integration-storage-queue/pom.xml index f1b5026f436e..2815759582bf 100644 --- a/sdk/spring/spring-cloud-azure-starter-integration-storage-queue/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-integration-storage-queue/pom.xml @@ -10,7 +10,7 @@ com.azure.spring spring-cloud-azure-starter-integration-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Integration Storage Queue Spring Cloud Azure Starter Integration Storage Queue @@ -92,7 +92,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot @@ -102,7 +102,7 @@ com.azure.spring spring-integration-azure-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-jdbc-mysql/pom.xml b/sdk/spring/spring-cloud-azure-starter-jdbc-mysql/pom.xml index 99303b8f7796..374ffc0b6428 100644 --- a/sdk/spring/spring-cloud-azure-starter-jdbc-mysql/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-jdbc-mysql/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-jdbc-mysql - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter JDBC MySQL Spring Cloud Azure Starter for building applications with JDBC and Azure MySQL Services. Support authenticating with Azure AD. @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql/pom.xml b/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql/pom.xml index 1288ef6a3b83..d664aced1b01 100644 --- a/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-jdbc-postgresql - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter JDBC PostgreSQL Spring Cloud Azure Starter for building applications with JDBC and Azure PostgreSQL Services. Support authenticating with Azure AD. @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-keyvault-certificates/pom.xml b/sdk/spring/spring-cloud-azure-starter-keyvault-certificates/pom.xml index 50901ef0a0e5..932ca89d9525 100644 --- a/sdk/spring/spring-cloud-azure-starter-keyvault-certificates/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-keyvault-certificates/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-keyvault-certificates - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Key Vault Certificates Spring Cloud Azure Starter Key Vault Certificates @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure diff --git a/sdk/spring/spring-cloud-azure-starter-keyvault-secrets/pom.xml b/sdk/spring/spring-cloud-azure-starter-keyvault-secrets/pom.xml index c42bce0cbdc3..7f4d3ad73772 100644 --- a/sdk/spring/spring-cloud-azure-starter-keyvault-secrets/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-keyvault-secrets/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-keyvault-secrets - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Key Vault Secrets Spring Cloud Azure Starter Key Vault Secrets @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure diff --git a/sdk/spring/spring-cloud-azure-starter-keyvault/pom.xml b/sdk/spring/spring-cloud-azure-starter-keyvault/pom.xml index 7d7039b79f76..2dd3581b3608 100644 --- a/sdk/spring/spring-cloud-azure-starter-keyvault/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-keyvault/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-keyvault - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Key Vault Spring Cloud Azure Starter Key Vault @@ -88,12 +88,12 @@ com.azure.spring spring-cloud-azure-starter-keyvault-secrets - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-keyvault-certificates - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-redis/pom.xml b/sdk/spring/spring-cloud-azure-starter-redis/pom.xml index 86c3e3c0dac4..3071c83e6ff6 100644 --- a/sdk/spring/spring-cloud-azure-starter-redis/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-redis/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-redis - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Redis Spring Cloud Azure Starter for building applications with Azure Cache for Redis. Support authenticating with Azure AD. @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-servicebus-jms/pom.xml b/sdk/spring/spring-cloud-azure-starter-servicebus-jms/pom.xml index 42e4ce22afa9..4377ac30d9ab 100644 --- a/sdk/spring/spring-cloud-azure-starter-servicebus-jms/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-servicebus-jms/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-servicebus-jms - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Service Bus JMS Spring Cloud Azure Starter Service Bus JMS @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-servicebus/pom.xml b/sdk/spring/spring-cloud-azure-starter-servicebus/pom.xml index a02aed3a8427..f8a85eb12491 100644 --- a/sdk/spring/spring-cloud-azure-starter-servicebus/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-servicebus/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Service Bus Spring Cloud Azure Starter Service Bus @@ -89,12 +89,12 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure azure-messaging-servicebus - 7.16.0 + 7.17.0 diff --git a/sdk/spring/spring-cloud-azure-starter-storage-blob/pom.xml b/sdk/spring/spring-cloud-azure-starter-storage-blob/pom.xml index 0999561da331..c858539e614e 100644 --- a/sdk/spring/spring-cloud-azure-starter-storage-blob/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-storage-blob/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-storage-blob - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Storage Blob Spring Cloud Azure Starter Storage Blob @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-storage-file-share/pom.xml b/sdk/spring/spring-cloud-azure-starter-storage-file-share/pom.xml index b999e6efbfcd..b80cceb41e2c 100644 --- a/sdk/spring/spring-cloud-azure-starter-storage-file-share/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-storage-file-share/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-storage-file-share - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Storage File Share Spring Cloud Azure Starter Storage File Share @@ -88,7 +88,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-storage-queue/pom.xml b/sdk/spring/spring-cloud-azure-starter-storage-queue/pom.xml index e54fff3cb578..b4d9e29f25cc 100644 --- a/sdk/spring/spring-cloud-azure-starter-storage-queue/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-storage-queue/pom.xml @@ -10,7 +10,7 @@ com.azure.spring spring-cloud-azure-starter-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Storage Queue Spring Cloud Azure Starter Storage Queue @@ -92,7 +92,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure diff --git a/sdk/spring/spring-cloud-azure-starter-storage/pom.xml b/sdk/spring/spring-cloud-azure-starter-storage/pom.xml index 0a41be67fbc9..6d021919c18f 100644 --- a/sdk/spring/spring-cloud-azure-starter-storage/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-storage/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-storage - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Storage Spring Cloud Azure Starter Storage @@ -88,19 +88,19 @@ com.azure.spring spring-cloud-azure-starter-storage-blob - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-file-share - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-stream-eventhubs/pom.xml b/sdk/spring/spring-cloud-azure-starter-stream-eventhubs/pom.xml index d5d5346e8132..85df3f175dbd 100644 --- a/sdk/spring/spring-cloud-azure-starter-stream-eventhubs/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-stream-eventhubs/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-stream-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Stream Event Hubs Spring Cloud Azure Starter Stream Event Hubs @@ -87,7 +87,7 @@ com.azure.spring spring-cloud-azure-stream-binder-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-stream-servicebus/pom.xml b/sdk/spring/spring-cloud-azure-starter-stream-servicebus/pom.xml index 1239d2472066..12f878f20a34 100644 --- a/sdk/spring/spring-cloud-azure-starter-stream-servicebus/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-stream-servicebus/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-stream-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Stream Service Bus Spring Cloud Azure Starter Stream Service Bus @@ -87,7 +87,7 @@ com.azure.spring spring-cloud-azure-stream-binder-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter/pom.xml b/sdk/spring/spring-cloud-azure-starter/pom.xml index 300fc32c33c5..3b5099ac699f 100644 --- a/sdk/spring/spring-cloud-azure-starter/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Starter Core starter, including auto-configuration support @@ -93,7 +93,7 @@ com.azure.spring spring-cloud-azure-autoconfigure - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/CHANGELOG.md b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/pom.xml b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/pom.xml index d2d41ac556e2..06aa4554c0e2 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/pom.xml +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-stream-binder-eventhubs-core - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Stream Binder Event Hubs Core Spring Cloud Azure Stream Binder Event Hubs Core @@ -49,7 +49,7 @@ com.azure.spring spring-integration-azure-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/CHANGELOG.md b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/pom.xml b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/pom.xml index b3823c56bf5d..45f99b72a6f5 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/pom.xml +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-stream-binder-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Stream Binder Event Hubs Spring Cloud Azure Stream Binder Event Hubs @@ -37,12 +37,12 @@ com.azure.spring spring-cloud-azure-autoconfigure - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-stream-binder-eventhubs-core - 4.18.0-beta.1 + 4.19.0-beta.1 @@ -60,7 +60,7 @@ com.azure.spring spring-cloud-azure-resourcemanager - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/CHANGELOG.md b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/CHANGELOG.md index 69bda720e930..aa68b8828d29 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/pom.xml b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/pom.xml index 3728af289eba..5bf76654c0a3 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/pom.xml +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-stream-binder-servicebus-core - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Stream Binder Service Bus Core Spring Cloud Azure Stream Binder Service Bus Core @@ -43,12 +43,12 @@ com.azure.spring spring-integration-azure-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure azure-messaging-servicebus - 7.16.0 + 7.17.0 org.springframework.boot diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/CHANGELOG.md b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/CHANGELOG.md index 69bda720e930..aa68b8828d29 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/pom.xml b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/pom.xml index 0a7291f28ef9..ca4c6a740960 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/pom.xml +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-stream-binder-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Stream Binder Service Bus Spring Cloud Azure Stream Binder Service Bus @@ -37,17 +37,17 @@ com.azure.spring spring-cloud-azure-stream-binder-servicebus-core - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-autoconfigure - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-cloud-azure-resourcemanager - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.boot diff --git a/sdk/spring/spring-cloud-azure-trace-sleuth/CHANGELOG.md b/sdk/spring/spring-cloud-azure-trace-sleuth/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-cloud-azure-trace-sleuth/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-trace-sleuth/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-cloud-azure-trace-sleuth/pom.xml b/sdk/spring/spring-cloud-azure-trace-sleuth/pom.xml index 08f755475e38..699990594057 100644 --- a/sdk/spring/spring-cloud-azure-trace-sleuth/pom.xml +++ b/sdk/spring/spring-cloud-azure-trace-sleuth/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-trace-sleuth - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Cloud Azure Trace on Sleuth https://microsoft.github.io/spring-cloud-azure @@ -36,7 +36,7 @@ com.azure.spring spring-cloud-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.cloud diff --git a/sdk/spring/spring-integration-azure-core/CHANGELOG.md b/sdk/spring/spring-integration-azure-core/CHANGELOG.md index 69bda720e930..aa68b8828d29 100644 --- a/sdk/spring/spring-integration-azure-core/CHANGELOG.md +++ b/sdk/spring/spring-integration-azure-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-integration-azure-core/pom.xml b/sdk/spring/spring-integration-azure-core/pom.xml index 03b52f89ff4e..ce8b62cda41c 100644 --- a/sdk/spring/spring-integration-azure-core/pom.xml +++ b/sdk/spring/spring-integration-azure-core/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-integration-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Integration Azure Core Spring Integration Azure Core @@ -41,7 +41,7 @@ com.azure.spring spring-messaging-azure - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework.integration diff --git a/sdk/spring/spring-integration-azure-eventhubs/CHANGELOG.md b/sdk/spring/spring-integration-azure-eventhubs/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-integration-azure-eventhubs/CHANGELOG.md +++ b/sdk/spring/spring-integration-azure-eventhubs/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-integration-azure-eventhubs/pom.xml b/sdk/spring/spring-integration-azure-eventhubs/pom.xml index 0627077adc40..c4621fa56634 100644 --- a/sdk/spring/spring-integration-azure-eventhubs/pom.xml +++ b/sdk/spring/spring-integration-azure-eventhubs/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-integration-azure-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Integration Azure Event Hubs Spring Integration Azure Event Hubs @@ -37,19 +37,19 @@ com.azure.spring spring-integration-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-integration-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 test-jar test com.azure.spring spring-messaging-azure-eventhubs - 4.18.0-beta.1 + 4.19.0-beta.1 diff --git a/sdk/spring/spring-integration-azure-servicebus/CHANGELOG.md b/sdk/spring/spring-integration-azure-servicebus/CHANGELOG.md index 69bda720e930..aa68b8828d29 100644 --- a/sdk/spring/spring-integration-azure-servicebus/CHANGELOG.md +++ b/sdk/spring/spring-integration-azure-servicebus/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-integration-azure-servicebus/pom.xml b/sdk/spring/spring-integration-azure-servicebus/pom.xml index 55c5376e7452..66287f9ecbd9 100644 --- a/sdk/spring/spring-integration-azure-servicebus/pom.xml +++ b/sdk/spring/spring-integration-azure-servicebus/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-integration-azure-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Integration Azure Service Bus Spring Integration Azure Service Bus @@ -37,24 +37,24 @@ com.azure.spring spring-integration-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-integration-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 test-jar test com.azure.spring spring-messaging-azure-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-messaging-azure-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 test-jar test diff --git a/sdk/spring/spring-integration-azure-storage-queue/CHANGELOG.md b/sdk/spring/spring-integration-azure-storage-queue/CHANGELOG.md index 69bda720e930..aa68b8828d29 100644 --- a/sdk/spring/spring-integration-azure-storage-queue/CHANGELOG.md +++ b/sdk/spring/spring-integration-azure-storage-queue/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-integration-azure-storage-queue/pom.xml b/sdk/spring/spring-integration-azure-storage-queue/pom.xml index 0c10e1f5f03d..c79317e1ffc3 100644 --- a/sdk/spring/spring-integration-azure-storage-queue/pom.xml +++ b/sdk/spring/spring-integration-azure-storage-queue/pom.xml @@ -13,7 +13,7 @@ com.azure.spring spring-integration-azure-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Integration Azure Storage Queue Spring Integration Azure Storage Queue @@ -38,12 +38,12 @@ com.azure.spring spring-integration-azure-core - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-messaging-azure-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 + 4.19.0-beta.1 Spring Messaging Azure Event Hubs Spring Messaging Azure Event Hubs @@ -37,12 +37,12 @@ com.azure.spring spring-messaging-azure - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-messaging-azure - 4.18.0-beta.1 + 4.19.0-beta.1 test-jar test diff --git a/sdk/spring/spring-messaging-azure-eventhubs/src/test/java/com/azure/spring/messaging/eventhubs/core/EventHubsTemplateTests.java b/sdk/spring/spring-messaging-azure-eventhubs/src/test/java/com/azure/spring/messaging/eventhubs/core/EventHubsTemplateTests.java index 7e931c350b6e..0a6109aa71db 100644 --- a/sdk/spring/spring-messaging-azure-eventhubs/src/test/java/com/azure/spring/messaging/eventhubs/core/EventHubsTemplateTests.java +++ b/sdk/spring/spring-messaging-azure-eventhubs/src/test/java/com/azure/spring/messaging/eventhubs/core/EventHubsTemplateTests.java @@ -5,6 +5,8 @@ import com.azure.core.amqp.exception.AmqpErrorCondition; import com.azure.core.amqp.exception.AmqpException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.eventhubs.EventData; import com.azure.messaging.eventhubs.EventDataBatch; import com.azure.messaging.eventhubs.EventHubProducerAsyncClient; @@ -31,6 +33,7 @@ class EventHubsTemplateTests { + private static final ClientLogger LOGGER = new ClientLogger(EventHubsTemplateTests.class); private EventHubProducerAsyncClient mockProducerClient; protected String destination = "event-hub"; @@ -93,9 +96,8 @@ void testSendAsyncForMessagesOneBatchAndSendCompletely() { List> messages = messagesList.stream().map((Function>) GenericMessage::new).collect(Collectors.toList()); - Mono mono = this.eventHubsTemplate.sendAsync(this.destination, messages, null).doOnSuccess(t -> { - System.out.println("do on success:" + t); - }); + Mono mono = this.eventHubsTemplate.sendAsync(this.destination, messages, null) + .doOnSuccess(t -> LOGGER.log(LogLevel.VERBOSE, () -> "do on success:" + t)); StepVerifier.create(mono) .verifyComplete(); @@ -125,12 +127,9 @@ void testSendAsyncForMessagesOneBatchAndSendCompletelyWithException() { List> messages = messagesList.stream().map((Function>) GenericMessage::new).collect(Collectors.toList()); - Mono mono = this.eventHubsTemplate.sendAsync(this.destination, messages, null).doOnError(ex -> { - System.out.println("do on Error"); - ex.printStackTrace(); - }).doOnSuccess(t -> { - System.out.println("do on success:" + t); - }); + Mono mono = this.eventHubsTemplate.sendAsync(this.destination, messages, null) + .doOnError(ex -> LOGGER.log(LogLevel.VERBOSE, () -> "do on Error", ex)) + .doOnSuccess(t -> LOGGER.log(LogLevel.VERBOSE, () -> "do on success:" + t)); StepVerifier.create(mono) .verifyComplete(); verify(this.mockProducerClient, times(1)).send(any(EventDataBatch.class)); @@ -160,12 +159,9 @@ void testSendAsyncForMessagesTwoBatchAndSendCompletelyWithException() { List> messages = messagesList.stream().map((Function>) GenericMessage::new).collect(Collectors.toList()); - Mono mono = this.eventHubsTemplate.sendAsync(this.destination, messages, null).doOnError(ex -> { - System.out.println("do on Error"); - ex.printStackTrace(); - }).doOnSuccess(t -> { - System.out.println("do on success:" + t); - }); + Mono mono = this.eventHubsTemplate.sendAsync(this.destination, messages, null) + .doOnError(ex -> LOGGER.log(LogLevel.VERBOSE, () -> "do on Error", ex)) + .doOnSuccess(t -> LOGGER.log(LogLevel.VERBOSE, () -> "do on success:" + t)); StepVerifier.create(mono) .verifyComplete(); verify(this.mockProducerClient, times(2)).send(any(EventDataBatch.class)); @@ -189,12 +185,9 @@ void testSendAsyncForMessagesWithTheSecondEventTooLargeForOneNewBatch() { List> messages = messagesList.stream().map((Function>) GenericMessage::new).collect(Collectors.toList()); - Mono mono = this.eventHubsTemplate.sendAsync(this.destination, messages, null).doOnError(ex -> { - System.out.println("do on Error" + ex.getMessage()); - ex.printStackTrace(); - }).doOnSuccess(t -> { - System.out.println("do on success:" + t); - }); + Mono mono = this.eventHubsTemplate.sendAsync(this.destination, messages, null) + .doOnError(ex -> LOGGER.log(LogLevel.VERBOSE, () -> "do on Error", ex)) + .doOnSuccess(t -> LOGGER.log(LogLevel.VERBOSE, () -> "do on success:" + t)); StepVerifier.create(mono) .verifyComplete(); verify(this.mockProducerClient, times(2)).send(any(EventDataBatch.class)); diff --git a/sdk/spring/spring-messaging-azure-servicebus/CHANGELOG.md b/sdk/spring/spring-messaging-azure-servicebus/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-messaging-azure-servicebus/CHANGELOG.md +++ b/sdk/spring/spring-messaging-azure-servicebus/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-messaging-azure-servicebus/pom.xml b/sdk/spring/spring-messaging-azure-servicebus/pom.xml index 5a8526bbca21..f0730a03f99b 100644 --- a/sdk/spring/spring-messaging-azure-servicebus/pom.xml +++ b/sdk/spring/spring-messaging-azure-servicebus/pom.xml @@ -13,7 +13,7 @@ com.azure.spring spring-messaging-azure-servicebus - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Messaging Azure Service Bus Spring Messaging Azure Service Bus @@ -38,19 +38,19 @@ com.azure.spring spring-messaging-azure - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-messaging-azure - 4.18.0-beta.1 + 4.19.0-beta.1 test-jar test com.azure azure-messaging-servicebus - 7.16.0 + 7.17.0 com.azure diff --git a/sdk/spring/spring-messaging-azure-storage-queue/CHANGELOG.md b/sdk/spring/spring-messaging-azure-storage-queue/CHANGELOG.md index 69bda720e930..aa68b8828d29 100644 --- a/sdk/spring/spring-messaging-azure-storage-queue/CHANGELOG.md +++ b/sdk/spring/spring-messaging-azure-storage-queue/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-messaging-azure-storage-queue/pom.xml b/sdk/spring/spring-messaging-azure-storage-queue/pom.xml index 8df3a2d0ca0f..55abb82ccc5d 100644 --- a/sdk/spring/spring-messaging-azure-storage-queue/pom.xml +++ b/sdk/spring/spring-messaging-azure-storage-queue/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-messaging-azure-storage-queue - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Messaging Azure Storage Queue Spring Messaging Azure Storage Queue @@ -37,12 +37,12 @@ com.azure.spring spring-messaging-azure - 4.18.0-beta.1 + 4.19.0-beta.1 com.azure.spring spring-messaging-azure - 4.18.0-beta.1 + 4.19.0-beta.1 test-jar test diff --git a/sdk/spring/spring-messaging-azure/CHANGELOG.md b/sdk/spring/spring-messaging-azure/CHANGELOG.md index 465a0ceac20d..1303275c337b 100644 --- a/sdk/spring/spring-messaging-azure/CHANGELOG.md +++ b/sdk/spring/spring-messaging-azure/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 4.18.0-beta.1 (Unreleased) +## 4.19.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,10 @@ ### Other Changes +## 4.18.0 (2024-05-07) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4180-2024-05-07) for more details. + ## 4.17.0 (2024-03-28) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#4170-2024-03-28) for more details. diff --git a/sdk/spring/spring-messaging-azure/pom.xml b/sdk/spring/spring-messaging-azure/pom.xml index c80a9aa147f5..92af809c1f82 100644 --- a/sdk/spring/spring-messaging-azure/pom.xml +++ b/sdk/spring/spring-messaging-azure/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-messaging-azure - 4.18.0-beta.1 + 4.19.0-beta.1 Spring Messaging Azure Spring Messaging Azure @@ -37,7 +37,7 @@ com.azure.spring spring-cloud-azure-service - 4.18.0-beta.1 + 4.19.0-beta.1 org.springframework diff --git a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/RequestRetryTestFactory.java b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/RequestRetryTestFactory.java index 0a3e792ec5fb..7fed3d1953bb 100644 --- a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/RequestRetryTestFactory.java +++ b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/RequestRetryTestFactory.java @@ -13,6 +13,8 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.UrlBuilder; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.storage.common.policy.RequestRetryOptions; import com.azure.storage.common.policy.RequestRetryPolicy; import reactor.core.Disposable; @@ -33,6 +35,8 @@ import static java.lang.StrictMath.pow; class RequestRetryTestFactory { + private static final ClientLogger LOGGER = new ClientLogger(RequestRetryTestFactory.class); + static final int RETRY_TEST_SCENARIO_RETRY_UNTIL_SUCCESS = 1; static final int RETRY_TEST_SCENARIO_RETRY_UNTIL_MAX_RETRIES = 2; @@ -219,7 +223,8 @@ public Mono send(HttpRequest request) { } }); while (!disposable.isDisposed()) { - System.out.println("Waiting for Flux to finish to prevent blocking on another thread exception"); + LOGGER.log(LogLevel.VERBOSE, + () -> "Waiting for Flux to finish to prevent blocking on another thread exception"); } if (retryTestDefaultData.compareTo(ByteBuffer.wrap(outputStream.toByteArray())) != 0) { throw new IllegalArgumentException(("Body not reset.")); diff --git a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/RetryTests.java b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/RetryTests.java index e0542697dd50..275488bc0ec6 100644 --- a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/RetryTests.java +++ b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/RetryTests.java @@ -5,6 +5,7 @@ import com.azure.core.exception.UnexpectedLengthException; import com.azure.core.http.HttpResponse; +import com.azure.core.util.logging.LogLevel; import com.azure.storage.common.policy.RequestRetryOptions; import com.azure.storage.common.policy.RetryPolicyType; import org.junit.jupiter.api.Test; @@ -32,7 +33,7 @@ public class RetryTests extends BlobTestBase { try { retryTestURL = new URL("https://" + RequestRetryTestFactory.RETRY_TEST_PRIMARY_HOST); } catch (MalformedURLException e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Failed to create URL for retry tests.", e); } } diff --git a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/DirectoryApiTests.java b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/DirectoryApiTests.java index 4a9a58e0cd8b..3c795ad37af9 100644 --- a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/DirectoryApiTests.java +++ b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/DirectoryApiTests.java @@ -1647,11 +1647,7 @@ public void createShareWithSmallTimeoutsFailForServiceClient() { return; } catch (Exception e) { // Test failed; wait before retrying - try { - Thread.sleep(retryDelayMillis); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } + sleepIfRunningAgainstService(retryDelayMillis); } } } diff --git a/sdk/vision/azure-ai-vision-imageanalysis/src/test/java/com/azure/ai/vision/imageanalysis/ImageAnalysisClientTestBase.java b/sdk/vision/azure-ai-vision-imageanalysis/src/test/java/com/azure/ai/vision/imageanalysis/ImageAnalysisClientTestBase.java index 12484368612e..c9179536e7f5 100644 --- a/sdk/vision/azure-ai-vision-imageanalysis/src/test/java/com/azure/ai/vision/imageanalysis/ImageAnalysisClientTestBase.java +++ b/sdk/vision/azure-ai-vision-imageanalysis/src/test/java/com/azure/ai/vision/imageanalysis/ImageAnalysisClientTestBase.java @@ -6,9 +6,11 @@ import java.io.File; import java.util.List; import java.util.Map.Entry; +import java.util.Objects; import com.azure.core.credential.KeyCredential; import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpHeaderName; import com.azure.core.http.HttpRequest; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; @@ -26,11 +28,15 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.azure.ai.vision.imageanalysis.*; import com.azure.ai.vision.imageanalysis.models.*; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; class ImageAnalysisClientTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(ImageAnalysisClientTestBase.class); final Boolean printResults = false; // Set to true to print results to console window @@ -64,8 +70,8 @@ private void createClient(String endpointEnvVar, String keyEnvVar, Boolean sync, endpoint = "https://fake-resource-name.cognitiveservices.azure.com"; } - String key = Configuration.getGlobalConfiguration().get(keyEnvVar); // Read real key from environment variable - if (key == null || keyEnvVar == "VISION_KEY_FAKE") { + String key = Configuration.getGlobalConfiguration().get(keyEnvVar); // Read real key from environment variable + if (key == null || Objects.equals(keyEnvVar, "VISION_KEY_FAKE")) { key = "00000000000000000000000000000000"; } @@ -105,7 +111,7 @@ protected void doAnalysis( ImageAnalysisOptions imageAnalysisOptions, // can be null RequestOptions requestOptions) { // can be null - Boolean fromUrl = imageSource.startsWith("http"); + boolean fromUrl = imageSource.startsWith("http"); Boolean genderNeutralCaption = null; List aspectRatios = null; @@ -209,7 +215,7 @@ protected void doAnalysisWithError( int expectedStatusCode, String expectedMessageContains) { - Boolean fromUrl = imageSource.startsWith("http"); + boolean fromUrl = imageSource.startsWith("http"); ImageAnalysisResult result = null; if (sync) { @@ -226,7 +232,7 @@ protected void doAnalysisWithError( options); } } catch (HttpResponseException e) { - System.out.println("Expected exception: " + e.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> "Expected exception: " + e.getMessage()); assertEquals(expectedStatusCode, e.getResponse().getStatusCode()); assertTrue(e.getMessage().contains(expectedMessageContains)); return; @@ -245,15 +251,15 @@ protected void doAnalysisWithError( options).block(); } } catch (HttpResponseException e) { - System.out.println("Expected exception: " + e.getMessage()); + LOGGER.log(LogLevel.VERBOSE, () -> "Expected exception: " + e.getMessage()); assertEquals(expectedStatusCode, e.getResponse().getStatusCode()); assertTrue(e.getMessage().contains(expectedMessageContains)); return; } } - System.out.println("Test should have thrown an exception, but it did not"); - assertTrue(false); + LOGGER.log(LogLevel.VERBOSE, () -> "Test should have thrown an exception, but it did not"); + fail(); } private static void validateAnalysisResult( @@ -372,7 +378,7 @@ private static void validateDenseCaptions(ImageAnalysisResult result) { // Do not include the check below. It's okay to have two identical dense captions since they have different bounding boxes. // assertFalse(otherDenseCaption.getText().equals(denseCaption.getText())); assertFalse( - otherDenseCaption.getBoundingBox().getX() == denseCaption.getBoundingBox().getX() + otherDenseCaption.getBoundingBox().getX() == denseCaption.getBoundingBox().getX() && otherDenseCaption.getBoundingBox().getY() == denseCaption.getBoundingBox().getY() && otherDenseCaption.getBoundingBox().getHeight() == denseCaption.getBoundingBox().getHeight() && otherDenseCaption.getBoundingBox().getWidth() == denseCaption.getBoundingBox().getWidth()); @@ -389,7 +395,7 @@ private static void validateObjects(ObjectsResult objectsResult) { assertNotNull(objectsResult); assertTrue(objectsResult.getValues().size() > 1); - Boolean found1 = false; + boolean found1 = false; for (DetectedObject object : objectsResult.getValues()) { assertNotNull(object); assertNotNull(object.getTags()); @@ -401,7 +407,7 @@ private static void validateObjects(ObjectsResult objectsResult) { assertTrue(tag.getConfidence() > 0.0); assertTrue(tag.getConfidence() < 1.0); // We expect to see this in the list of objects - if (tag.getName().toLowerCase().equals("person")) { + if (tag.getName().equalsIgnoreCase("person")) { found1 = true; } } @@ -431,17 +437,17 @@ private static void validateTags(TagsResult tagsResult) { assertNotNull(tagsResult.getValues()); assertTrue(tagsResult.getValues().size() > 1); - Boolean found1 = false, found2 = false; + boolean found1 = false, found2 = false; for (DetectedTag tag : tagsResult.getValues()) { assertNotNull(tag.getName()); assertFalse(tag.getName().isEmpty()); assertTrue(tag.getConfidence() > 0.0); assertTrue(tag.getConfidence() < 1.0); // We expect to see both of these in the list of tags - if (tag.getName().toLowerCase().equals("person")) { + if (tag.getName().equalsIgnoreCase("person")) { found1 = true; } - if (tag.getName().toLowerCase().equals("laptop")) { + if (tag.getName().equalsIgnoreCase("laptop")) { found2 = true; } } @@ -458,7 +464,7 @@ private static void validateTags(TagsResult tagsResult) { private static void validatePeople(ImageAnalysisResult result) { assertNotNull(result.getPeople()); - assertTrue(result.getPeople().getValues().size() > 0); + assertFalse(result.getPeople().getValues().isEmpty()); for (DetectedPerson person : result.getPeople().getValues()) { assertTrue(person.getConfidence() > 0.0); @@ -487,13 +493,13 @@ private static void validateSmartCrops(ImageAnalysisResult result, List assertNotNull(result.getSmartCrops()); List listCropRegions = result.getSmartCrops().getValues(); if (aspectRatios == null) { - assertTrue(listCropRegions.size() == 1); + assertEquals(1, listCropRegions.size()); assertTrue(listCropRegions.get(0).getAspectRatio() >= 0.5); assertTrue(listCropRegions.get(0).getAspectRatio() <= 2.0); } else { - assertTrue(listCropRegions.size() == aspectRatios.size()); + assertEquals(listCropRegions.size(), aspectRatios.size()); for (int i = 0; i < listCropRegions.size(); i++) { - assertTrue(listCropRegions.get(i).getAspectRatio() == aspectRatios.get(i)); + assertEquals(listCropRegions.get(i).getAspectRatio(), aspectRatios.get(i)); assertTrue(listCropRegions.get(0).getAspectRatio() >= 0.75); assertTrue(listCropRegions.get(0).getAspectRatio() <= 1.8); } @@ -537,20 +543,20 @@ private static void validateRead(ImageAnalysisResult result) { // Do some validations on the first line DetectedTextLine line = lines.get(0); assertNotNull(line); - assertTrue(line.getText().equals("Sample text")); + assertEquals("Sample text", line.getText()); List polygon = line.getBoundingPolygon(); assertNotNull(polygon); assertEquals(4, polygon.size()); - for (int i = 0; i < polygon.size(); i++) { - assertTrue(polygon.get(i).getX() > 0); - assertTrue(polygon.get(i).getY() > 0); + for (ImagePoint imagePoint : polygon) { + assertTrue(imagePoint.getX() > 0); + assertTrue(imagePoint.getY() > 0); } // Do some verifications on the 3rd line line = lines.get(2); assertNotNull(line); - assertTrue(line.getText().equals("123 456")); + assertEquals("123 456", line.getText()); List words = line.getWords(); assertNotNull(words); @@ -558,111 +564,111 @@ private static void validateRead(ImageAnalysisResult result) { DetectedTextWord word = words.get(1); assertNotNull(word); - assertTrue(word.getText().equals("456")); + assertEquals("456", word.getText()); assertTrue(word.getConfidence() > 0.0); assertTrue(word.getConfidence() < 1.0); polygon = word.getBoundingPolygon(); assertNotNull(polygon); assertEquals(4, polygon.size()); - for (int i = 0; i < polygon.size(); i++) { - assertTrue(polygon.get(i).getX() > 0); - assertTrue(polygon.get(i).getY() > 0); + for (ImagePoint imagePoint : polygon) { + assertTrue(imagePoint.getX() > 0); + assertTrue(imagePoint.getY() > 0); } } private static void printHttpRequestAndResponse(Response response) { // Print HTTP request details to console HttpRequest request = response.getRequest(); - System.out.println(" HTTP request method: " + request.getHttpMethod()); - System.out.println(" HTTP request URL: " + request.getUrl()); - System.out.println(" HTTP request headers: "); + LOGGER.log(LogLevel.VERBOSE, () -> " HTTP request method: " + request.getHttpMethod()); + LOGGER.log(LogLevel.VERBOSE, () -> " HTTP request URL: " + request.getUrl()); + LOGGER.log(LogLevel.VERBOSE, () -> " HTTP request headers: "); request.getHeaders().forEach(header -> { - System.out.println(" " + header.getName() + ": " + header.getValue()); + LOGGER.log(LogLevel.VERBOSE, () -> " " + header.getName() + ": " + header.getValue()); }); - if (request.getHeaders().getValue("content-type").contains("application/json")) { - System.out.println(" HTTP request body: " + request.getBodyAsBinaryData().toString()); + if (request.getHeaders().getValue(HttpHeaderName.CONTENT_TYPE).contains("application/json")) { + LOGGER.log(LogLevel.VERBOSE, () -> " HTTP request body: " + request.getBodyAsBinaryData().toString()); } // Print HTTP response details to console - System.out.println(" HTTP response status code: " + response.getStatusCode()); - System.out.println(" HTTP response headers: "); + LOGGER.log(LogLevel.VERBOSE, () -> " HTTP response status code: " + response.getStatusCode()); + LOGGER.log(LogLevel.VERBOSE, () -> " HTTP response headers: "); response.getHeaders().forEach(header -> { - System.out.println(" " + header.getName() + ": " + header.getValue()); + LOGGER.log(LogLevel.VERBOSE, () -> " " + header.getName() + ": " + header.getValue()); }); } private static void printAnalysisResults(String testName, ImageAnalysisResult result) { - System.out.println(" ******************** TEST NAME: " + testName + " ******************** "); + LOGGER.log(LogLevel.VERBOSE, () -> " ******************** TEST NAME: " + testName + " ******************** "); try { - System.out.println(" Image height: " + result.getMetadata().getHeight()); - System.out.println(" Image width: " + result.getMetadata().getWidth()); - System.out.println(" Model version: " + result.getModelVersion()); + LOGGER.log(LogLevel.VERBOSE, () -> " Image height: " + result.getMetadata().getHeight()); + LOGGER.log(LogLevel.VERBOSE, () -> " Image width: " + result.getMetadata().getWidth()); + LOGGER.log(LogLevel.VERBOSE, () -> " Model version: " + result.getModelVersion()); if (result.getCaption() != null) { - System.out.println(" Caption:"); - System.out.println(" \"" + result.getCaption().getText() + "\", Confidence " + LOGGER.log(LogLevel.VERBOSE, () -> " Caption:"); + LOGGER.log(LogLevel.VERBOSE, () -> " \"" + result.getCaption().getText() + "\", Confidence " + String.format("%.4f", result.getCaption().getConfidence())); } if (result.getDenseCaptions() != null) { - System.out.println(" Dense Captions:"); + LOGGER.log(LogLevel.VERBOSE, () -> " Dense Captions:"); for (DenseCaption denseCaption : result.getDenseCaptions().getValues()) { - System.out.println(" \"" + denseCaption.getText() + "\", Bounding box " + LOGGER.log(LogLevel.VERBOSE, () -> " \"" + denseCaption.getText() + "\", Bounding box " + denseCaption.getBoundingBox() + ", Confidence " + String.format("%.4f", denseCaption.getConfidence())); } } if (result.getObjects() != null) { - System.out.println(" Objects:"); + LOGGER.log(LogLevel.VERBOSE, () -> " Objects:"); for (DetectedObject detectedObject : result.getObjects().getValues()) { - System.out.println(" \"" + detectedObject.getTags().get(0).getName() + "\", Bounding box " + LOGGER.log(LogLevel.VERBOSE, () -> " \"" + detectedObject.getTags().get(0).getName() + "\", Bounding box " + detectedObject.getBoundingBox() + ", Confidence " + String.format("%.4f", detectedObject.getTags().get(0).getConfidence())); } } if (result.getTags() != null) { - System.out.println(" Tags:"); + LOGGER.log(LogLevel.VERBOSE, () -> " Tags:"); for (DetectedTag tag : result.getTags().getValues()) { - System.out.println(" \"" + tag.getName() + "\", Confidence " + LOGGER.log(LogLevel.VERBOSE, () -> " \"" + tag.getName() + "\", Confidence " + String.format("%.4f", tag.getConfidence())); } } if (result.getPeople() != null) { - System.out.println(" People:"); + LOGGER.log(LogLevel.VERBOSE, () -> " People:"); for (DetectedPerson person : result.getPeople().getValues()) { - System.out.println(" Bounding box " + person.getBoundingBox() + LOGGER.log(LogLevel.VERBOSE, () -> " Bounding box " + person.getBoundingBox() + ", Confidence " + String.format("%.4f", person.getConfidence())); } } if (result.getSmartCrops() != null) { - System.out.println(" Crop Suggestions:"); + LOGGER.log(LogLevel.VERBOSE, () -> " Crop Suggestions:"); for (CropRegion cropRegion : result.getSmartCrops().getValues()) { - System.out.println(" Aspect ratio " + cropRegion.getAspectRatio() + LOGGER.log(LogLevel.VERBOSE, () -> " Aspect ratio " + cropRegion.getAspectRatio() + ": Bounding box " + cropRegion.getBoundingBox()); } } if (result.getRead() != null) { - System.out.println(" Read:"); + LOGGER.log(LogLevel.VERBOSE, () -> " Read:"); for (DetectedTextLine line : result.getRead().getBlocks().get(0).getLines()) { - System.out.println(" Line: '" + line.getText() + LOGGER.log(LogLevel.VERBOSE, () -> " Line: '" + line.getText() + "', Bounding polygon " + line.getBoundingPolygon()); for (DetectedTextWord word : line.getWords()) { - System.out.println(" Word: '" + word.getText() + LOGGER.log(LogLevel.VERBOSE, () -> " Word: '" + word.getText() + "', Bounding polygon " + word.getBoundingPolygon() + ", Confidence " + String.format("%.4f", word.getConfidence())); } } } } catch (Exception e) { - e.printStackTrace(); + LOGGER.log(LogLevel.VERBOSE, () -> "Error printing analysis results", e); } } } diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/GroupMessageTests.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/GroupMessageTests.java index dd6fc1ad5aff..316e35d9a0db 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/GroupMessageTests.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/GroupMessageTests.java @@ -5,6 +5,8 @@ import com.azure.core.test.annotation.DoNotRecord; import com.azure.core.util.BinaryData; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.messaging.webpubsub.client.models.SendMessageFailedException; import com.azure.messaging.webpubsub.client.models.SendToGroupOptions; import com.azure.messaging.webpubsub.client.models.WebPubSubDataFormat; @@ -18,6 +20,7 @@ import java.util.concurrent.TimeUnit; public class GroupMessageTests extends TestBase { + private static final ClientLogger LOGGER = new ClientLogger(GroupMessageTests.class); private static final String HELLO = "hello"; @@ -178,9 +181,10 @@ public void testSendMessagePerformance() throws InterruptedException { final long endNanoReceive = System.nanoTime(); // about 800 ms for 1k messages - System.out.println("send takes milliseconds: " + (endNanoSend - beginNano) / 1E6); + LOGGER.log(LogLevel.VERBOSE, () -> "send takes milliseconds: " + (endNanoSend - beginNano) / 1E6); // about 1 second for 1k messages - System.out.println("send and receive takes milliseconds: " + (endNanoReceive - beginNano) / 1E6); + LOGGER.log(LogLevel.VERBOSE, + () -> "send and receive takes milliseconds: " + (endNanoReceive - beginNano) / 1E6); } finally { client.stop(); }